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.

Marc Novakowski
  • 44,628
  • 11
  • 58
  • 63
Anand
  • 729
  • 2
  • 10
  • 26
  • Try: http://stackoverflow.com/questions/1268025/using-one-probability-set-to-generate-another – Jander Oct 13 '10 at 06:32

1 Answers1

1

Using the top two answers for Expand a random range from 1–5 to 1–7, 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];
}
Community
  • 1
  • 1
Marc Novakowski
  • 44,628
  • 11
  • 58
  • 63