"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Efficiently Select Array Items Randomly Without Repetition?

How to Efficiently Select Array Items Randomly Without Repetition?

Published on 2024-11-03
Browse:362

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:

function randomNoRepeats(array) {
  var copy = array.slice(0);
  return function() {
    if (copy.length  "Bar"
console.log(chooser()); // => "Foo"
console.log(chooser()); // => "Gah"
console.log(chooser()); // => "Foo" -- only repeats once all items are exhausted.

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3