Last active
July 1, 2022 05:09
-
-
Save ankushKun/f729f1b868133faf6b9e2650ae60f962 to your computer and use it in GitHub Desktop.
100 Prisoners Riddle Simulation
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 random | |
# Increasing this will have a drastic effect of total running time | |
NUM_PRISONERS = 100 | |
BOXES_ALLOWED = NUM_PRISONERS // 2 | |
##### CONFIG ##### | |
# Number of simulations to run | |
# It will run 100 times with 'NUM_PRISONERS' in each run | |
# Doesnot have much effect in total running time | |
NUM_SIMS = 1000 | |
# Prints info such % completion of the simulation and | |
# number of prisoners who found thir numbered slip in each sim | |
OUTPUT = True | |
lives_random = 0 | |
lives_loop = 0 | |
for s in range(NUM_SIMS): | |
# Create a list of numbers for the prisoners | |
PRISONER_NUMBERS = [n for n in range(1,NUM_PRISONERS+1)] | |
class box: | |
def __init__(self,count): | |
self.label = count | |
self.slip = PRISONER_NUMBERS.pop(random.randint(0,len(PRISONER_NUMBERS)-1)) | |
# Create a list of boxes and add randomly numbered slips in them | |
BOXES = [] | |
for count in range(1,NUM_PRISONERS+1): | |
BOXES.append(box(count)) | |
random_count = 0 | |
loop_count = 0 | |
for my_prisoner_number in range(1,NUM_PRISONERS+1): | |
# Pick randomly to find slip | |
boxes_copy = BOXES.copy() | |
for _ in range(BOXES_ALLOWED): | |
picked_box = boxes_copy.pop(random.randint(0,len(boxes_copy)-1)) | |
if picked_box.slip == my_prisoner_number: | |
random_count += 1 | |
break | |
# Go in loop | |
starting_box = BOXES[my_prisoner_number - 1] | |
for _ in range(BOXES_ALLOWED): | |
if starting_box.slip == my_prisoner_number: | |
loop_count += 1 | |
break | |
else: | |
starting_box = BOXES[starting_box.slip - 1] | |
if random_count == NUM_PRISONERS: lives_random += 1 | |
if loop_count == NUM_PRISONERS: lives_loop += 1 | |
if OUTPUT: | |
precentage_complete = f"{str(round(((s+1)/NUM_SIMS)*100,1)).zfill(5)}%" | |
live_str = ' 🥳' | |
dead_str = '💀 ' | |
print(f"[{precentage_complete}]\t\tRandom : {live_str if random_count==NUM_PRISONERS else dead_str} ({str(random_count).zfill(3)})\t\tLoop : {live_str if loop_count==NUM_PRISONERS else dead_str} ({str(loop_count).zfill(3)})") | |
# Calculate probability | |
prob_random = (lives_random/NUM_SIMS)*100 | |
prob_loop = (lives_loop/NUM_SIMS)*100 | |
print("---------------------------------------------------------") | |
print(f"Probability Random : {prob_random}%\tProbability Loop : {prob_loop}%") | |
print("---------------------------------------------------------") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment