flyagaricus
flyagaricus

Reputation: 119

Random set of non-repeating numbers in Javascript

I have an annoying script I can't complete.

I need 32 non-repeating numbers out of a possible 0-64 number set. Every time I try to create a loop to check the new random number against all the numbers in the array I end up with nothing, or an infinite loop.

I'm stumped :(

Upvotes: 0

Views: 769

Answers (2)

Olin Soffer
Olin Soffer

Reputation: 1

This code will generate a non repeating random number between 0 and whatever number you give it and will start over when it has been called the amount of the number you give it.

Give it a try:

let randomNumber = function (max) {
    let min = 0, prevIndexes = [];
    function exec(max2) {
        max = max || max2;
        let result = Math.floor(Math.random() * (max - min + 1) + min);
        if (prevIndexes) {
            if (prevIndexes.length - 1 === max) {
                clear();
            }
            let foundDouble, eqPrevInn = true;
            while (eqPrevInn) {
                foundDouble = false;
                result = Math.floor(Math.random() * (max - min + 1) + min);
                for (let i = 0, l = prevIndexes.length; i < l; i++) {
                    if (result === prevIndexes[i]) {
                        foundDouble = true;
                        break;
                    }
                }
                if (!foundDouble) {
                    eqPrevInn = false;
                }
            }
        }
        prevIndexes.push(result);
        console.log(prevIndexes);
        return result;

    }

    let clear = function () {
        if (prevIndexes) {
            prevIndexes = [];
            //             console.log('prevIndexes has been cleared');
        }
        else {
            //             console.log('already clear');
        }
    }
    return {
        exec: exec,
        clear: clear
    }
};

let random32 = randomNumber(32/*range*/).exec;

for (let i = 0; i <= 32; i++) {
    random32();
}

Upvotes: 0

techfoobar
techfoobar

Reputation: 66663

Try this:

var keys = [], numbers = [], x, total = 0;
while(total < 32) {
    x = Math.floor(Math.random() * 64);
    // way faster that looping through the array to check if it exists
    if(keys[x] == undefined) { 
        keys[x] = 1;
        numbers.push(x);
        total++;
    }
}
console.log(numbers);

Working Demo

Upvotes: 3

Related Questions