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

查看:70
本文介绍了在 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.

新数组 x,y 处的总和 = arr1 的 x,y 处的总和 + arr2 的 x,y 处的总和 + ....

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|

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

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:

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]]

这篇关于在 Ruby 中查找二维数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆