Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number generator issues in Ruby

My intention here is just to fill up an array with numbers in order from 1, to a random number between 1 and 1000. However, after repeatedly running this code (about 50 times), the highest number I have gotten is 120, and only twice has it been over 100. The majority of my arrays were anywhere between 0 and 60. This behavior appears off to me. Am I doing something wrong?

my_array = []
i = 0
while i <= rand(1000)
    my_array << i 
    i += 1  
end

puts my_array.count
puts my_array
like image 668
Keith Grout Avatar asked Nov 21 '25 15:11

Keith Grout


1 Answers

Your function is broken, because you're checking versus the random number. Do this:

(0..1000).collect{ rand(1000) }

This will return an array of one thousand random numbers.

Or, closer to your code:

my_array = []
i = 0
while i <= 1000
    my_array << rand(1000) 
    i += 1  
end

As per comment, what you want is:

(1..rand(1000))

(1..rand(1000)).to_a

The first results in a range, which is "easier to carry around", the second results in the populated array.

(Edit) Note:

(1..10) is inclusive - (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.

like image 67
Narfanator Avatar answered Nov 24 '25 04:11

Narfanator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!