This question讨论了如何使用sample从数组中选择随机元素,但我想多次这样做,每次选择一个唯一的。
我能想到的最简单的解决方案是这样的,但我觉得必须有一个更简单的方法(不修改原始数组):
myArray = ["stuff", "widget", "ruby", "goodies", "java", "emerald", "etc" ]
selected = []
first = myArray.sample
selected << first
second = myArray.sample
while(selected.include? second) do
second = myArray.sample
end
selected << second
编辑:
在我的具体情况下,我不会立即一个接一个地调用,所以使用带样本的参数将无济于事
答案 0 :(得分:3)
你可以这样做:
(myArray - selected).sample
E.g。如果:
selected = ['ruby', 'goodies']
然后:
myArray - selected #=> ["stuff", "widget", "java", "emerald", "etc"]
因此,sample
将从["stuff", "widget", "java", "emerald", "etc"]
中删除。
答案 1 :(得分:1)
您可以将其他参数号传递给sample(n)
,它会为您返回一个新数组
myArray = ["stuff", "widget", "ruby", "goodies", "java", "emerald", "etc" ]
n = myArray.length
# The elements are chosen by using random and unique indices and doesn’t repeat itself
selected = myArray.sample(n)
第二个选项是使用slice!
和rand
种子:
myArray = ["stuff", "widget", "ruby", "goodies", "java", "emerald", "etc" ]
myArray_copy = myArray
selected = []
selected << myArray_copy.slice!(rand(myArray_copy.length - 1))
答案 2 :(得分:0)
您可以使用方法uniq
。假设您的array
为ary
,请致电:
ary.uniq{|x| x.user_id}
这将返回一个具有唯一user_ids
的集合。