Home > Article > Web Front-end > How Can We Efficiently Select Random Array Items Without Repetition?
Efficient Random Selection of Array Items Without Repetition
In this article, we explore an issue faced by users seeking an efficient method for randomly selecting items from an array without repetition. The provided code effectively selects items but introduces the possibility of an infinite loop due to the usage of a recursive function.
Recursive Function?
The function chooseName() can be considered recursive as it refers to itself within its definition. The termination condition is the discovery of a unique item, where unique is set to false, breaking the loop and starting the function call anew.
Improving Efficiency
To enhance efficiency, we consider an alternative approach suggested by commenter @YuriyGalanter. Instead of relying on a recursive function, we can randomly select items from the array and store them in a temporary array. Once all items are selected, we reset the temporary array and continue the random selection process.
Implementation
The implementation below incorporates 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>
By utilizing this function, items can be randomly selected without the potential for infinite looping while avoiding the repetition issue.
The above is the detailed content of How Can We Efficiently Select Random Array Items Without Repetition?. For more information, please follow other related articles on the PHP Chinese website!