Last active
January 28, 2020 19:25
-
-
Save gajeam/9b05034643d36d5730979935e098f18d to your computer and use it in GitHub Desktop.
Can you track the delirious ducks?
This file contains 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 random | |
DIR_UP = 'u' | |
DIR_RIGHT = 'r' | |
DIR_DOWN = 'd' | |
DIR_LEFT = 'l' | |
START_POS = (1, 1) #(x_coordinate, y_coordinate) | |
POND = (3, 3) #(pond_width, pond_height) | |
def available_moves(pond, duck_pos): | |
moves = [DIR_UP, DIR_RIGHT, DIR_DOWN, DIR_LEFT] | |
if duck_pos[0] == 0: | |
moves.remove(DIR_LEFT) | |
if duck_pos[0] == pond[0] - 1: | |
moves.remove(DIR_RIGHT) | |
if duck_pos[1] == 0: | |
moves.remove(DIR_UP) | |
if duck_pos[1] == pond[1] - 1: | |
moves.remove(DIR_DOWN) | |
return moves | |
def move_duck(pond, duck_pos): | |
possible_moves = available_moves(POND, duck_pos) | |
move = random.choice(possible_moves) | |
if (move == DIR_UP): | |
duck_pos = (duck_pos[0], duck_pos[1] - 1) | |
elif (move == DIR_LEFT): | |
duck_pos = (duck_pos[0] - 1, duck_pos[1]) | |
elif (move == DIR_DOWN): | |
duck_pos = (duck_pos[0], duck_pos[1] + 1) | |
elif (move == DIR_RIGHT): | |
duck_pos = (duck_pos[0] + 1, duck_pos[1]) | |
return duck_pos | |
def run_simulation(num_ducks): | |
ducks = [] | |
for x in range(num_ducks): | |
ducks.append(START_POS) | |
move_count = 0 | |
while True: | |
move_count += 1 | |
# Update the movement of the ducks | |
for i in range(len(ducks)): | |
ducks[i] = move_duck(POND, ducks[i]) | |
# Check to see whether they're all the same value | |
if (len(set(ducks)) == 1): | |
return move_count | |
def calculate_average(num_ducks=2): | |
simulation_count = 1000 | |
simulation_values = [] | |
for x in range(simulation_count): | |
simulation_values.append(run_simulation(num_ducks)) | |
return sum(simulation_values)/ len(simulation_values) | |
print("Two ducks in a pond:", calculate_average()) | |
print("Three ducks in a pond:", calculate_average(3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment