Random number generator without dupes in Javascript?

后端 未结 6 1782
一生所求
一生所求 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:31

    This is relatively simple to do, the theory behind it is creating another array which keeps track of which elements of the array you have used.

    var tempArray = new Array(12),i,r;
    for (i=0;i<9;i++)
        {
        r = Math.floor(Math.random()*12);    // Get a random index
        if (tempArray[r] === undefined)      // If the index hasn't been used yet
            {
            document.write(numberArray[r]);  // Display it
            tempArray[r] = true;             // Flag it as have been used
            }
        else                                 // Otherwise
            {
            i--;                             // Try again
            }
        }
    

    Other methods include shuffling the array, removing used elements from the array, or moving used elements to the end of the array.

提交回复
热议问题