Skip to content

Instantly share code, notes, and snippets.

@PatWg
Created November 11, 2023 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PatWg/ee6a1d56d0c57505f51706a363674d8e to your computer and use it in GitHub Desktop.
Save PatWg/ee6a1d56d0c57505f51706a363674d8e to your computer and use it in GitHub Desktop.
ICC 23-24: Simulation du problème des 100 prisonniers avec des dataclass
from typing import List
from random import shuffle
from dataclasses import dataclass
@dataclass
class Box:
number: int
key_inside: int
@dataclass
class Prisoner:
number: int
found_key: bool = False
def look_for_key(self, boxes: List[Box]) -> None:
"""
This method simulates a prisoner looking for his key.
:param boxes: List of boxes that are in the room
"""
attempts_left: int = 50
next_box: int = self.number
while attempts_left > 0:
key_inside = self.open_box(boxes=boxes, box_number=next_box)
if key_inside == self.number:
self.found_key = True
attempts_left -= 1
next_box = key_inside
def open_box(self, boxes: List[Box], box_number: int) -> int:
"""
This method simulates a prisoner opening the box with number `box_number`.
:param boxes: List of boxes that are in the room
:param box_number: The number of the next box to open
:return: The key found inside the box with number `box_number`
"""
for box in boxes:
if box.number == box_number:
return box.key_inside
@dataclass
class Simulation:
prisoners: List[Prisoner]
boxes: List[Box]
def run(self) -> None:
"""
This method starts a simulation.
"""
for prisoner in self.prisoners:
prisoner.look_for_key(self.boxes)
def is_successful(self) -> bool:
"""
This method verifies if a simulation is successful or not.
:return: True if all prisoners found their keys, False otherwise
"""
for prisoner in self.prisoners:
if not prisoner.found_key:
return False
return True
def create_simulation() -> Simulation:
nb_prisoners: int = 100
randomized_keys: List[int] = list(range(nb_prisoners))
shuffle(randomized_keys)
prisoners: List[Prisoner] = []
boxes: List[Box] = []
for i in range(nb_prisoners):
prisoners.append(Prisoner(number=i, found_key=False))
boxes.append(Box(number=i, key_inside=randomized_keys.pop(0)))
return Simulation(prisoners=prisoners, boxes=boxes)
success_count: int = 0
nb_simulations: int = 1000
for _ in range(nb_simulations):
simulation: Simulation = create_simulation()
simulation.run()
if simulation.is_successful():
success_count += 1
print(f"{success_count} simulations réussies sur {nb_simulations}.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment