Home > Web Front-end > JS Tutorial > How to Optimize Array Item Random Selection Without Repetition?

How to Optimize Array Item Random Selection Without Repetition?

Linda Hamilton
Release: 2024-10-30 08:14:27
Original
544 people have browsed it

How to Optimize Array Item Random Selection Without Repetition?

How to Enhance Array Item Random Selection Efficiency

When it comes to randomly choosing array items while avoiding repetitions, efficiency plays a crucial role. While the provided code effectively prevents selecting the same item multiple times in a row, there is potential for performance enhancements.

Regarding the question of recursion, the provided function does not technically qualify as recursive because it does not call itself directly but rather invokes itself through another function (chooseName()). However, it shares similarities with recursive functions in its iterative nature.

To improve efficiency, an alternative approach can be adopted that eliminates the recursive-like behavior and significantly reduces the time spent searching for unique items. This strategy involves creating a new function that randomly selects items until all items in the array have been exhausted. Once all items have been used, the function starts over from the beginning, ensuring no items are repeated.

The following code implements this approach:

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

var chooser = randomNoRepeats(['Foo', 'Bar', 'Gah']);
chooser(); // => "Bar"
chooser(); // => "Foo"
chooser(); // => "Gah"
chooser(); // => "Foo" -- only repeats once all items are exhausted.</code>
Copy after login

By using this modified approach, you can effectively avoid repetition while maintaining efficient item selection without the potential for lengthy loop iterations as in the recursive-like implementation.

The above is the detailed content of How to Optimize Array Item Random Selection Without Repetition?. 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