How do you produce a random number between 1 and 7 using a function that generates 1 to 5

Possible duplicate:
Expand a random range from 1-5 to 1-7

I figured out a solution using reject sampling i.e.

public static int rand7() {
    while (true) {
       int num = 5 * (rand5() - 1) + (rand5() - 1);
       if (num < 21) return (num % 7 + 1);
    }
}

but I am thinking of a different solution, i.e. rand5 () is called 7 times and the result is divided by 5, but I'm not sure if this is correct. Please let me know if there is or not.

public static int rand7() {    
    int num = rand5()+rand5()+rand5()+rand5()+rand5()+rand5()+rand5();
    return num/5;
}

EDIT: It seems that the probability of generating 1 is (1/5) ^ 7, but for generation 2 it is 7 * (1/5) ^ 7. This is uneven, so it will not work.

+5
source share
5 answers

1..7, , .. 3 , 1.

, 1..7 .

0

( ). , , .

enter image description here

+3

, ( , , ).

+ rand5(), a rand5. 7/5 ; rand5. ( 4.2.)

1 25,

int[][] lut = { {  1,  2,  3,  4,  5},
                {  6,  7,  8,  9, 10},
                ...,
                { 21, 22, 23, 24, 25 } }

return lut[rand5()][rand()]

7, , 5 7 . - .

+2

rand7() rand5(). .

, rand5() 10 rand7(), rand7(). 100, rand7() , . .

+2

A simple solution is to use rand5 () in the octet bits by assigning 0 to the derived values ​​of 1 or 2, generating again by 3, or assigning 1 to the values ​​of 4 or 5. If the final result is zero, then repeat. Here is the code:

public static int rand7() {
    int returnValue = 0;
    while (returnValue == 0) {
        for (int i = 1; i <= 3; i++) {
            returnValue = (returnValue << 1) + rand5_output_2();
        }
    }
    return returnValue;
}

private static int rand5_output_2() {
    while (true) {
        int flip = rand5();

        if (flip < 3) {
            return 0;
        }
        else if (flip > 3) {
            return 1;
        }
    }
}
+2
source

All Articles