在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]]更多推荐
发布评论