Javascript中随机设置的非重复数字

时间:2013-05-24 06:01:12

标签: javascript loops random

我有一个烦人的脚本,我无法完成。

我需要32个非重复数字,可能是0-64数字集。每当我尝试创建一个循环来检查数组中所有数字的新随机数时,我最终都没有任何结果,或者是无限循环。

我很难过:(

2 个答案:

答案 0 :(得分:3)

试试这个:

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

答案 1 :(得分:0)

此代码将生成介于0和您给出的任何数字之间的非重复随机数,并且当它被称为您给出的数字量时将重新开始。

试一试:

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