Pascal's triangle: Difference between revisions

→‎{{header|Common Lisp}}: improve the last version to be a bit more idiomatic, really print n lines and not n+1
(→‎{{header|Common Lisp}}: improve the last version to be a bit more idiomatic, really print n lines and not n+1)
Line 1,512:
 
<lang lisp>(defun pascal (n)
(genrow n '(1)))
 
(defun genrow (n l)
(when (< 0 n)
(print l)
(genrow (1- n) (cons 1 (newrow l)))))
 
(defun newrow (l)
(if (> 2 (length l))
'(1)
(cons (+ (car l) (cadr l)) (newrow (cdr l)))))</lang>
Line 1,527:
 
<lang lisp>(defun pascal-next-row (a)
(loop :for q :in a
:and p = 0 :then q
:as s = (list (+ p q))
:nconc s :into a
:finally (rplacd s (list 1))
(return a)))
 
(defun pascal (n)
(loop :for a = (list 1) :then (pascal-next-row a)
:repeat n
: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 print-pascal-printtriangle function determinescomputes and uses the length of the finalprinted rowlast and uses itrow to decide how wide the triangle should be.
 
<lang lisp>
(defun next-pascal-triangle-row (llist)
`(1
`(1 ,@(loop for i from 0 to (- (length l) 2)
,.(mapcar collect (#'+ (nth i l)list (nth (1+ i)rest l)list))
1))
 
(defun pascal-printtriangle (rnumber-of-rows)
(loop repeat number-of-rows
(let* ((pasc (loop with p = (list (list 1))
repeat rfor dorow = '(nconc1) pthen (list (apply #'next-pascal-triangle-row (last p)))row)
finally (returncollect p)row))
 
(len (length (format nil "~A" (car (last pasc))))))
(defun print-pascal-triangle (number-of-rows)
(format t (format nil "~~{~~~D:@<~~{~~A ~~}~~>~~%~~}" len) pasc)))
(let* ((triangle (pascal-triangle number-of-rows))
(max-row-length (length (write-to-string (first (last triangle))))))
(format t
(format t (format nil "~~{~~~D:@<~~{~~A ~~}~~>~~%~~}" len) pasc))max-row-length)
triangle)))
</lang>
 
For example:
 
<lang lisp>(print-pascal-printtriangle 4)</lang>
<lang>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
</lang>
<lang lisp>(print-pascal-printtriangle 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>
 
Anonymous user