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

How to Efficiently Select Array Items Randomly Without Repetition?

Susan Sarandon
Release: 2024-10-31 03:54:01
Original
775 people have browsed it

How to Efficiently Select Array Items Randomly Without Repetition?

Efficiently Selecting Array Items Randomly Without Repetition

You have devised a function that randomly selects items from an array, ensuring that recent selections are not repeated. While the current solution works effectively, you have concerns about its efficiency and whether it could lead to excessive looping. Let's explore a more efficient approach.

1. Recursion Considerations

Yes, your chooseName() function can be considered recursive as it calls itself until it finds a unique name. Recursion can be useful for certain problems, but it's important to be mindful of stack usage and the potential for excessive depth.

2. An Efficient Solution

To address efficiency concerns, we can adopt a different strategy. Instead of relying on recursion and looping until a unique name is found, we can create a copy of the original array and randomly select items from the copy until all items are selected. Once all items are exhausted, we reset the copy to its original state.

Here's a JavaScript implementation of 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']);
console.log(chooser()); // => "Bar"
console.log(chooser()); // => "Foo"
console.log(chooser()); // => "Gah"
console.log(chooser()); // => "Foo" -- only repeats once all items are exhausted.</code>
Copy after login

This approach makes use of JavaScript's array slice() method to create a shallow copy of the original array. It then repeatedly selects random items from the copy and removes them from the copy, effectively mimicking a random selection without repeats until all items are exhausted. Once all items are selected, the copy is reset, allowing for random selection to start again.

The above is the detailed content of How to Efficiently Select Array Items Randomly 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