Ruby遍历2D数组并填充随机数据
我必须生成一个动态大小的2D数组,每个子数组的第一个索引中都有一个预定值,接下来的三个索引中都有三个随机值(每个都在不同的范围内),最后是三个随机索引的计算总数。这是我到目前为止所拥有的 示例代码Ruby遍历2D数组并填充随机数据,ruby,multidimensional-array,random,Ruby,Multidimensional Array,Random,我必须生成一个动态大小的2D数组,每个子数组的第一个索引中都有一个预定值,接下来的三个索引中都有三个随机值(每个都在不同的范围内),最后是三个随机索引的计算总数。这是我到目前为止所拥有的 示例代码 一个可能的选项是使用并映射范围 例如,给定的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.
一个可能的选项是使用并映射范围 例如,给定的
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]]
因此,在基本示例中添加一些规范:
(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]]
将元素和推入数组的另一种方法是使用: 注意
运动员.dup
以避免引用同一对象
一旦看到对象(atternate
和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
改进:避免使用计数器。一个可能的选择是使用并映射范围 例如,给定的
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]]
因此,在基本示例中添加一些规范:
(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]]
将元素和推入数组的另一种方法是使用: 注意
运动员.dup
以避免引用同一对象
一旦看到对象(atternate
和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
改进:消除计数器使用。代码在生成过程中似乎挂起。在没有嵌套的运动员的情况下运行它。每个循环都会导致一次干净的跑步,但只生成一组重复的运动员数据。代码似乎在生成过程中挂起。在没有嵌套运动员的情况下运行它。每个循环都会产生一次干净的跑步,但只生成一组重复的运动员数据。因此,我尝试了您的示例代码,并在循环后打印了铁人三项全能阵列。它正在生成#{field}个相同的数组。如果我使用3作为字段的用户输入,我将得到3个相同的数组。下一个注释中的示例输出。另外,我也很感谢您的帮助。请输入参加triathalon比赛的运动员人数:3[[3,80,102,193,375],[3,80,102,193,375],[3,80,102,193,375]]我的错,在设置
triathalon
数组时,需要复制对象,以避免创建引用同一对象的数组。我编辑。请参阅:关于你的最后一句话的一个小点:你可以改为写triathalon.each.with_索引(1){|运动员,计数|..}
。参数1
导致索引(count
)从1
开始,这很方便。因此,我尝试了您的示例代码,并在循环后打印了铁人三项全能阵列。它正在生成#{field}个相同的数组。如果我使用3作为字段的用户输入,我将得到3个相同的数组。下一个注释中的示例输出。另外,我也很感谢您的帮助。请输入参加triathalon比赛的运动员人数:3[[3,80,102,193,375],[3,80,102,193,375],[3,80,102,193,375]]我的错,在设置triathalon
数组时,需要复制对象,以避免创建引用同一对象的数组。我编辑。请参阅:关于你的最后一句话的一个小点:你可以改为写triathalon.each.with_索引(1){|运动员,计数|..}
。参数1
导致索引(count
)从1
开始,这很方便。