JavaScript generate random number except some values

One way, which will maintain the generator's statistical properties, is to generate a number in [1, 18]. Then apply, in this order:

  1. If the number is 8 or more, add 1.

  2. If the number is 15 or more, add 1.

I'd be reluctant to reject and re-sample as that can cause correlation plains to appear in linear congruential generators.


it should be or instead of and

function generateRandom(min, max) {
    var num = Math.floor(Math.random() * (max - min + 1)) + min;
    return (num === 8 || num === 15) ? generateRandom(min, max) : num;
}

var test = generateRandom(1, 20)

Right now I'm using this and it works without causing browser issues with infinities loops, also tested in mobile devices (using Ionic/Cordova):

function getRandomIndex(usedIndexs, maxIndex) {
    var result = 0;
    var min = 0;
    var max = maxIndex - 1;
    var index = Math.floor(Math.random()*(max-min+1)+min);

    while(usedIndexs.indexOf(index) > -1) {
        if (index < max) {
            index++;
        } else {
          index = 0;
        }
    }

    return index;
}

Tags:

Javascript