Created
February 26, 2014 04:37
-
-
Save phyous/9223633 to your computer and use it in GitHub Desktop.
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 pascalsTriangle(n) | |
return [] if n < 0 | |
return [1] if n == 0 | |
ret = Array.new(n, []).map.each_with_index {|a, i| a = Array.new(i+1,1)} | |
(1..n-1).each do |y| | |
(0..y).each do |x| | |
idy1 = y - 1 | |
idx1 = x - 1 | |
idy2 = y - 1 | |
idx2 = x | |
s1 = idy1 >= 0 && idx1 >= 0 && !ret[idy1][idx1].nil? ? ret[idy1][idx1] : 0 | |
s2 = idy2 >= 0 && idx2 >= 0 && !ret[idy2][idx2].nil? ? ret[idy2][idx2] : 0 | |
ret[y][x] = s1+s2 | |
end | |
end | |
ret.flatten | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment