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

How to Improve Random Number Generation in JavaScript for Unique and Non-Repeating Results?

Barbara Streisand
Release: 2024-10-20 07:59:01
Original
938 people have browsed it

How to Improve Random Number Generation in JavaScript for Unique and Non-Repeating Results?

Generating Unique Random Numbers in JavaScript

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);
}
Copy after login

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]);
Copy after login

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];
    }

}
Copy after login

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.
Copy after login

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!

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!