|
| 1 | +""" |
| 2 | +Project Euler Problem 493: https://projecteuler.net/problem=493 |
| 3 | +
|
| 4 | +70 coloured balls are placed in an urn, 10 for each of the seven rainbow colours. |
| 5 | +What is the expected number of distinct colours in 20 randomly picked balls? |
| 6 | +Give your answer with nine digits after the decimal point (a.bcdefghij). |
| 7 | +
|
| 8 | +----- |
| 9 | +
|
| 10 | +This combinatorial problem can be solved by decomposing the problem into the |
| 11 | +following steps: |
| 12 | +1. Calculate the total number of possible picking cominations |
| 13 | +[combinations := binom_coeff(70, 20)] |
| 14 | +2. Calculate the number of combinations with one colour missing |
| 15 | +[missing := binom_coeff(60, 20)] |
| 16 | +3. Calculate the probability of one colour missing |
| 17 | +[missing_prob := missing / combinations] |
| 18 | +4. Calculate the probability of no colour missing |
| 19 | +[no_missing_prob := 1 - missing_prob] |
| 20 | +5. Calculate the expected number of distinct colours |
| 21 | +[expected = 7 * no_missing_prob] |
| 22 | +
|
| 23 | +References: |
| 24 | +- https://en.wikipedia.org/wiki/Binomial_coefficient |
| 25 | +""" |
| 26 | + |
| 27 | +import math |
| 28 | + |
| 29 | +BALLS_PER_COLOUR = 10 |
| 30 | +NUM_COLOURS = 7 |
| 31 | +NUM_BALLS = BALLS_PER_COLOUR * NUM_COLOURS |
| 32 | + |
| 33 | + |
| 34 | +def solution(num_picks: int = 20) -> str: |
| 35 | + """ |
| 36 | + Calculates the expected number of distinct colours |
| 37 | +
|
| 38 | + >>> solution(10) |
| 39 | + '5.669644129' |
| 40 | +
|
| 41 | + >>> solution(30) |
| 42 | + '6.985042712' |
| 43 | + """ |
| 44 | + total = math.comb(NUM_BALLS, num_picks) |
| 45 | + missing_colour = math.comb(NUM_BALLS - BALLS_PER_COLOUR, num_picks) |
| 46 | + |
| 47 | + result = NUM_COLOURS * (1 - missing_colour / total) |
| 48 | + |
| 49 | + return f"{result:.9f}" |
| 50 | + |
| 51 | + |
| 52 | +if __name__ == "__main__": |
| 53 | + print(solution(20)) |
0 commit comments