从数组中选择随机唯一元素

时间:2013-09-06 03:08:44

标签: arrays ruby-on-rails-4

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

编辑:

在我的具体情况下,我不会立即一个接一个地调用,所以使用带样本的参数将无济于事

3 个答案:

答案 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。假设您的arrayary,请致电:

 ary.uniq{|x| x.user_id}

这将返回一个具有唯一user_ids的集合。