首页 > 解决方案 > 计算嵌套数组中整数的总和,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 

我该如何处理?你会推荐什么资源?

标签: arraysruby

解决方案


这是计算所需结果的另外两种方法。

arr = [[10, 0], [3, 5], [5, 8]]

使用数组#transpose

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_vectorMatrix::column_vectorMatrix#[]。请注意,实例方法[]记录在Object.


推荐阅读