Keep getting same values for rand(n1..n2) within a loop

for i in 1..numAthletes
    randomNum = 0;
    runningTotal = 0;

    randomNum = rand(30..89);
    athleteTimes['swim'] = randomNum;
    runningTotal += randomNum;

    randomNum = rand(90..119);
    athleteTimes['run'] = randomNum;
    runningTotal += randomNum;

    randomNum = rand(120..360);
    athleteTimes['bike'] = randomNum;
    runningTotal += randomNum;

    athleteTimes['total'] = runningTotal

    athleteTotal[i] = athleteTimes;

When I run the above code, I keep getting the same value sets for the hash being stored inside the subsequent hash. I'm assuming there is something I need to do to reset/reseed the random generator, but I'm unsure how to do this with in Ruby.

I tried using r = and using r.rand(n1..n2) hoping this would force the generator to be reseeded, but it did not.


You re-use the same athleteTimes hash in each iteration and therefore change existing values in the athleteTotal hash.

Instead you need to create a new hash in each iteration:

number_of_athletes.times do |i|
  swim = rand(30..89)
  run  = rand(90..119)
  bike = rand(120..360)

  athlete_total[i+1] = {
    'swim'  => swim,
    'run'   => run,
    'bike'  => bike,
    'total' => swim + run + bike

Furthermore you will notice, that I re-wrote your example using common Ruby idioms like snakecase variable names, no ; at the end of a line.

Need Your Help

Numba: How to Suppress

python-3.x numba

I keep on getting this error in my numba code: