在循环中保持rand(n1..n2)的值相同

时间:2016-02-13 18:57:09

标签: ruby random hashmap random-seed

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;
end

当我运行上面的代码时,我一直在为后续哈希中存储的哈希获取相同的值集。我假设我需要做一些事情来重置/重新设置随机生成器,但我不确定如何在Ruby中执行此操作。

我尝试使用r = Random.new并使用r.rand(n1..n2)希望这会强制重新生成发生器,但事实并非如此。

1 个答案:

答案 0 :(得分:4)

您在每次迭代中重复使用相同的athleteTimes哈希值,因此会更改athleteTotal哈希值中的现有值。

相反,您需要在每次迭代中创建一个新哈希:

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
  }
end

此外,您会注意到,我使用常见的Ruby惯用语来重写您的示例,例如snakecase变量名,行末尾没有;