# Re: pp Pascal (#84)

**URL:** <https://www.ruby-forum.com/t/re-pp-pascal-84/64480>\
**Category:** Ruby\
**Created:** [June 26, 2006, 9:59am UTC](https://www.ruby-forum.com/t/re-pp-pascal-84/64480 "2006-06-26T09:59:23Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Derek\_Poon](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/b5e925/32.png) [@Derek\_Poon](https://www.ruby-forum.com/u/Derek_Poon)\
**Post date:** [June 26, 2006, 9:59am UTC](https://www.ruby-forum.com/t/re-pp-pascal-84/64480/1 "2006-06-26T09:59:23Z")

</div>

This solution works pretty quickly. On a P4 1.8 GHz:

$ time ./pp\_pascal.rb 185 \> /dev/null  
real 0m0.412s  
user 0m0.368s  
sys 0m0.041s

Anything larger than 185 rows fails due to stack overflow.

########################################################################

# 

class Pascal  
class \<\< self  
# Entry of Pascal’s Triangle (numbering rows and columns starting  
# from zero).  
def entry(row, col)  
@entry ||= []  
@entry[row] ||= [1] # Base case: entry(any\_row, 0) =\> 1

```
   if 2 * col > row # Take advantage of symmetry
     entry(row, row - col)
   else # Recurse with memoization
     @entry[row][col] ||= entry(row - 1, col - 1) + entry(row -

```

1, col)  
end  
end  
end

attr\_accessor :rows

def initialize(rows)  
self.rows = rows  
end

def to\_s  
# Make each entry wide enough for the largest number and its  
padding  
max\_entry = Pascal.entry(rows - 1, (rows - 1) / 2)  
entry\_width = 2 + max\_entry.to\_s.length  
line\_width = rows \* entry\_width

```
 (0...rows).collect do |row|
   (0..row).collect do |col|
     Pascal.entry(row, col).to_s.center(entry_width)
   end.join.center(line_width)
 end.join("\n")

```

end  
end

puts Pascal.new(ARGV[0].to\_i)
