Random number generator without dupes in Javascript?

后端 未结 6 1781
一生所求
一生所求 2020-11-28 14:53

I need help with writing some code that will create a random number from an array of 12 numbers and print it 9 times without dupes. This has been tough for me to accomplish.

6条回答
  •  粉色の甜心
    2020-11-28 15:38

    Here is a generic way of getting random numbers between min and max without duplicates:

    function inArray(arr, el) {
        for(var i = 0 ; i < arr.length; i++) 
                if(arr[i] == el) return true;
        return false;
    }
    
    function getRandomIntNoDuplicates(min, max, DuplicateArr) {
        var RandomInt = Math.floor(Math.random() * (max - min + 1)) + min;
        if (DuplicateArr.length > (max-min) ) return false;  // break endless recursion
        if(!inArray(DuplicateArr, RandomInt)) {
           DuplicateArr.push(RandomInt); 
           return RandomInt;
        }
        return getRandomIntNoDuplicates(min, max, DuplicateArr); //recurse
    }
    

    call with:

    var duplicates  =[];
    for (var i = 1; i <= 6 ; i++) { 
        console.log(getRandomIntNoDuplicates(1,10,duplicates));
    }
    

提交回复
热议问题