r/dailyprogrammer • • 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!

13 Upvotes

24 comments sorted by

View all comments

Show parent comment

1

u/luxgladius 0 0 Apr 03 '12

That's correct in general. However, in order to dodge this, I implemented a limit on the result to ensure I get an even number of intervals. That is the expression $lim = int((232 )/$n)*$n -1. If I get a result larger than this number, then I am in the final interval that has been cut off which would, as you say, skew the probability toward the early members of the sequence. That is why if I get any result greater than the limit, I just generate a new one. Having such a big basis (232) means that I won't to have to "re-roll" very often for common values of $n, but it could happen.