I have a two dimensional array, which represents columns and rows of data. I need to sum both the columns and rows, but I need to total from the the new ‘summary’ row.
Data (6×5 array)
[1, 0, 3, 0, 0],
[0, 4, 0, 0, 4],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
so the result should be a 7×6 array
[1, 0, 3, 0, 0, 4],
[0, 4, 0, 0, 4, 8],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[1, 4, 3, 0, 4, 12]
I know I can sum each column and add an additional row to my two dimensional array via
# Sum the columns, add additional one row for summary
a << a.transpose.map{|x| x.reduce(:+)}
but how do I add the additional column
map! takes each element of the array, passes it to the block and replaces that element with whatever that block returns. So since we call it on a 2d array,
rowwill be a 1d array – the row of the original array.Then I calculate the sum with
reduce(:+)of that row. Then I need to append it to that row. What I’ve done here is to wrap the result of sum into an array and then used + to concatenate those two arrays.I could have also done this: