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

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

Patricia Arquette
Release: 2024-10-20 08:02:29
Original
533 people have browsed it

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

Generating Non-Repeating Random Numbers in JavaScript

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

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

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!

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!