首页 > 解决方案 > Ruby遍历二维数组并填充随机数据

问题描述

我必须在每个子数组的第一个索引中生成一个动态大小的二维数组,在每个子数组的第一个索引中生成三个随机值(每个索引都在不同的范围内),最后是三个的计算总数随机指数。这是我到目前为止所拥有的。

示例代码

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

标签: rubymultidimensional-arrayrandom

解决方案


一种可能的选择是使用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]]


将元素的总和推入数组的另一种方法是使用Object#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 }

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

一旦你看到你的对象(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

改进:摆脱计数器使用Enumerable#each_with_index


推荐阅读