|
| 1 | +""" |
| 2 | +Project Euler problem 205: |
| 3 | +
|
| 4 | +
|
| 5 | +Peter has nine four-sided (pyramidal) dice, each with faces numbered 1, 2, 3, 4. |
| 6 | +Colin has six six-sided (cubic) dice, each with faces numbered 1, 2, 3, 4, 5, 6. |
| 7 | +
|
| 8 | +Peter and Colin roll their dice and compare totals: the highest total wins. The result |
| 9 | +is a draw if the totals are equal. |
| 10 | +
|
| 11 | +What is the probability that Pyramidal Pete beats Cubic Colin? Give your answer rounded |
| 12 | +to seven decimal places in the form 0.abcdefg |
| 13 | +""" |
| 14 | + |
| 15 | +from itertools import product |
| 16 | + |
| 17 | + |
| 18 | +def probability_of_sums( |
| 19 | + dice_min: int = 1, dice_max: int = 6, dice_number: int = 6 |
| 20 | +) -> (list, list): |
| 21 | + """ |
| 22 | + Returns the list of possible sums and their probabilities of dice_number dices with |
| 23 | + numbers from dice_min to dice_max |
| 24 | + """ |
| 25 | + sums = [] |
| 26 | + counter = [] |
| 27 | + for dices in product(range(dice_min, dice_max + 1), repeat=dice_number): |
| 28 | + s = sum(dices) |
| 29 | + if s not in sums: |
| 30 | + sums.append(s) |
| 31 | + counter.append(1) |
| 32 | + else: |
| 33 | + idx = sums.index(s) |
| 34 | + counter[idx] += 1 |
| 35 | + total = sum(counter) |
| 36 | + probability = [_t / total for _t in counter] |
| 37 | + return sums, probability |
| 38 | + |
| 39 | + |
| 40 | +def solution(): |
| 41 | + """ |
| 42 | + Returns the probability of Peter winning in dice game with nine four-sided |
| 43 | + dice (1, 2, 3, 4 points) against Colin who has six six-sided dice (1, 2, 3, 4, 5, |
| 44 | + 6). Winner of a match is who has more total points. |
| 45 | + Algorithm calculates the possible point sums for each player and their |
| 46 | + probabilities. Peter's probability to win is summed up from all the permutations |
| 47 | + where he has more points than Colin. |
| 48 | +
|
| 49 | + >>> solution() |
| 50 | + 0.5731441 |
| 51 | + """ |
| 52 | + peter_wins = 0 |
| 53 | + colin_wins = 0 |
| 54 | + draw = 0 |
| 55 | + for s_peter, p_peter in zip( |
| 56 | + *probability_of_sums(dice_min=1, dice_max=4, dice_number=9) |
| 57 | + ): |
| 58 | + for s_colin, p_colin in zip( |
| 59 | + *probability_of_sums(dice_min=1, dice_max=6, dice_number=6) |
| 60 | + ): |
| 61 | + p_branch = p_peter * p_colin |
| 62 | + if s_peter > s_colin: |
| 63 | + peter_wins += p_branch |
| 64 | + elif s_colin > s_peter: |
| 65 | + colin_wins += p_branch |
| 66 | + else: |
| 67 | + draw += p_branch |
| 68 | + |
| 69 | + return round(peter_wins, 7) |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + print(solution()) |
0 commit comments