Skip to content

Instantly share code, notes, and snippets.

@bharddwaj
Created January 8, 2020 12:12
Show Gist options
  • Save bharddwaj/048c9416133165b196dfd62a3d48b465 to your computer and use it in GitHub Desktop.
Save bharddwaj/048c9416133165b196dfd62a3d48b465 to your computer and use it in GitHub Desktop.
Page 17 problem in Introduction to Probability by Grinstead and Snell
import random
def SingleDimensionWalk(x,count):
'''
Write a program to simulate a random walk in one dimension starting at 0.
Have your program print out the lengths of the times between returns to the starting point (returns to 0).
'''
if random.randint(0,1):
x+=1
else:
x-=1
while x!= 0:
count += 1
if random.randint(0,1):
x += 1
else:
x-=1
#print(f"{x}")
#print(f"{x}")
return count
def TwoDimensionWalk(x,y,count):
'''
Write a program to simulate a random walk in two dimensions starting at (0,0).
'''
a = random.randint(0,3)
if a == 0:
x += 1
elif a == 1:
x -= 1
elif a == 2:
y += 1
else:
#a == 3
y -= 1
while x!=0 or y!=0: #if either x or y are not equal to 0 keep going
count += 1
a = random.randint(0,3)
if a == 0:
x += 1
elif a == 1:
x -= 1
elif a == 2:
y += 1
else:
#a == 3
y -= 1
#print(f"({x},{y})")
#print(f"({x},{y})")
return count
#TwoDimensionWalk(0,0,0)
walking_distances_2d = []
walking_distances = []
for i in range(10):
walking_distances.append(SingleDimensionWalk(0,0))
walking_distances_2d.append(TwoDimensionWalk(0,0,0))
print(f"Max Walking Distance: {max(walking_distances)}")
print(f"Max Walking Distance 2D: {max(walking_distances_2d)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment