我在这里的意图只是用数字从 1 到 1 到 1000 之间的随机数填充一个数组。但是,在重复运行此代码(大约 50 次)之后,我得到的最高数字是 120,并且只有两次超过 100。我的大多数数组都在 0 到 60 之间。这种行为对我来说似乎很奇怪。难道我做错了什么?
my_array = []
i = 0
while i <= rand(1000)
my_array << i
i += 1
end
puts my_array.count
puts my_array
您的功能已损坏,因为您正在检查随机数。做这个:
(0..1000).collect{ rand(1000) }
这将返回一个包含一千个随机数的数组。
或者,更接近您的代码:
my_array = []
i = 0
while i <= 1000
my_array << rand(1000)
i += 1
end
根据评论,您想要的是:
(1..rand(1000))
(1..rand(1000)).to_a
第一个结果是一个“更容易携带”的范围,第二个结果是填充数组。
(编辑)注意:
(1..10)
是包容的 -(1..10).to_a == [1,2,3,4,5,6,7,8,9,10]
(1...10)
is partially exclusive - (1...10).to_a == [1,2,3,4,5,6,7,8,9]
- it does not include the end of the array, but still includes the beginning.
It sounds like you want:
(1...rand(1000)).to_a
Additionally, I have amended my code to reflect what I was trying to accomplish initially. My problem was that every time I looped through my code I generated a new random number. Because of this, as 'i' incremented toward 1000 it became more and more likely that a random number would be generated that was lower than 'i'. My fix, while not as elegant as the solution above that I accepted, was to store the random number in a variable, BEFORE attempting to use it in a loop. Thanks again. Here is the amended code:
my_array = []
i = 0
g = rand(1000)
while i <= g
my_array << i
i += 1
end
puts my_array.count
puts my_array