Home  >  Article  >  Web Front-end  >  How to Generate Non-Repeating Random Numbers in JavaScript without Recursion

How to Generate Non-Repeating Random Numbers in JavaScript without Recursion

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 08:03:29307browse

How to Generate Non-Repeating Random Numbers in JavaScript without Recursion

Generating Non-Repeating Random Numbers in JavaScript

The goal of this task is to generate a sequence of random numbers within a specified range that do not repeat. One approach involves checking each generated number against a list of previously created numbers. However, this method can lead to a "RangeError" due to excessive recursion.

A better solution is to generate a random permutation of the desired numbers upfront. This can be achieved using various techniques:

Random Permutation

<code class="javascript">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);
}</code>

This algorithm generates a random ordering of the numbers in nums. If you want to restrict the range or specify even numbers, you can modify nums accordingly.

Fisher-Yates Shuffle

<code class="javascript">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]);</code>

The Fisher-Yates Shuffle is a more efficient alternative to the random permutation method, as it avoids the use of costly array operations.

Generators

<code class="javascript">function* shuffle(array) {

    var i = array.length;

    while (i--) {
        yield array.splice(Math.floor(Math.random() * (i+1)), 1)[0];
    }

}</code>

Generators offer an even more dynamic option. By utilizing the yield and next methods, you can access the shuffled numbers on demand without pre-generating the entire sequence.

This approach is especially useful in cases where you need a large number of random numbers and want to avoid holding them all in memory at once.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn