How to Efficiently Randomly Select Array Item Without Repeats
Your code creates an array of recent choices to prevent repetition, and calls a recursive function named chooseName() when a selected item is in the recent choices. This approach ensures uniqueness but may lead to an infinite loop if the array size is limited.
Is It a Recursive Function?
Yes, chooseName() calls itself to find a unique selection. Recursion enables the function to iterate through array items until it finds one that is not in the recent choices.
Improving Efficiency
To avoid infinite looping, consider an alternative approach suggested in the answer:
function randomNoRepeats(array) {
var copy = array.slice(0);
return function() {
if (copy.length This function generates a copy of the original array and randomly chooses an item from it. Once all items are used, it creates a new copy of the original array, ensuring unique selections even when the array is exhausted.
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