ruby - 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
解决方案
一种可能的选择是使用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
避免引用同一个对象。
一旦你看到你的对象(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。
推荐阅读
- amazon-web-services - 通过 API 从不同的 cloudformation 堆栈调用 lambda 函数
- r - 使用 R 在钟形曲线信号中查找峰值
- python - 用 beautifulsoup 解析页面
- visual-studio-code - 输入在 Visual Studio Code 中不起作用
- python - 如何使用 Pygal 和 Python 在世界地图中显示字符串数据?
- reactjs - setState 如何在幕后更新 DOM?
- python - 如何同时显示聚合值和非聚合值?
- javascript - 如何让用户看到正在下载的 Azure blob 存储文件,而不是在 Angular 的网络选项卡本身中下载完整的流
- javascript - Webpack:带有样式加载器的捆绑包的 CSS 顺序
- python - 当对实例的所有引用都被销毁(Python)时,在类实例中启动的线程会发生什么?