Hi!

At Fri, 23 Jun 2006 22:31:52 +0900, Ruby Quiz wrote:

> I recently showed a friend what an amazing language Ruby was, by
> quickly programming up a script to calculate Fibonacci's Sequence,
> and his first response was: "Can you do Pascal's Triangle?"  So I
> did, which proved harder than expected.

Besides the necessary comment that the triangle presented as "Pascal's
Triangle" is already present in the famous Chinese mathematician Zhu
Shijie's "Precious Mirror of the Four Elements" that dates back to
1303 here's my solution:


exit 1 if ARGV.length != 1 || ARGV[0] =~ /[^\d]/
rows = Array.new
current = [1]
rows.push current.dup
(ARGV[0].to_i + 1).times do |row|
  (current.length - 2).times { |i| current[i] += current[i + 1] }
  current[0...0], current[-1] = 1, 1
  rows.push current.dup
end
fieldsize = rows.last.map { |n| n.to_s.length }.max
rows.each_with_index do |row, n|
  print ' ' * (fieldsize + 1) * (rows.length - n - 1)
  puts row.map { |elem| elem.to_s.rjust(fieldsize) + ' ' * (fieldsize + 2) }.join
end


Concerning performance:

time ruby pascal.rb 666 > /dev/null

real    0m7.683s
user    0m7.608s
sys     0m0.044s

I'm using the 32 bit edition of Fedora Core 5 on an Athlon 3700+
running at 2,2 GHz featured with 1 GB RAM.

Josef 'Jupp' Schugt