Created
March 19, 2017 18:16
-
-
Save ShiangYong/c4db131c18b171e4c857dc9327c0f412 to your computer and use it in GitHub Desktop.
Monte Carlo code to solve the Four Square Ranches (Riddler Classic), https://fivethirtyeight.com/features/can-you-find-the-honest-prince/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import time | |
import matplotlib.pyplot as plt | |
def isConvex(dx, dy): | |
for j in range(4): | |
if dx[j]*dy[(j+1) % 4] < dy[j]*dx[(j+1) % 4]: | |
return False | |
return True | |
def runSimulation(runs): | |
total = 0 | |
init_time = time.time() | |
for j in range(runs): | |
# generate coordinates for four point | |
coordX = np.random.random_sample(4) | |
coordX[1:3] *= -1.0 # flip X coordinates | |
coordY = np.random.random_sample(4) | |
coordY[2:4] *= -1.0 # flip Y coordinates | |
# plot points to check code correctness | |
# plt.scatter(coordX, coordY) | |
# plt.plot([-1, 1], [0, 0]) | |
# plt.plot([0, 0], [-1, 1]) | |
# plt.show() | |
total += isConvex(np.roll(coordX, -1) - coordX, np.roll(coordY, -1) - coordY) | |
print("N=", runs, " convex prob =", total/runs, | |
' run time (hr) = {0:.3f}'.format((time.time() - init_time)/3600.0)) | |
return total | |
# ===== MAIN PROGRAM ===== | |
runSimulation(200*1000*1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment