Last active
December 28, 2015 22:59
-
-
Save avanishgiri/7575283 to your computer and use it in GitHub Desktop.
This file contains 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
### ALGORITHM ### | |
# for each index 0 .. last_index | |
#for each index i .. 0 | |
# during each iteration of the inner loop | |
# we store one member of a diagonal from the upper-left half | |
# and the element that reflects it across the line y=x (the middle diagonal) | |
# the member from the upper-left half is at index [i-j][i] | |
# we push this member into the final array at index i | |
# the member from the bottom half, that mirrors the above member | |
# is at the above index plus an offset of (last_index - i),(last_index - i) | |
# we push this member into the final array at index i + (2 * offset) | |
# in order to avoid double counting the elements from the middle diagonal | |
# we check to see that that mirror_diagonal is not the same as the middle_diagonal | |
# in the case that they are the same, we are at the middle diagonal, | |
# so we avoid inserting the element (the mirror of the middle diagonal is itself) | |
matrix = ('a'..'y').each_slice(5).to_a | |
def all_diagonals(m) | |
len = m[0].length | |
diagonals = Array.new(2*len - 1){[]} #Create array of empty arrays | |
#The num of diagonals is 2 * (matrix length) - 1 | |
middle_diagonal_index = last_index = len - 1 | |
0.upto(last_index) do |i| | |
offset = last_index - i | |
mirror_diagonal_index = i + 2*offset | |
i.downto(0) do |j| | |
diagonals[i] << m[i-j][j] | |
if mirror_diagonal_index != middle_diagonal_index | |
diagonals[mirror_diagonal_index] << m[i-j+offset][j+offset] | |
end | |
end | |
end | |
diagonals | |
end | |
matrix.each { |i| p i } | |
puts; puts; | |
p all_diagonals(matrix) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment