2010-06-10 132 views
1

我有一個陣列的二維陣列。我想創建一個新的二維數組,它可以在2D數組中找到這些值的總和。查找Ruby中2D陣列的總和

薩姆位於x,新的數組的Y =薩姆位於x,ARR1 +薩姆Y的位於x,ARR2 + Y的....

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

現在添加上述二維陣列將導致在,

|3,4,6| 
|4,6,8| 
|4,6,8| 
|4,6,8| 

如何在Ruby中實現這一點(不是任何其他語言)。我寫了一個方法,但看起來很長很醜。

回答

5
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

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

甜!感謝Jorg! – bragboy 2010-06-10 13:46:00

2

假設每個陣列具有相同的尺寸,你可以使用下面的代碼:(讓我知道,如果你想它的任何解釋)

# returns an array 
# where each element (x,y) 
# is the sum of all elements (x,y) from an arbitrary number of arrays 

def sum_arrays *a 
    arr = [] 
    a[0].each_index do |r|  # iterate through rows 
    row = [] 
    a[0][r].each_index do |c| # iterate through columns 
     # get sum at these co-ordinates, and add to new row 
     row << a.inject(0) { |sum,e| sum += e[r][c] } 
    end 
    arr << row # add this row to new array 
    end 
    arr # return new array 
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]]  

print sum_arrays x,y,z 
# => [[3,4,6],[4,6,8],[4,6,8],[4,6,8]] 

希望這有助於!

+0

謝謝Jerkio! – bragboy 2010-06-10 13:46:25