Skip to content

Instantly share code, notes, and snippets.

@phyous
Created February 26, 2014 04:37
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 phyous/9223633 to your computer and use it in GitHub Desktop.
Save phyous/9223633 to your computer and use it in GitHub Desktop.
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