Horje
how to prevent random method from giving more than two same numbers js site:stackoverflow.com Code Example
how to prevent random method from giving more than two same numbers js site:stackoverflow.com
function setRandomInterval(min, max) {
    var last;
    if (min >= max) {
        throw 'Selected interval [' + min + ', ' + max + ') does not work for random numbers.';
    }
    return function () {
        var random;
        do {
            random = Math.floor(Math.random() * (max - min)) + min;
        } while (random === last);
        last = random;
        return random;
    };
}

var i,
    getRandom = setRandomInterval(0, 4);

for (i = 0; i < 100; i++) {
    console.log(getRandom());
}

setRandomInterval(4, 4); // throw error
how to prevent random method from giving more than two same numbers js site:stackoverflow.com
function getNumber() {
    var min = 0,
        max = 4,
        random;

    do {
        random = Math.floor(Math.random() * (max - min)) + min;
    } while (random === getNumber.last);
    getNumber.last = random;
    return random;
};

var i;
for (i = 0; i < 100; i++) {
    console.log(getNumber());
}




Javascript

Related
what is the weather like at the moment Code Example what is the weather like at the moment Code Example
jquery basics Code Example jquery basics Code Example
how to load a javascript game from react Code Example how to load a javascript game from react Code Example
logo ticker javascript Code Example logo ticker javascript Code Example
express plus make router Code Example express plus make router Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
7