Home >Web Front-end >JS Tutorial >How to Generate Non-Repeating Random Numbers in JavaScript without Recursion?
Generating a sequence of non-repeating random numbers can be a challenge in JavaScript. Here's a breakdown of a representative problem and its resolution.
The Problem:
The provided code attempts to generate non-repeating random numbers by checking against an array of previously generated numbers. However, this approach triggers a stack overflow error due to recursive function calls.
The Best Solution:
Instead of continuous recursive function calls, consider generating a shuffled array of numbers at the outset. This approach ensures that each number is generated only once. Here's a Fisher–Yates Shuffle that achieves this efficiently:
<code class="javascript">function shuffle(array) { let i = array.length; let j = 0; let temp; while (i--) { j = Math.floor(Math.random() * (i + 1)); temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } let ranNums = shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);</code>
This technique avoids costly array operations by swapping elements directly within the original array.
Another Alternative:
For browsers with generator support, you can use the following generator function:
<code class="javascript">function* shuffle(array) { let i = array.length; while (i--) { yield array.splice(Math.floor(Math.random() * (i + 1)), 1)[0]; } } let 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 // etc.</code>
By utilizing yielded values, this approach delays array operations until they are actually required, making it more efficient for certain use cases. Whichever method you choose, these solutions effectively generate non-repeating random numbers in JavaScript.
The above is the detailed content of How to Generate Non-Repeating Random Numbers in JavaScript without Recursion?. For more information, please follow other related articles on the PHP Chinese website!