progress

~/problems / Randomness / Randomized algorithms

Roll a die and tally the faces

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Write roll_tally(sides: int, rolls: int, rng: random.Random) -> list[int]. Roll a fair die with faces 1 .. sides, rolls times, and return a list of sides counts: counts[i] is how many rolls showed face i + 1.

Use rng for every roll (for example rng.randint(1, sides)), never the global random module, so the tests can repeat your rolls.

roll_tally(6, 0, random.Random(0))       # [0, 0, 0, 0, 0, 0]
roll_tally(1, 5, random.Random(0))       # [5]   a one-sided die always shows 1
roll_tally(6, 60_000, random.Random(0))  # about 10,000 in each slot

Constraints: 1 <= sides <= 100, 0 <= rolls <= 3 * 10^5.

Show hint

rng.randint(a, b) includes both ends. Every face, the first and the last included, must be able to come up.

Topic: Randomized algorithms. Reservoir sampling, Fisher-Yates, rejection sampling.

0:00
Ctrl ' run · Ctrl ↵ submit
esc