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

How Can I Efficiently Select Random Array Items Without Repeats?

Patricia Arquette
Release: 2024-10-31 04:47:30
Original
324 people have browsed it

How Can I Efficiently Select Random Array Items Without Repeats?

How to Efficiently Randomly Select Array Item Without Repeats

Your code creates an array of recent choices to prevent repetition, and calls a recursive function named chooseName() when a selected item is in the recent choices. This approach ensures uniqueness but may lead to an infinite loop if the array size is limited.

Is It a Recursive Function?

Yes, chooseName() calls itself to find a unique selection. Recursion enables the function to iterate through array items until it finds one that is not in the recent choices.

Improving Efficiency

To avoid infinite looping, consider an alternative approach suggested in the answer:

<code class="javascript">function randomNoRepeats(array) {
  var copy = array.slice(0);
  return function() {
    if (copy.length < 1) { copy = array.slice(0); }
    var index = Math.floor(Math.random() * copy.length);
    var item = copy[index];
    copy.splice(index, 1);
    return item;
  };
}</code>
Copy after login

This function generates a copy of the original array and randomly chooses an item from it. Once all items are used, it creates a new copy of the original array, ensuring unique selections even when the array is exhausted.

The above is the detailed content of How Can I Efficiently Select Random Array Items Without Repeats?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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!