r/dailyprogrammer • u/mattryan • Apr 03 '12
[4/3/2012] Challenge #35 [intermediate]
Imagine you are given a function flip() that returns a random bit (0 or 1 with equal probability). Write a program that uses flip to generate a random number in the range 0...N-1 such that each of the N numbers is generated with equal probability. For instance, if your program is run with N = 6, then it will generate the number 0, 1, 2, 3, 4, or 5 with equal probability.
N can be any integer >= 2.
Pseudocode is okay.
You're not allowed to use rand or anything that maintains state other than flip.
Thanks to Cosmologicon for posting this challenge to /r/dailyprogrammer_ideas!
View all comments
Show parent comment
2
u/Steve132 0 1 Apr 03 '12
Correct me if I'm wrong, but I don't think this is actually evenly distributed. It looks like what you are doing is generating a 32 bit binary rand(), then returning rand() % n.
The problem with the rand() % n approach, is that it actually produces numbers that aren't randomly distributed if n isn't a power of two. Here is why: Consider we did the same thing, but with a 4 bit rand() instead. Then, you generated randomly a number between 0 and 15. We want to make it actually between 0 and 9, so we do % 9. Lets say we start with a perfectly uniform distribution: of samples
Now, lets do mod 9
If we look at the distribution sorted now, we can clearly see that the numbers between 0 and (16-9) are duplicated.
This is true in general...using rand() % n, if b is the closest power of two to n, then numbers between 0 and (b-n) are twice as likely to occur, because of the wrap-around effect of mod()