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
re: Quick and Dirty Solution by Charlie)
Actually, what I was thinking, but failed to write is:
int result = (c / 3) + 1;
I brain-farted and managed to mix up the modulo and division operators.
With the correction in place, different values for c give these results:
0-2: 1
3-5: 2
6-8: 3
9-11: 4
12-14: 5
15-17: 6
18-20: 7
21-23: 8 (which fails the comparison test, and thus causes the loop to re-run)
24: 9 (as above)
I think I managed to do that in my other snippet as well. Serve me right for not testing my code...