在一个循环中继续为 rand(n1..n2) 获取相同的值

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

当我运行上面的代码时,我一直在为存储在后续哈希中的哈希获取相同的值集。我假设我需要对 reset/reseed 随机生成器做一些事情,但我不确定如何在 Ruby 中做到这一点。

我尝试使用 r = Random.new 并使用 r.rand(n1..n2) 希望这会强制重新播种生成器,但它没有。

您在每次迭代中重复使用相同的 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 变量名称)重写了您的示例,行尾没有 ;