oka*_*56k 1 ruby ruby-on-rails ruby-on-rails-5
如何在保持其长度为at的同时确保此数组的唯一性5
?
def fixed
5.times.collect { SecureRandom.random_number(10) }
end
Run Code Online (Sandbox Code Playgroud)
这种行为似乎很奇怪:
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]
Run Code Online (Sandbox Code Playgroud)
当可能值的数量很小(例如您的示例中为10)时,我将生成一个包含所有选项的数组,并随机选择一个sample
条目:
(0..9).to_a.sample(5)
Run Code Online (Sandbox Code Playgroud)
如果可能值的数量巨大,那么首先生成所有值肯定不是一个选择。然后,只要数组不包含足够的条目,我就会生成一个随机值:
require 'set'
values = Set.new
until values.length == 5 do
values.add(SecureRandom.random_number(1_000_000))
end
values.to_a
Run Code Online (Sandbox Code Playgroud)
请注意,我正在使用a Set
来确保第二个版本中值的唯一性。
归档时间: |
|
查看次数: |
84 次 |
最近记录: |