Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I populate an array with random numbers?

Tags:

I am trying to populate an array of four elements with positive integers that are less than 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.

like image 350
Laur Stefan Avatar asked Jul 24 '14 21:07

Laur Stefan


People also ask

How do you fill an array with random numbers?

Since Math. random() returns random double value between 0 and 1 , we multiply it by 100 to get random numbers between 0 to 100 and then we cast it into type int . To store random double values in an array we don't need to cast the double value returned by Math. random() function.

How do you make an array of random values?

Use Math. random() and Math. floor() method to get the random values. Push the values one by one in the array (But this approach may generate repeated values).


2 Answers

You can pass a range to rand()

Array.new(4) { rand(1...9) }
like image 132
fbonetti Avatar answered Sep 20 '22 18:09

fbonetti


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]
like image 26
J-Dizzle Avatar answered Sep 22 '22 18:09

J-Dizzle