Anonymous
Input is a dictionary with the number on the side with a probability in percentage. Calling the function should return the number that was rolled.
I will create a list object to capture all the numbers on all sides of the dice and maintain a cumulative sum of all the sides adding one after the other. I then generate a random number and return the key for which the random number is greater than the cumulative sum for the first time when iterating over the cumulative sum numbers in order.
def roll_a_dice(prob: dict):
if np.sum(prob.values()) != 1:
raise InputError
sorted_keys = sorted(prob.keys())
sorted_values = []
cumul_sum = []
for key in sorted_keys:
sorted_values.append(prob[key])
if len(cumul_sum) == 0:
cumul_sum.append(prob[key])
else:
latest_sum = cumul_sum.pop()
cumul_sum.append(latest_sum)
cumul_sum.append(latest_sum + prob[key])
rand_val = np.random.random()
for i, cum_val in enumerate(cumul_sum):
if rand_val > cum_val:
continue
else:
return sorted_keys[i]