Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-10-20 07:57:02
Original
725 people have browsed it

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:

<code class="js">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]);</code>
Copy after login

Alternatively, generators can be used for this purpose:

<code class="js">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
...</code>
Copy after login

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

The above is the detailed content of How to Generate Non-Repeating Random Numbers in JavaScript Effectively?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!