arrays - 计算嵌套数组中整数的总和,Ruby
问题描述
我对学习 Ruby 很陌生,所以请多多包涵。我正在处理 7 kyu Ruby 编码挑战,我的任务是找出公交车上剩下多少人(第一个值代表人们在,第二个值,人们离开)请查看代码中的注释以获取更多详细信息。
下面是一个测试示例:
([[10, 0], [3, 5], [5, 8]]), # => should return 5"
到目前为止,这是我的解决方案:
def number(bus_stops)
bus_stops.each{ | on, off | on[0] -= off[1] }
end
bus_stops
# loop through the array
# for the first array in the nested array subtract second value from first
# add the sum of last nested array to first value of second array and repeat
# subtract value of last element in nested array and repeat
我该如何处理?你会推荐什么资源?
解决方案
这是计算所需结果的另外两种方法。
arr = [[10, 0], [3, 5], [5, 8]]
arr.transpose.map(&:sum).reduce(:-)
#=> 5
步骤如下。
a = arr.transpose
#=> [[10, 3, 5], [0, 5, 8]]
b = a.map(&:sum)
#=> [18, 13] ([total ons, total offs])
b.reduce(:-)
#=> 5
使用矩阵方法
require 'matrix'
(Matrix.row_vector([1] * arr.size) * Matrix[*arr] * Matrix.column_vector([1,-1]))[0,0]
#=> 5
步骤如下。
a = [1] * arr.size
#=> [1, 1, 1]
b = Matrix.row_vector(a)
#=> Matrix[[1, 1, 1]]
c = Matrix[*arr]
#=> Matrix[[10, 0], [3, 5], [5, 8]]
d = b * c
#=> Matrix[[18, 13]]
e = Matrix.column_vector([1,-1])
#=> Matrix[[1], [-1]]
f = d * e
#=> Matrix[[5]]
f[0,0]
#=> 5
请参阅Matrix::[]、Matrix::row_vector、Matrix::column_vector和Matrix#[]。请注意,实例方法[]
记录在Object
.
推荐阅读
- java - Java 中 if else 语句中的多个布尔值始终为 false
- reactjs - 在 TypeScript 中应用 React 组件道具的严格推理/形状
- c# - 我的 dotnet ef 工具不能使用相同的 dotnet sdk 和包参考?
- python - Heroku 上的 Telegram 机器人请求用户输入的问题
- json - 保护 WordPress Rest API 仅从我的 Android 应用程序访问
- r - 从 LRS 获取 xAPI 语句
- pandas - 将字典列表转换为数据框时处理缺失值
- python - 为什么精灵没有出现在pygame中?
- css - 如何根据值定义语法提供 CSS 代码建议
- python-telegram-bot - 如何在电报机器人api中的一个命令中获取多个输入?