In JavaScript, generating non-repeating random numbers presents challenges, as exemplified by the error report in Chrome. The function presented in the question necessitates improvements to ensure unique numbers.
Alternative Approach 1: Random Permutation
To avoid invoking the random number function repeatedly, it's advisable to generate a random permutation of numbers initially. The following code snippet achieves this for numbers between 1 and 10:
var nums = [1,2,3,4,5,6,7,8,9,10], ranNums = [], i = nums.length, j = 0; while (i--) { j = Math.floor(Math.random() * (i+1)); ranNums.push(nums[j]); nums.splice(j,1); }
This approach eliminates the risk of elongated processing time to find unused numbers.
Alternative Approach 2: Fisher–Yates Shuffle
A more efficient method known as the Fisher–Yates Shuffle can be employed:
function shuffle(array) { var i = array.length, j = 0, temp; while (i--) { j = Math.floor(Math.random() * (i+1)); // swap randomly chosen element with current element temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10]);
Alternative Approach 3: Generators
Another option is to utilize generators:
function* shuffle(array) { var i = array.length; while (i--) { yield array.splice(Math.floor(Math.random() * (i+1)), 1)[0]; } }
To use:
var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10]); ranNums.next().value; // first random number from array ranNums.next().value; // second random number from array ranNums.next().value; // etc.
The choice of approach depends on the specific requirements and constraints of the application.
The above is the detailed content of How to Improve Random Number Generation in JavaScript for Unique and Non-Repeating Results?. For more information, please follow other related articles on the PHP Chinese website!