3 ms·
1) Given a number 1 to 5, get a new one if it's 5, else throw away the MSB, you get 2 bits of randomness per number. Subtract one and call it a. (Now you have
by llimllib 18y ago
1) Given a number 1 to 5, get a new one if it's 5, else throw away the MSB, you get 2 bits of randomness per number. Subtract one and call it a.
(Now you have two bits of randomness evenly distributed among the set {00, 01, 10, 11})
2) Get another number 1 to 5, toss it if it's 5, take the LSB. Call it b.
(Now you have another bit of randomness, evenly distributed among {0,1})
3) if b == 1 and a == 11, start over. else return (4b)+a+1
Python implementation (with the -1 then +1 factored out):
def one_to_seven(debug=False):
a = one_to_five()
while a == 5: a = one_to_five()
b = one_to_five()
while b == 5: b = one_to_five()
b = (b % 2) * 4
if a+b == 8: return one_to_seven()
return a+b
- llimllib 18y agopatio11's solution is about twice as efficient as mine, and is a much simpler way to think about it.