generated from mwc/lab_encryption
72 lines
2.4 KiB
Python
72 lines
2.4 KiB
Python
from die import Die
|
|
from tqdm import tqdm
|
|
|
|
class FiveDice:
|
|
def __init__(self):
|
|
self.dice = [Die() for number in range(5)]
|
|
|
|
def roll(self):
|
|
for die in self.dice:
|
|
die.roll()
|
|
return self.faces()
|
|
|
|
def faces(self):
|
|
return [die.face for die in self.dice]
|
|
|
|
def all_ones(self):
|
|
for face in self.faces():
|
|
if face != 1:
|
|
return False
|
|
return True
|
|
|
|
def findn(self,nofakind):
|
|
""" dice.findn(n) determines whether there are at least n of a kind in the roll and returns true if so and returns false otherwise. """
|
|
nmuch = {} # create an empty dictionary to associate each face rolled with its frequency
|
|
for die in dice.faces(): # go through each dice rolled
|
|
if die in nmuch: # check if the dictionary already has the face included, and if so increase its frequency by 1
|
|
nmuch[die] += 1
|
|
if nmuch[die]==nofakind: # each time the dictionary is updated, check if the desired frequency has been achieved, and if so return true
|
|
return True
|
|
else:
|
|
nmuch[die] = 1 # add the face to the dictionary with frequency 1 if it has not already been included
|
|
return False # if the desired frequency was never achieved, return false
|
|
|
|
def is_three_of_a_kind(self):
|
|
""" I didn't read the assignment carefully... this should return the result of dice.findn(3) """
|
|
return dice.findn(3)
|
|
|
|
def is_four_of_a_kind(self):
|
|
""" same issue... returns the result of dice.findn(4) """
|
|
return dice.findn(4)
|
|
|
|
dice = FiveDice()
|
|
successes = 0
|
|
trials = 1000000
|
|
|
|
print("THIS IS THE ORIGINAL SIMULATION:")
|
|
for trial in tqdm(range(trials)):
|
|
dice.roll()
|
|
if dice.all_ones():
|
|
successes += 1
|
|
print(successes/trials)
|
|
|
|
print("\n")
|
|
print("THIS IS TO CHECK IF THERE ARE AT LEAST THREE OF A KIND:")
|
|
successes = 0
|
|
for trial in tqdm(range(trials)):
|
|
dice.roll()
|
|
# if dice.findn(3):
|
|
if dice.is_three_of_a_kind():
|
|
successes += 1
|
|
print(successes/trials)
|
|
|
|
print("\n")
|
|
print("THIS IS TO CHECK IF THERE ARE AT LEAST FOUR OF A KIND:")
|
|
successes = 0
|
|
for trial in tqdm(range(trials)):
|
|
dice.roll()
|
|
# if dice.findn(4):
|
|
if dice.is_four_of_a_kind():
|
|
successes += 1
|
|
print(successes/trials)
|