I am trying to populate an array of four elements with positive integers that are less than 9.
我正在尝试使用小于9的正整数填充四个元素的数组。
Here is my code:
这是我的代码:
generated_number=Array.new(4)#create empty array of size 4
generated_number.each do |random| #for each position in the array create a random number
random=rand(10)
end
puts generated_number
I don't understand what I'm missing.
我不明白我错过了什么。
4 个解决方案
#1
27
You can pass a range to rand()
你可以将范围传递给rand()
Array.new(4) { rand(1...9) }
#2
4
I think you're over complicating things.
我认为你过度复杂化了。
generated_numbers = 4.times.map{Random.rand(8) } #=> [4, 2, 6, 8]
edit: For giggles I put together this function:
编辑:对于咯咯笑声我把这个功能放在一起:
def rand_array(x, max)
x.times.map{ Random.rand(max) }
end
puts rand_array(5, 20) #=> [4, 13, 9, 19, 13]
#3
0
This is how I solved it for an array with 10 elements:
n=10
my_array = Array.new(n)
i = 0
loop do
random_number = rand(n+1)
my_array.push(random_number)
i += 1
break if i >= n
end
for number in my_array
puts number
#4
0
This is something I did for a school final, numbers aren't exactly the same but you can change numbers and such:
这是我为学校决赛所做的事情,数字不完全相同,但你可以改变数字等等:
numbers_array = []
10.times do
numbers_array.push(rand(1..100))
end
puts numbers_array
#1
27
You can pass a range to rand()
你可以将范围传递给rand()
Array.new(4) { rand(1...9) }
#2
4
I think you're over complicating things.
我认为你过度复杂化了。
generated_numbers = 4.times.map{Random.rand(8) } #=> [4, 2, 6, 8]
edit: For giggles I put together this function:
编辑:对于咯咯笑声我把这个功能放在一起:
def rand_array(x, max)
x.times.map{ Random.rand(max) }
end
puts rand_array(5, 20) #=> [4, 13, 9, 19, 13]
#3
0
This is how I solved it for an array with 10 elements:
n=10
my_array = Array.new(n)
i = 0
loop do
random_number = rand(n+1)
my_array.push(random_number)
i += 1
break if i >= n
end
for number in my_array
puts number
#4
0
This is something I did for a school final, numbers aren't exactly the same but you can change numbers and such:
这是我为学校决赛所做的事情,数字不完全相同,但你可以改变数字等等:
numbers_array = []
10.times do
numbers_array.push(rand(1..100))
end
puts numbers_array