Skip to content

Instantly share code, notes, and snippets.

@MauricioRibeiroA
Forked from EvilScott/diagonals.rb
Created February 16, 2017 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MauricioRibeiroA/d099c6c3fa739140e46a5534482e92cb to your computer and use it in GitHub Desktop.
Save MauricioRibeiroA/d099c6c3fa739140e46a5534482e92cb to your computer and use it in GitHub Desktop.
Retrieve diagonals from array of arrays in Ruby
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