Javascript generate random unique number every time

后端 未结 7 1316
予麋鹿
予麋鹿 2021-01-15 16:25

Ok so i need to create four randomly generated numbers between 1-10 and they cannot be the same. so my thought is to add each number to an array but how can I check to see i

相关标签:
7条回答
  • 2021-01-15 16:36

    You want what is called a 'random grab bag'. Consider you have a 'bag' of numbers, each number is only represented once in this bag. You take the numbers out, at random, for as many as you need.

    The problem with some of the other solutions presented here is that they randomly generate the number, and check to see if it was already used. This will take longer and longer to complete (theoretically up to an infinite amount of time) because you are waiting for the random() function to return a value you don't already have (and it doesn't have to do that, it could give you 1-9 forever, but never return 10).

    There are a lot of ways to implement a grab-bag type solution, each with varying degrees of cost (though, if done correctly, won't ever be infinite).

    The most basic solution to your problem would be the following:

    var grabBag = [1,2,3,4,5,6,7,8,9,10];
    
    // randomize order of elements with a sort function that randomly returns -1/0/1
    grabBag.sort(function(xx,yy){ return Math.floor(Math.random() * 3) - 1; })
    
    function getNextRandom(){
        return grabBag.shift();
    };
    
    var originalLength = grabBag.length;
    for(var i = 0; i < originalLength; i++){
        console.log(getNextRandom());
    }
    

    This is of course destructive to the original grabBag array. And I'm not sure how 'truly random' that sort is, but for many applications it could be 'good enough'.

    An slightly different approach would be to store all the unused elements in an array, randomly select an index, and then remove the element at that index. The cost here is how frequently you are creating/destroying arrays each time you remove an element.

    0 讨论(0)
  • 2021-01-15 16:39

    Here is a recursive function what are you looking for.

    "howMany" parameter is count of how many unique numbers you want to generate.
    "randomize" parameter is biggest number that function can generate.
    

    for example : rand(4,8) function returns an array that has 4 number in it, and the numbers are between 0 and 7 ( because as you know, Math.random() function generates numbers starting from zero to [given number - 1])

    var array = [];
    var isMatch= false;
    function rand(howMany, randomize){
         if( array.length < howMany){
        var r = Math.floor( Math.random() * randomize );
        for( var i = 0; i < howMany; i++ ){
            if( array[i] !== r ){
               isMatch= false;
               continue;
                } else {
               isMatch= true;
               break;
            }
        }
        if( isMatch == false ){
           array.push(r);
               ran(howMany, randomize);
        }
            ran(howMany, randomize);
        return array;
         }
    }
    
    0 讨论(0)
  • 2021-01-15 16:40

    Here are a couple versions using Matt's grabBag technique:

    function getRandoms(numPicks) {
        var nums = [1,2,3,4,5,6,7,8,9,10];
        var selections = [];
    
        // randomly pick one from the array
        for (var i = 0; i < numPicks; i++) {
            var index = Math.floor(Math.random() * nums.length);
            selections.push(nums[index]);
            nums.splice(index, 1);
        }
        return(selections);
    }
    

    You can see it work here: http://jsfiddle.net/jfriend00/b3MF3/.

    And, here's a version that lets you pass in the range you want to cover:

    function getRandoms(numPicks, low, high) {
        var len = high - low + 1;
        var nums = new Array(len);
        var selections = [], i;
        // initialize the array
        for (i = 0; i < len; i++) {
            nums[i] = i + low;
        }
    
        // randomly pick one from the array
        for (var i = 0; i < numPicks; i++) {
            var index = Math.floor(Math.random() * nums.length);
            selections.push(nums[index]);
            nums.splice(index, 1);
        }
        return(selections);
    }
    

    And a fiddle for that one: http://jsfiddle.net/jfriend00/UXnGB/

    0 讨论(0)
  • 2021-01-15 16:40

    I'm using a recursive function. The test function pick 6 unique value between 1 and 9.

    //test(1, 9, 6);
    
    function test(min, max, nbValue){
        var result = recursValue(min, max, nbValue, []);
        alert(result);
    }
    
    function recursValue(min, max, nbValue, result){
        var randomNum = Math.random() * (max-min);
        randomNum = Math.round(randomNum) + min;
    
        if(!in_array(randomNum, result)){
            result.push(randomNum);
            nbValue--;
        }
    
        if(nbValue>0){
            recursValue(min, max, nbValue, result);
        }
        return result;
    }
    
    function in_array(value, my_array){
        for(var i=0;i< my_array.length; i++){
            if(my_array[i] == value){
                console.log(my_array+" val "+value);
                return true;   
            }        
        }
        return false;
    }
    
    0 讨论(0)
  • 2021-01-15 16:44

    In your answer earlier, you do have a small bug. Instead of

    var originalLength = grabBag.length;
    for(var i = 0; i < originalLength .length; i++){
        console.log(getNextRandom());
    }
    

    I believe you meant:

    var originalLength = grabBag.length;
    for(var i = 0; i < originalLength; i++){
        console.log(getNextRandom());
    }
    

    Thanks.

    0 讨论(0)
  • 2021-01-15 16:45

    Use an array to see if the number has already been generated.

    var randomArr = [], trackingArr = [],
        targetCount = 4, currentCount = 0,
        min = 1, max = 10,
        rnd;
    
    while (currentCount < targetCount) {
        rnd = Math.floor(Math.random() * (max - min + 1)) + min;
        if (!trackingArr[rnd]) {
            trackingArr[rnd] = rnd;
            randomArr[currentCount] = rnd;
            currentCount += 1;
        }
    }
    
    alert(randomArr); // Will contain four unique, random numbers between 1 and 10.
    

    Working example: http://jsfiddle.net/FishBasketGordo/J4Ly7/

    0 讨论(0)
提交回复
热议问题