--------------010107070200090108040004
Content-Type: text/plain; charset=ISO-8859-15
Content-Transfer-Encoding: 7bit
Hello,
you can take this as negative example, cause I store the triangle and
the formatted output :) Thus it's much slower than most solutions.
kind regards
Robert
--------------010107070200090108040004
Content-Type: text/plain;
name ascal_triangle.rb"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
filename ascal_triangle.rb"
#!C:\ruby\bin\ruby.exe
class PTriangle
def build num
@body rray.new
# fill the empty triangle
# using non-recursive algo
( num + 1 ).times do | row |
row.times do | pos |
if pos 0 or pos row - 1
number
else
number body[ row - 2 ][ pos - 1 ] + @body[ row - 2 ][ pos ]
end
@body[ row - 1 ] || ]
@body[ row - 1 ][ pos ] umber
end
end
@body
end
def render
@rendered ]
# calculate maximum number length
# needed for alignment
max body.last[ @body.last.size / 2 ].to_s.size
# shift all lines to the right if a new line is added
# right justify all numbers
@body.each do | row |
@rendered.map! { | line | ' ' * max << line }
@rendered << row.map { | num | num.to_s.rjust( max * 2, ' ' ) }.join
end
# cleanup, don't know how to do it more elegant
# remove not necessary indentation
@rendered.map! { | line | line[ ( max * 2 - 1 )..-1 ] }
end
end
if __FILE__ $0
level RGV.first.to_i
level unless level > 0
pt Triangle.new
pt.build level
puts pt.render
end
--------------010107070200090108040004--