Home > Article > Web Front-end > 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>
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!