Add corners of a matrix in Ruby

0

I have a square matrix. Let's say that I set it to 3 and put as data 1 to 9, the corners would be 1, 3, 7, 9.

So, I use this code to find and add them:

for i in 0..N-1
    for j in 0..N-1
        if(((i==0) || (i==N-1))&&((j==0) || (j==N-1)))
            E[i]=(M[i][j])
            sumaE+=E[i].to_i
        end
    end
end

print("Esquinas:#{E}.\nSuma=#{sumaE}")

It works because it gives me the sum as 20, but the array gives it incomplete ["1", nil, "9"]. Does anyone know how to solve nil ?

(Extra data: I think my ruby is 2.2)

    
asked by Betsadi 18.05.2017 в 02:42
source

1 answer

1

I hope I have understood what you want. and although this implementation is very different from the one you have, I hope that at least it serves as a reference.

Assuming that 'square matrix' means:

matriz = [[1,2,3], [4,5,6], [7,8,9]]

To generate an array with the ends of the array:

extremos = []
extremos << matriz[0][0] # el primero del primer array
extremos << matriz[0][-1] # el último del primer array
extremos << matriz[-1][0] # el primero del último array
extremos << matriz[-1][-1] # el último del último array

extremos # => [1,3,7,9]

To get the sum:

extremos.inject(:+) # => 20
  

Another implementation:

matriz = [[1,2,3], [4,5,6], [7,8,9]]

extremos = matriz.map{ |a| [a[0], a[-1]] }.minmax.flatten
# => [1, 3, 7, 9]

extremos.inject(:+)
# => 20
    
answered by 18.05.2017 в 03:35