如何确保此数组的唯一性,同时将其长度保持在 5
?
def fixed
5.times.collect { SecureRandom.random_number(10) }
end
这种行为看起来奇怪:
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 2, 3, 4]
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 1, 3]
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 1, 2, 3, 4]
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 1, 2, 4]
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 1, 2, 3]
最佳答案
当可能值的数量很小时——比如你的例子中的 10——然后我会生成一个包含所有选项的数组,然后随机选择一个 sample
。条目数:
(0..9).to_a.sample(5)
如果可能值的数量很大,那么首先生成所有值当然不是一种选择。然后只要数组不包含足够的条目,我就会生成一个随机值:
require 'set'
values = Set.new
until values.length == 5 do
values.add(SecureRandom.random_number(1_000_000))
end
values.to_a
请注意我使用的是 Set
以确保第二个版本中值的唯一性。
关于ruby-on-rails - rails : random unique array of fixed length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56822273/