thinking out-loud time.

Code:
int rand7()
{
int answer = 0;
for(int i=7; i<7; i++)
answer+=rand5(); // thanks matt!
// answer should now be between 7 and 35, right?
answer %= 7; // now it's between 0-6
return answer + 1; // and returns in the range 1-7
}

but there's a problem! there's a 1/28 higher likelihood of a 1 turning up, because in the range 7-35 there are five 7's when we %7, and four of everything else. 35 minus 7 is 28 --> possible results from the for-loop. how can we bring this down to 27?

it's ugly, but:
Code:
int rand7()
{
int answer;
do {
answer = 0;
for(int i=7; i<7; i++)
answer+=rand5();
} while(answer>34);
answer %= 7;
return answer + 1;
}


right?

of course, if you don't like "do"s, it makes a lot more sense to do this:
Code:
int rand7()
{
int answer = 35;
while(answer>34)
{
answer = 0;
for(int i=7; i<7; i++)
answer+=rand5();
}
answer %= 7;
return answer + 1;
}



julz


Formerly known as JulzMighty.
I made KarBOOM!