2012-01-10 69 views
2

我有一個二維數組,它表示列和行的數據。我需要對列和行進行求和,但我需要從新的「摘要」行中總計。二維數組 - 總和'行'並添加爲數組的新元素

數據(6×5陣列)

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

所以結果應該是一個7x6陣列

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

我知道可以總結各列,並通過

追加一行到我的二維陣列
# Sum the columns, add additional one row for summary 
a << a.transpose.map{|x| x.reduce(:+)} 

但是,如何添加附加列

回答

4
a.map! {|row| row + [row.reduce(:+)]} 

將數組的每個元素傳遞給該塊,並將該元素替換爲該塊返回的內容。因此,因爲我們將它稱爲2d數組,所以row將是1d數組 - 原始數組的行。

然後我計算該行的reduce(:+)的總和。然後我需要將它追加到該行。我在這裏完成的是將sum的結果包裝到一個數組中,然後使用+來連接這兩個數組。

我也做到了這一點:

a.map! {|row| row << row.reduce(:+) } 
+0

正是我一直在尋找!你會介意一些簡單的解釋嗎? – 2012-01-10 03:50:51

0

當我問我想出了一個解決這個問題,但我想知道是否有更好的方法。

我的解決方案

# Sum the rows (including the new summary row) 
row_sum = a.map{|x| x.reduce(:+)} 

# transpose the original array, add the summary column as a new row 
c = a.transpose << row_sum 

# transpose it back to the original view, now we have both summary of rows and columns 
c.tranpose 

更新

這是我的新簡短的回答感謝的Jakub Hampl

# Create the summary column (row totals), update the array 
a.map! {|r| r + [r.reduce(:+)]} 

# Create the summary row (column totals) 
a.transpose.map{|x| x + [x.reduce(:+)]}