All about flooble | fun stuff | Get a free chatterbox | Free JavaScript | Avatars
 perplexus dot info

 More randomness! (Posted on 2003-06-30)
Suppose you have a function (or a magic ball) that is capable of producing a totally random integer between 1 and 5 (inclusive).

Using this, how would you generate a random number (also an integer) between 1 and 7 (inclusive)? (Note that the for the number to be random, all integers between 1 and 7 must have an equal chance of being generated)

Assume that using your 1-5 generator is pretty time-consuming, so you want to minimize the number of times you are going to use it.

 See The Solution Submitted by levik Rating: 4.3333 (6 votes)

Comments: ( Back to comment list | You must be logged in to post comments.)
 A binary solution | Comment 15 of 16 |
Use RAND5() to generate a binary number like this:

BINARY():
repeat
let B = RAND5()
until B<5
if B=1 or 2, return 0; else, return 1

This BINARY() function does, on the average, 5/4ths calls to RAND5().

You can construct the desired function as

RANDOM_1_TO_7():
return BINARY() + 2*BINARY() + 4*BINARY()

which requires three calls to BINARY(), and thus 15/4ths calls to RAND5().

 Posted by Federico Kereki on 2003-07-14 15:49:01

 Search: Search body:
Forums (0)