我必须在每个子阵列的第一个索引中生成一个具有预定值的动态大小的2D数组,在以下三个索引中的每一个中有三个随机值(每个都落在不同的范围内),最后,计算出三个的总数。随机指数。这是我到目前为止所拥有的。
print("Please enter the number of athletes competing in the triathalon: ")
field=gets.to_i
count=1
athlete = Array.new(5)
triathalon = Array.new(field){athlete}
triathalon.each do
athlete.each do
athlete.insert(0,count)
athlete.insert(1,rand(30..89))
athlete.insert(2,rand(90..119))
athlete.insert(3,rand(120..360))
#calculate total time per athlete
athlete.insert(4,athlete[1]+athlete[2]+athlete[3])
count+=1
end
end
一种可能的选择是使用Range并使用Enumerable#map映射范围。
例如给予n = 3
运动员,基本的例子:
(1..n).map { |n| [n] } #=> [[1], [2], [3]]
因此,在基本示例中添加一些规范:
n = 3
res = (1..n).map do |n|
r1 = rand(30..89)
r2 = rand(90..119)
r3 = rand(120..360)
score = r1 + r2 + r3
[n, r1, r2, r3, score]
end
#=> [[1, 38, 93, 318, 449], [2, 64, 93, 259, 416], [3, 83, 93, 343, 519]]
[5,10,15].tap{ |a| a << a.sum } #=> [5, 10, 15, 30]
所以你可以写:
[rand(30..89), rand(90..119), rand(120..360)].tap{ |a| a << a.sum }
这允许写一个班轮(使用Array#unshift):
(1..n).map { |n| [rand(30..89), rand(90..119), rand(120..360)].tap{ |a| a << a.sum }.unshift n }
可视化设置:
field = 3 # no user input for example
p athlete = Array.new(5) #=> [nil, nil, nil, nil, nil]
p triathalon = Array.new(field){athlete.dup} #=> [[nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil]]
注意athlete.dup
以避免引用同一个对象。
一旦看到对象(athlete
和triathalon
),就可以意识到不需要迭代嵌套数组,只需通过索引访问:
count=1
triathalon.each do |athlete|
athlete[0] = count
athlete[1] = rand(30..89)
athlete[2] = rand(90..119)
athlete[3] = rand(120..360)
athlete[4] = athlete[1] + athlete[2] + athlete[3]
count+=1
end
改进:摆脱反击使用Enumerable#each_with_index。