我想从数组中检索元素,但要确保如果已经选择了元素位置,则不会重复。最好和/或最易读的方法是什么?
我想到的方法仅适用于数字,并且当元素在另一个位置有重复项时受到限制。我发现的最接近的是:Java - generate Random range of specific numbers without duplication of those numbers - how to?但它并不适用,因为我不需要数组中的所有元素。虽然它让我意识到一个可能的“解决方案”是先洗牌,然后迭代数组以获得我需要的数量,但我想知道还有什么办法可以做到这一点?
最佳答案
这是一个已知的算法。您需要的是 Knuth-Fisher-Yates 洗牌的变体 http://en.wikipedia.org/wiki/Knuth_shuffle .
将所有数字添加到集合中。如果所有数字都是连续的,则只需使用 for 循环
Repeat this until there's only one number in the collection:
generate a random number using the length of the collection.
remove the number from the collection.
At this point there's only one element in the collection. So remove the only number from the collection.
关于java - 检索数组中的随机元素而不重复位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24234777/