简体   繁体   English

Javascript中非重复数字的随机集合

[英]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. 我需要一个可能的0-64数字集中的32个非重复数字。 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 :( 我很困惑:(

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 工作演示

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. 此代码将生成一个介于0和您提供的任何数字之间的非重复随机数,并在被称为您提供的数字的数量时重新开始。

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM