Skip to content

Instantly share code, notes, and snippets.

@dmadisetti
Last active August 29, 2015 14:17
Show Gist options
  • Save dmadisetti/6cabdaa41e18646e9f70 to your computer and use it in GitHub Desktop.
Save dmadisetti/6cabdaa41e18646e9f70 to your computer and use it in GitHub Desktop.
Monte Carlo to determine number of steps it takes an ant to return around a prism
import random
global pointer, A
class State:
# Keep paths with obj scope
def __init__(self):
self.paths = []
# Path class for tidiness
class Path():
def __init__(self, node, weight):
self.weight = weight
self.node = node
# Potentially expand to ensure all paths add to 1
# But I think we're good
def newPath(self, node, weight):
self.paths.append(self.Path(node,weight))
def move(self):
global pointer
r = random.random()
runningWeight = 0
for path in self.paths:
runningWeight += path.weight
if runningWeight >= r:
pointer = path.node
return
def init():
global A
# Ant starting place
A = State()
# Symmetrical verticies on same triangular face
B = State()
# Vertice across prism
C = State()
# Symmetrical verticies on same opposite face
D = State()
# Add paths
A.newPath(B, 2.0/3)
A.newPath(C, 1.0/3)
B.newPath(A, 1.0/3)
B.newPath(B, 1.0/3)
B.newPath(D, 1.0/3)
C.newPath(D, 2.0/3)
C.newPath(A, 1.0/3)
D.newPath(C, 1.0/3)
D.newPath(B, 1.0/3)
D.newPath(D, 1.0/3)
def run():
global pointer, A
moves = {}
for i in range(1,1000):
random.seed(i) # New rand
A.move() # Sets pointer from A
n = 1
# Move until pointer is set back to A
while pointer != A:
pointer.move()
n+=1
# Add to hash to tabulate
if n in moves:
moves[n] += 1
else:
moves[n] = 1
#Let's set our results
print moves
def main():
init()
run()
# Set er off
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment