Pascal's triangle: Difference between revisions
Content added Content deleted
(Added Algol W) |
(→{{header|Common Lisp}}: Added another solution using pretty-printing) |
||
Line 1,196: | Line 1,196: | ||
:repeat n |
:repeat n |
||
:collect a))</lang> |
:collect a))</lang> |
||
Another iterative solution, this time using pretty-printing to automatically print the triangle in the shape of a triangle in the terminal. The pascal-print function determines the length of the final row and uses it to decide how wide the triangle should be. |
|||
<lang lisp> |
|||
(defun next-pascal (l) |
|||
`(1 ,@(loop for i from 0 to (- (length l) 2) |
|||
collect (+ (nth i l) (nth (1+ i) l))) |
|||
1)) |
|||
(defun pascal-print (r) |
|||
(let* ((pasc (loop with p = (list (list 1)) |
|||
repeat r do (nconc p (list (apply #'next-pascal (last p)))) |
|||
finally (return p))) |
|||
(len (length (format nil "~A" (car (last pasc)))))) |
|||
(format t (format nil "~~{~~~D:@<~~{~~A ~~}~~>~~%~~}" len) pasc))) |
|||
</lang> |
|||
For example: |
|||
<lang lisp>(pascal-print 4)</lang> |
|||
<lang> |
|||
1 |
|||
1 1 |
|||
1 2 1 |
|||
1 3 3 1 |
|||
1 4 6 4 1 |
|||
</lang> |
|||
<lang lisp>(pascal-print 8)</lang> |
|||
<lang> |
|||
1 |
|||
1 1 |
|||
1 2 1 |
|||
1 3 3 1 |
|||
1 4 6 4 1 |
|||
1 5 10 10 5 1 |
|||
1 6 15 20 15 6 1 |
|||
1 7 21 35 35 21 7 1 |
|||
1 8 28 56 70 56 28 8 1 |
|||
</lang> |
|||
=={{header|D}}== |
=={{header|D}}== |