Expand a random range from 1–5 to 1–7
int i;
do
{
i = 5 * (rand5() - 1) + rand5(); // i is now uniformly random between 1 and 25
} while(i > 21);
// i is now uniformly random between 1 and 21
return i % 7 + 1; // result is now uniformly random between 1 and 7
WHy can’t I just put
i = 6*(rand5()-1);
there? why we need “*” and” +” operation
(rand5() – 1) returns a number from 0 to 4. If you multiply any of these numbers by 6 you will get one of only 5 numbers (0, 6, 12, 18 or 24).
Doing it the other way ensures every possible integer between 1 and 21 can appear in the output (with a uniform probability).
EDIT:
5 * (rand5() – 1) will give you one of either (0, 5, 10, 15, 20). To this we then add another random integer between 1 and 5, thus filling in the gaps. We now have a random integer between 1 and 25 with uniform probability. Since we want a range from 1 to 21, we reject anything over 21 and try again.