views:

46

answers:

1

Given two random integer generators one that generates between 1 and 7 and another that generates between 1 and 5, how do you make a random integer generator that generates between 1 and 13? I have tried solving this question in various ways but I have not been able to come up with a solution that generates numbers from 1 to 13 with equal or near equal probability.

+1  A: 

Using the top two answers for http://stackoverflow.com/questions/137783, I've come up with the following. There's probably a more efficient way to do this (maybe using the 1-5 generator?) but this seems to work.

Optimized for Compactness

    var j;
    do {
        j = 7 * (rand7() - 1) + rand7();  // uniformly random between 1 and 49
    } while (j > 39);
    // j is now uniformly random between 1 and 39 (an even multiple of 13)
    j = j % 13 + 1;

Optimized for understandability

var v = [
    [1,  2,  3,  4,  5,  6,  7],
    [8,  9, 10, 11, 12, 13,  1],
    [2,  3,  4,  5,  6,  7,  8],
    [9, 10, 11, 12, 13,  1,  2],
    [3,  4,  5,  6,  7,  8,  9],
    [10, 11, 12, 13, 0,  0,  0],
    [0,  0,  0,  0,  0,  0,  0]
];
var j = 0;
while (j == 0) {
    j = v[rand7() - 1][rand7() - 1];
}
Marc Novakowski
Lovely solution, thank you very much. :)
Meher