Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何从0到100的范围内得到5个随机数?_Ruby_Random_Range - Fatal编程技术网

Ruby 如何从0到100的范围内得到5个随机数?

Ruby 如何从0到100的范围内得到5个随机数?,ruby,random,range,Ruby,Random,Range,我想生成5个不同的随机数。我已经生成了从0到100的范围。我想从范围中随机选取5个数字 您可以在Ruby中生成n个唯一随机数的列表,如下所示: (1..99).to_a.sample(5) =>[69, 50, 15, 68, 29] arr = [] (1..5).each{|t| arr << rand(100)} arr #=> [78, 19, 34, 96, 59] 您也可以尝试以下方法: (1..99).to_a.sample(5) =>[69, 5

我想生成5个不同的随机数。我已经生成了从0到100的范围。我想从范围中随机选取5个数字

您可以在Ruby中生成n个唯一随机数的列表,如下所示:

(1..99).to_a.sample(5)
=>[69, 50, 15, 68, 29]
arr = []
(1..5).each{|t| arr << rand(100)}
arr
#=> [78, 19, 34, 96, 59]

您也可以尝试以下方法:

(1..99).to_a.sample(5)
=>[69, 50, 15, 68, 29]
arr = []
(1..5).each{|t| arr << rand(100)}
arr
#=> [78, 19, 34, 96, 59]
我认为这里已经发布了更好的解决方案,这只是一个备选答案

a=[]
a = []
while true
   a << rand(101) # if you want to get 100
   break if a.uniq.count == 5
end
虽然是真的
a这可以产生两次相同的数字,OP要求“5个不同的随机数”。另外,你可以只写
5.times.map{rand(100)}
@p11y谢谢你教我这个。我已经更新了我的答案。虽然它还不优雅,但我想它现在应该可以用了。scottxu的解决方案要好得多。+1表示采用
5.times.map{rand(100)}
思想并找到一种有趣的方法来确保结果的唯一性。