简体   繁体   中英

How to sum two-dimensional arrays

let's say that I have two-dimensional arrays

array= [[10,12,15,17],[16,32,65,47],[45,48,41,23],[36,25,74,98],  [32,19,66,88],...]

I would like to do this in ruby

arr = [[10+45+32+..,12+48+19,15+41+66+..,17+23+88+..],   [16+36+..,32+25+..,65+74+..,47+98+..]

Thank you in advance.

Use partition to separate and collect the even-indexed sub-arrays and odd-indexed sub-arrays. Then transpose each partition, followed by the sum of each newly formed sub-array.

array = [[10,12,15,17],[16,32,65,47],[45,48,41,23],[36,25,74,98],[32,19,66,88]]

array.partition.with_index { |_,i| i.even? }
               .map { |e| e.transpose.map(&:sum) }
#=> [[87, 79, 122, 128], [52, 57, 139, 145]]

key methods: Enumerable#partition , Integer#even? and Array#transpose . See ruby-docs for more info. If you're using Ruby versions < 2.4.0, use inject(:+) instead of sum , as follows:

array.partition.with_index { |_,i| i.even? }
               .map { |e| e.transpose.map { |e| e.inject(:+) } }
#=> [[87, 79, 122, 128], [52, 57, 139, 145]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM