Generating a random number between 1-7 by rand(5)
I want to write an algo to generate a random number between 1-7 given a
method that generates a random number between 1-5.
I thought of one solution as rand(5)/5*7 ??
I think this should work.
Can anybody tell me an optimal solution ?
I read somewhere this solution, but I do not know how they thought of
keeping " int num = 5 * (rand5() - 1) + (rand5() - 1);" . I understand
that it generates a random number between 1-7 but how they thought of this
logic or what they trying to convey is not getting into my head. Can
anybody please throw a light on this.
public static int rand7() {
while (true) {
int num = 5 * (rand5() - 1) + (rand5() - 1);
if (num < 21) return (num % 7 + 1);
}
}
No comments:
Post a Comment