home *** CD-ROM | disk | FTP | other *** search
/ ftp.cs.arizona.edu / ftp.cs.arizona.edu.tar / ftp.cs.arizona.edu / icon / historic / v941.tgz / icon.v941src.tar / icon.v941src / ipl / procs / pascltri.icn < prev    next >
Text File  |  2000-07-29  |  2KB  |  55 lines

  1. ############################################################################
  2. #
  3. #       File:     pascltri.icn
  4. #
  5. #       Subject:  Procedure to compute a row of Pascal's Triangle
  6. #
  7. #       Author:   Erik Eid
  8. #
  9. #       Date:     August 7, 1997
  10. #
  11. ############################################################################
  12. #
  13. #   This file is in the public domain.
  14. #
  15. ############################################################################
  16. #
  17. #     The procedure, when invoked by a call to PascalsTriangle(n), returns
  18. # the nth row of Pascal's Triangle in list form.  Pascal's Triangle is a
  19. # mathematical structure in which each element of a row is the sum of the
  20. # two elements directly above it.  The first few levels are:
  21. #    Row 1:          1           Triangle stored as: [[1],
  22. #        2:        1   1                              [1, 1],
  23. #        3:      1   2   1                            [1, 2, 1],
  24. #        4:    1   3   3   1                          [1, 3, 3, 1],
  25. #        5:  1   4   6   4   1                        [1, 4, 6, 4, 1]]
  26. #
  27. # For example, PascalsTriangle(4) would return the list [1, 3, 3, 1].
  28. #
  29. #     The procedure fails if n is not an integer or if it is less than one.
  30. #
  31. ############################################################################
  32.  
  33. procedure PascalsTriangle(level)    #: Pascal triangle row
  34. static tri
  35. local row, elem, temp
  36. initial tri := [[1], [1, 1]]               # Start with first two rows stored
  37.   if not (level = integer(level)) then fail
  38.   if level < 1 then fail
  39.   if level > *tri then                     # If we haven't calculated this
  40.                                            # row before, then do so and keep
  41.                                            # it statically to prevent having
  42.                                            # to do so again.
  43.     every row := *tri+1 to level do {
  44.       temp := [1]                          # First element of any row is 1.
  45.       every elem := 2 to row-1 do          # Each of the next elements is
  46.         put (temp, tri[row-1][elem-1] +    # the sum of the two above it.
  47.              tri[row-1][elem])
  48.       put (temp, 1)                        # Last element of any row is 1.
  49.       put (tri, temp)                      # Attach this row to the triangle.
  50.     }
  51.   return tri[level]                        # Return the chosen level.
  52. end
  53.  
  54.