-
-
Save MauricioRibeiroA/b5467945da622a01462e54dd8ff3f860 to your computer and use it in GitHub Desktop.
Retrieve diagonals from array of arrays in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
def diagonals | |
[self, self.map(&:reverse)].inject([]) do |all_diags, matrix| | |
((-matrix.count + 1)..matrix.first.count).each do |offet_index| | |
diagonal = [] | |
(matrix.count).times do |row_index| | |
col_index = offet_index + row_index | |
diagonal << matrix[row_index][col_index] if col_index >= 0 | |
end | |
all_diags << diagonal.compact if diagonal.compact.count > 1 | |
end | |
all_diags | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment