Home  >  Article  >  Web Front-end  >  How Can I Efficiently Select Random Array Items Without Repeats?

How Can I Efficiently Select Random Array Items Without Repeats?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 04:47:30325browse

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>

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!

Statement:
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