"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Generate Non-Repeating Random Numbers in JavaScript Effectively?

How to Generate Non-Repeating Random Numbers in JavaScript Effectively?

Published on 2024-11-08
Browse:370

How to Generate Non-Repeating Random Numbers in JavaScript Effectively?

Generating Non-Repeating Random Numbers in JS

Generating non-repeating random numbers in JS can be achieved using various techniques. Originally, the approach was to check if a newly generated number had already been created by adding it to an array and comparing against it. However, this can lead to a "Maximum call stack size exceeded" error due to excessive recursive calls.

An efficient solution is to generate a randomized list of numbers once and work through it sequentially. This approach eliminates the need for recursive calls and guarantees no repetitions.

Here's an example using a Fisher–Yates Shuffle:

function shuffle(array) {
    var i = array.length,
        j = 0,
        temp;

    while (i--) {
        j = Math.floor(Math.random() * (i 1));
        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]);

Alternatively, generators can be used for this purpose:

function* shuffle(array) {
    var i = array.length;
    while (i--) {
        yield array.splice(Math.floor(Math.random() * (i 1)), 1)[0];
    }
}

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
...

These techniques provide efficient ways to generate non-repeating random numbers in JavaScript, eliminating issues related to excessive recursive calls.

Release Statement This article is reprinted at: 1729382177 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3