java - 检索数组中的随机元素而不重复位置

标签 java arrays duplicates

我想从数组中检索元素,但要确保如果已经选择了元素位置,则不会重复。最好和/或最易读的方法是什么?

我想到的方法仅适用于数字,并且当元素在另一个位置有重复项时受到限制。我发现的最接近的是: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/

相关文章:

java - 当 Java 小程序的多个实例写入服务器上的同一个文件时,如何避免出现错误

arrays - swift 。排序结构数组

python - 使用缩小的公平窗口迭代数组

python - 调用 drop_duplicates 后索引包含重复条目

cron - 如何在 CRON 驱动的 DetectDuplicate 中摄取所有流文件?

python - 根据两列的值删除数据框 pandas 中的重复项

RSA 解密期间出现 javax.crypto.BadPaddingException

java - 将文本字段数据添加到列表中。 Swing

java - 同时返回带有列表对象的 ModelAndView

c - 关于指针、数组和malloc