Keith Grout
Keith Grout

Reputation: 909

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

Upvotes: 3

Views: 2403

Answers (3)

Narfanator
Narfanator

Reputation: 5813

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.

Upvotes: 6

pguardiario
pguardiario

Reputation: 54984

It sounds like you want:

(1...rand(1000)).to_a

Upvotes: 2

Keith Grout
Keith Grout

Reputation: 909

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

Upvotes: 0

Related Questions