1
votes

how to write a method that accepts two square matrices (nxn two dimensional arrays), and return the sum of the two. Both matrices being passed into the method will be of size nxn (square), containing only integers.

How to sum two matrices: Take each cell [n][m] from the first matrix, and add it with the [n][m] cell from the second matrix. This will be cell [n][m] in the solution matrix.

like:

|1 2 3|
|3 2 1|
|1 1 1|
+
|2 2 1|
|3 2 3|
|1 1 3|
=
|3 4 4|
|6 4 4|
|2 2 4|



matrix_addition( [ [1, 2, 3], [3, 2, 1,], [1, 1, 1] ], [ [2, 2, 1], [3, 2, 3], [1, 1, 3] ] )
returns [ [3, 4, 4], [6, 4, 4], [2, 2, 4] ]
3
have you tried anything? what have you tried?Uri Agassi

3 Answers

7
votes

Even though it is possible to define method to do so, it is much easier to use ruby build in Matrix library for this:

require 'matrix'

m1 = Matrix[ [1, 2, 3], [3, 2, 1], [1, 1, 1] ]
m2 = Matrix[ [2, 2, 1], [3, 2, 3], [1, 1, 3] ]

sum = m1 + m2
3
votes

Yes, certainly, use the Matrix class methods, but here is a way using recursion that might be of interest.

Code

def sum_arrays(a1, a2)
  t = a1.zip(a2)
  t.map { |e1,e2| (e1.is_a? Array) ? sum_arrays(e1,e2) : e1+e2 }
end

Examples

a1 = [1,2,3]
a2 = [4,5,6]
sum_arrays(a1, a2)
  #=> [5, 7, 9]

a1 = [[1,2,3], [4,5]]
a2 = [[6,7,8], [9,10]]
sum_arrays(a1, a2)
  #=> [[7, 9, 11], [13, 15]]

a1 = [[[ 1,  2,  3], [ 4,  5]],
      [[ 6,  7], [ 8,  9, 10]]] 
a2 = [[[11, 12, 13], [14, 15]],
      [[16, 17], [18, 19, 20]]]
sum_arrays(a1, a2)
 #=> [[[12, 14, 16], [18, 20]],
 #    [[22, 24], [26, 28, 30]]]

Generalization

You could make greater use of this method by passing an operator.

Code

def op_arrays(a1, a2, op)
  t = a1.zip(a2)
  t.map { |e1,e2| (e1.is_a? Array) ? op_arrays(e1,e2,op) : e1.send(op,e2) }
end

Examples

a1 = [[1,2,3], [4,5]]
a2 = [[6,7,8], [9,10]]

op_arrays(a1, a2, '+') #=> [[7, 9, 11], [13, 15]]
op_arrays(a1, a2, '-') #=> [[-5, -5, -5], [-5, -5]]
op_arrays(a1, a2, '*') #=> [[6, 14, 24], [36, 50]]

You could alternatively pass the operator as a symbol:

op_arrays(a1, a2, :+)
  #=> [[7, 9, 11], [13, 15]]
0
votes

Have you used ruby Matrix class? It has #+ operator (mimic method).