Chapter 28
What Share Of Your Gummy Vitamins Are The Right Flavor?
You and your spouse each take two gummy vitamins every day, from a shared bottle of 60 that comes in two flavours. You each prefer a different flavour, but rather than fish out the right ones you take the first four that fall out and split them by preference. For example, if two of each flavour come out you each get your favourite, but if three of your flavour come out you get two of yours and your spouse gets one of each. On average, what percentage of the vitamins you take are the flavour you prefer? Assume the bottle starts as a 50-50 split and that the four each day are chosen uniformly at random.
The Riddler, FiveThirtyEight(original post)
Solution
Each morning four vitamins tumble out, of them your flavour. You claim up to two of yours, so you receive of your flavour and take of the other; your spouse takes the rest. Over days you take vitamins in all, and the answer is the expected number of your-flavour vitamins you end up with, divided by .
The difficulty is that the bottle’s makeup drifts as vitamins leave it, so the daily draw is hypergeometric with shifting parameters and there is no tidy closed form. But the state that matters is just the pair of your-flavour and other-flavour vitamins remaining, and an exact recursion tracks it. Writing for the expected number of your-flavour vitamins you still collect, the day’s four-vitamin draw gives ending at . Evaluating from the full bottle and dividing by the vitamins you take gives the exact You get your flavour about four times in five, comfortably more than half, because the two you are allowed to claim each day go to your preference whenever it is available.
The computation
Carry the exact recursion above. For every reachable bottle state , average over the hypergeometric four-vitamin draw, crediting yourself of your flavour, and memoise. The printed value is the exact fraction.
from fractions import Fraction as F
from math import comb
from functools import lru_cache
@lru_cache(None)
def E(a, b): # your-flavour vitamins still to collect
if a + b == 0:
return F(0)
denom = comb(a + b, 4)
total = F(0)
for k in range(5): # k of your flavour among the 4 drawn
ways = comb(a, k) * comb(b, 4 - k)
if ways:
total += F(ways, denom) * (min(k, 2) + E(a - k, b - 4 + k))
return total
print(E(30, 30) / 30) # 918/1121 ~ 0.819