2

这个问题讨论了如何使用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

编辑:

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

4

3 回答 3

3

你可以做:

(myArray - selected).sample

例如,如果:

selected = ['ruby', 'goodies']

然后:

myArray - selected #=> ["stuff", "widget", "java", "emerald", "etc"]

所以,sample将被取出["stuff", "widget", "java", "emerald", "etc"]

于 2013-09-06T04:28:30.620 回答
2

您可以将其他参数编号传递给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))
于 2013-09-06T03:52:35.197 回答
0

你可以只使用方法uniq。假设您arrayary,请致电:

 ary.uniq{|x| x.user_id}

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

于 2013-09-06T03:15:00.600 回答