Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from random import randint
- def sailor_walk(border, x, y):
- rnd = randint(1, 4)
- if rnd == 1: # Up
- y += 1
- elif rnd == 2: # Down
- y -= 1
- elif rnd == 3: # Left
- x -= 1
- else: # Right
- x += 1
- return x, y
- def new_sailor(x, y):
- x = 0
- y = 0
- return x, y
- def check_sailor_fell(border, x, y):
- if abs(x) > border or abs(y) > border:
- return True
- return False
- def print_result(i, num_sailors, sailors_fell):
- if sailors_fell > 0:
- print(f"({i+1}) Out of {num_sailors} drunk sailors, "
- f"{sailors_fell} ({((sailors_fell/num_sailors)*100):.2f}%) "
- f"fell into the water")
- else:
- print(f"Out of {num_sailors} drunken sailors, no sailors fell!")
- def run(sailors_fell, x, y, rep, grid_size, num_steps, num_sailors):
- for i in range(num_sailors):
- x, y = new_sailor(x, y)
- for j in range(num_steps):
- x, y = sailor_walk(grid_size, x, y)
- if check_sailor_fell(grid_size, x, y):
- sailors_fell += 1
- break
- print_result(rep, num_sailors, sailors_fell)
- return sailors_fell
- sailors_fell = 0
- x = 0
- y = 0
- grid_size = int(input("Enter the size: "))
- num_steps = int(input("Enter the number of steps: "))
- num_sailors = int(input("Enter the number of sailors: "))
- min_sailors_fell = 100
- max_sailors_fell = 0
- # Find how many iterations it will take for 1/3 of the sailors to fall
- i = 0
- curr_sailors_fell = 0
- while(curr_sailors_fell < 30):
- curr_sailors_fell = run(sailors_fell, x, y, i,
- grid_size, num_steps, num_sailors)
- i += 1
- # # Find the min and max sailors fell in n iterations
- # for i in range(10000):
- # curr_sailors_fell = run(sailors_fell, x, y, i,
- # grid_size, num_steps, num_sailors)
- # if curr_sailors_fell < min_sailors_fell:
- # min_sailors_fell = curr_sailors_fell
- # elif curr_sailors_fell > max_sailors_fell:
- # max_sailors_fell = curr_sailors_fell
- # print(f"Min sailors fell: {min_sailors_fell} "
- # f"({(min_sailors_fell/num_sailors)*100:.2f}%)")
- # print(f"Max sailors fell: {max_sailors_fell} "
- # f"({(max_sailors_fell/num_sailors)*100:.2f}%)")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement