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.
(In reply to Quick and Dirty Solution
Where you say
int result = (c % 3) + 1;
I assume you mean 7 rather than 3, but then I don't see the reason for checking that it's less than or equal to 7.
Under this assumption, however, while c can be anything from 0 to 24, when taken mod 7, zero through three will come up more often than four through six (on a 4-to-3 ratio) as 0-6 is one complete set; 7-13 is another; 14-20 another, but 21-24 are an incomplete set, re-representing what are now overrepresented digits.
Posted by Charlie
on 2003-06-30 08:50:42