Ruby通过2D阵列迭代并使用随机数据填充



我必须在每个子数组的第一个索引中生成一个动态尺寸的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

一个可能的选项是使用范围并使用枚举的#映射范围绘制范围。

例如,给定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]]


将元素总和推入数组的另一种方法是使用对象#tap:

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

这允许编写一个衬里(使用数组#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避免引用同一对象。

一旦看到对象(athletetriathalon),您就可以意识到,不需要迭代嵌套数组,只需通过索引访问:

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

改进:要摆脱计数器,请使用枚举#enter_with_index。

最新更新