不同大小的阵列的总和 [英] Sum of arrays of different size

查看:111
本文介绍了不同大小的阵列的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其元素是不同大小的阵列,说:

  [45,96,0.0,96,96,96,0.0],[04,55,06,55,04,04,02,55]

我想找到两个数组的总和,即,

  49,151,...]


解决方案

您可以使用这样的:

  a.flat_map {| X | x.in_groups_of(a.max_by(安培;:大小).size,0)} transpose.map(安培;:总和)。

或者这样:

  a.max_by(安培;:大小).map.with_index {| _,我| a.sum {| X | X [I] || 0}}

I have an array, whose elements are arrays of different sizes, say:

[[45, 96, 0.0, 96, 96, 96, 0.0], [04, 55, 06, 55, 04, 04, 02, 55]]

I want to find the sum of the two arrays, i.e.,

[49, 151, ...]

解决方案

You can use something like this:

a.flat_map{|x| x.in_groups_of(a.max_by(&:size).size, 0)}.transpose.map(&:sum)

Or this:

a.max_by(&:size).map.with_index{|_, i| a.sum{|x| x[i]||0}}

这篇关于不同大小的阵列的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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