http://www.perlmonks.org?node_id=158773


in reply to Re: Rolling a biased die
in thread Rolling a biased die

Cool algorithm. It's like a king of the hill match.

1 starts as king of the hill. ($rand = 1)

2 comes along and challanges it. Whoever wins stays on top (is assigned to $rand).

Just like 2, everyone else (3, 4, 5 and 6) gets a chance.

Whoever is left on top ($rand) is declared the winner. :)


To understand why the probabilities work you have to step through the algorithm backwards.

ie. What is the chance that 6 (the final iteration) is going to win it's match against the king of the hill? $bias{6} / sum(values %bias), which is obvious.

Now - consider the second last iteration (5). Given that 6 is going to have it's chance in a minute, and hence does not need to be included, what is the chance that 5 will win it's match? $bias{5} / (sum(values %bias) - $bias{6}). We remove 6 from the running by excluding it's weighting from the total.

Update: This explanation is awful. :)