【问题标题】:Calculating the sum of integers in a nested array, Ruby计算嵌套数组中整数的总和,Ruby
【发布时间】:2020-12-22 17:45:59
【问题描述】:

我刚开始学习 Ruby,所以请多多包涵。我正在处理一个 7 kyu Ruby 编码挑战,我的任务是找出公共汽车上剩下多少人(第一个值代表人们在,第二个值,人们离开)请查看代码中的 cmets 以获取更多详细信息。

下面是一个测试示例:

([[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]])。这样,读者可以在没有定义它们的情况下引用答案和 cmets 中的变量(例如,arr)。此外,输入都应该是有效的 Ruby 对象。你的无效,因为逗号,括号是多余的。应始终显示预期的结果,您已在此处完成。
  • 谢谢,下次再做。

标签: arrays ruby


【解决方案1】:

有很多方法可以实现这一点。这是inject

arr.map { |inner_array| inner_array.inject(&:-) }.inject(&:+)

遍历数组并计算每个位置的人数,即公交车上会剩下多少人(这可以返回负整数)。这将返回

[10, -2, -3]
[10 on, none off][3 on, 5 off][5 on, 8 off]

然后在每个元素之间注入一个+ 运算符来计算公交车上剩余人数的总和。这仅适用于您从 0 人开始和 0 人开始计数。

【讨论】:

  • 注意inject不需要block,也可以将操作名作为Symbol,例如arr.map { |inner_array| inner_array.inject(:-) }.inject(:+)。此外,外部inject 只是sum:arr.map { |inner_array| inner_array.inject(:-) }.sum
  • 正确,注意 sum 仅在 ruby​​ 2.4 及更高版本 (IIRC) 中可用
【解决方案2】:

这里有另外两种计算期望结果的方法。

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

使用Array#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 

使用Matrix 方法

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 中。

【讨论】:

  • 我无法找到实例方法 Matrix#*(矩阵。乘法)的 Ruby 文档。读者可以帮忙吗?
【解决方案3】:

sum 接受一个块,在这种情况下非常简单:

arr = [[10, 0], [3, 5], [5, 8]]
p arr.sum{|on, off| on - off}  # => 5

所以你很接近。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 2020-11-05
    • 2022-01-24
    • 1970-01-01
    • 2018-12-10
    相关资源
    最近更新 更多