> 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. Two solutions from me (you may choose if like at least one :)) The first uses hashes to store the values of a line. makes it pretty obvious what is going on (at least for the author *g*) ------------------------------------------------------------- require 'enumerator' pascal = [{0, 1}] + (1...ARGV[0].to_i).map{Hash.new(0)} pascal.each_cons(2) do |last, this| last.each{|p, v| this[p - 1] += v; this[p + 1] += v} end size = pascal.last.fetch(0, pascal.last[1]).to_s.size + 1 pascal.each do |row| line = row.sort.map{|p, v| v.to_s.center size}.join puts line.center(size * pascal.last.size).rstrip end ------------------------------------------------------------- And the other one with a completely different approach: ------------------------------------------------------------- fac = lambda{|n| n < 2 ? 1 : (1..n).inject{|f, i| f * i}} tri = lambda{|n, r| fac[n] / (fac[r] * fac[n-r])} size = lambda{|r| tri[r-1, r / 2].to_s.size + 1} line = lambda{|y, r| (0..y).map{|x| tri[y,x].to_s.center size[r]}} lines = lambda{|r| (0...r).map{|y| line[y, r]}} pascal = lambda{|r| lines[r].map{|l| l.join.center(size[r] * r).rstrip}} puts pascal[(ARGV[0] || 15).to_i] ------------------------------------------------------------- which is more like a case study of functional programming in ruby (comments welcome, that's not my primary domain) cheers Simon