在Ruby中查找二维数组的总和(Finding the sum of 2D Arrays in Ruby)

编程入门 行业动态 更新时间:2024-10-27 11:15:47
在Ruby中查找二维数组的总和(Finding the sum of 2D Arrays in Ruby)

我有一个二维数组阵列。 我想创建一个新的二维数组,它可以在2D数组中找到这些值的总和。

新阵列的x,y处的总和= arr1的x,y处的总和+ arr2 +的x,y处的和。

|1,2,4| |1,1,1| |1,1,1| |2,4,6| |1,1,1| |1,1,1| |2,4,6| |1,1,1| |1,1,1| |2,4,6| |1,1,1| |1,1,1|

现在添加上面的二维数组将导致,

|3,4,6| |4,6,8| |4,6,8| |4,6,8|

如何在Ruby中实现这一点(不是任何其他语言)。 我写了一个方法,但看起来很长很丑。

I have an array of two dimensional Arrays. I want to create a new two dimensional array which finds the sum of these values in the 2D arrays.

Sum at x,y of new array = Sum at x,y of arr1 + Sum at x,y of arr2 + ....

|1,2,4| |1,1,1| |1,1,1| |2,4,6| |1,1,1| |1,1,1| |2,4,6| |1,1,1| |1,1,1| |2,4,6| |1,1,1| |1,1,1|

Now adding the above two dimensional arrays will result in,

|3,4,6| |4,6,8| |4,6,8| |4,6,8|

How to achieve this in Ruby (not in any other languages). I have written a method, but it looks very long and ugly.

最满意答案

require 'matrix' Matrix[ [1, 2, 4], [2, 4, 6], [2, 4, 6], [2, 4, 6] ] + Matrix[ [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1] ] + Matrix[ [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1] ] # => Matrix[[3, 4, 6], [4, 6, 8], [4, 6, 8], [4, 6, 8]]

或者,如果你需要与@ Jeriko的答案相同的格式,即返回一个Array而不是Matrix :

def sum_arrays(*a) return *a.map {|m| Matrix[*m] }.reduce(:+) end # data you supplied: x = [[1, 2, 4], [2, 4, 6], [2, 4, 6], [2, 4, 6]] y = [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]] z = [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]] p sum_arrays(x, y, z) # => [[3, 4, 6], [4, 6, 8], [4, 6, 8], [4, 6, 8]] require 'matrix' Matrix[ [1, 2, 4], [2, 4, 6], [2, 4, 6], [2, 4, 6] ] + Matrix[ [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1] ] + Matrix[ [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1] ] # => Matrix[[3, 4, 6], [4, 6, 8], [4, 6, 8], [4, 6, 8]]

Or, if you want the same format as in @Jeriko's answer, i.e. returning an Array instead of a Matrix:

def sum_arrays(*a) return *a.map {|m| Matrix[*m] }.reduce(:+) end # data you supplied: x = [[1, 2, 4], [2, 4, 6], [2, 4, 6], [2, 4, 6]] y = [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]] z = [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]] p sum_arrays(x, y, z) # => [[3, 4, 6], [4, 6, 8], [4, 6, 8], [4, 6, 8]]

更多推荐

本文发布于:2023-08-04 15:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417615.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   总和   Ruby   Arrays   sum

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!