Ruby getting the diagonal elements in a 2d Array
Better might be a one-liner that utilizes the Matrix library:
require 'matrix'
Matrix.rows(array).each(:diagonal).to_a
puts (0..2).collect { |i| array[i][i] }
Ruby snippet based off of Get all the diagonals in a matrix/list of lists in Python
This is to get all the diagonals. Anyway, the idea is to pad the array from different sides so the diagonals align up in the rows and columns:
arr = [[1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8], [2, 3, 4, 5]]
# pad every row from down all the way up, incrementing the padding.
# so: go through every row, add the corresponding padding it should have.
# then, grab every column, that’s the end result.
padding = arr.size - 1
padded_matrix = []
arr.each do |row|
inverse_padding = arr.size - padding
padded_matrix << ([nil] * inverse_padding) + row + ([nil] * padding)
padding -= 1
end
padded_matrix.transpose.map(&:compact)