Pages

Tuesday, March 29, 2011

Exercise 1.12: Pascal's Triangle

The following pattern of numbers is called Pascal's Triangle
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1
Write a procedure the computes elements of Pascal's triangle by means of a recursive process.
My biggest problem with this exercise was that I didn't understand what it was asking. What input is the procedure supposed to take? I originally thought that I should take a number, and print out that many rows of the triangle. Then I realized I don't really know how to print out data like that in Scheme. So I peeked at a solution online, and realized the procedure is supposed to take the row and column, and return the number. The following procedure does that. The terminating condition for the recursion is when the column is either the first one, or the last one in the row. In both those cases the result is 1.

(define (pascal row column)
  (if (or (= 1 column)
          (= row column))
      1
      (+ (pascal (- row 1) column)
  (pascal (- row 1) (- column 1)))))