How to fill an array with random numbers?

I am trying to fill 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 am missing.

+6
source share
3 answers

You can pass a range to rand()

 Array.new(4) { rand(1...9) } 
+21
source

I think you're making it too complicated.

  generated_numbers = 4.times.map{Random.rand(8) } #=> [4, 2, 6, 8] 

edit: for a giggle, 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
source

Here 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 
0
source

Source: https://habr.com/ru/post/972795/


All Articles