Last active
January 3, 2016 08:09
-
-
Save stevenbarragan/8434248 to your computer and use it in GitHub Desktop.
From a n x n array print out all the diagonals
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
def diagonal(a) | |
x = y = 0 | |
out = [] | |
limit = a.size - 1 | |
(0..limit * 2).each do | |
out << down(x,y,a) | |
x += 1 if y == limit | |
y += 1 if y < limit | |
end | |
out | |
end | |
def down(x,y,a) | |
out = [] | |
while y >= 0 && x < a.size | |
out << a[x][y] | |
x += 1 | |
y -= 1 | |
end | |
out | |
end | |
describe '#down' do | |
it 'return the correct diagonal from 0,3' do | |
expect(down(0,3,[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]])).to eq [4,3,2,1] | |
end | |
it 'return the correct diagonal from 1,3' do | |
expect(down(1,3,[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]])).to eq [4,3,2] | |
end | |
it 'return the correct diagonal from 0,0' do | |
expect(down(0,0,[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]])).to eq [1] | |
end | |
end | |
describe '#diagonal' do | |
it 'return the correct diagonals' do | |
expect(diagonal [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]).to eq [[1],[2,1],[3,2,1],[4,3,2,1],[4,3,2],[4,3],[4]] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment