[ create a new paste ] login | about

Project: programmingpraxis
Link: http://programmingpraxis.codepad.org/Qb5pOMrj    [ raw code | output | fork ]

programmingpraxis - Scheme, pasted on Nov 22:
; pascal's triangle

(define (string-join sep ss)
  (define (f s ss)
    (string-append s (string sep) ss))
  (define (join ss)
    (if (null? (cdr ss)) (car ss)
      (f (car ss) (join (cdr ss)))))
  (if (null? ss) "" (join ss)))

(define (sums xs)
  (let loop ((xs xs) (zs (list)))
    (if (null? (cdr xs))
        (reverse zs)
        (loop (cdr xs)
              (cons (+ (car xs) (cadr xs)) zs)))))

(define (pascal n)
  (let loop ((n n) (tri (list (list 1))))
    (if (zero? n)
        (reverse tri)
        (loop (- n 1)
          (cons (append (list 1)
                        (sums (car tri))
                        (list 1))
                tri)))))

(define (display-pascal width tri)
  (let loop ((tri tri))
    (when (pair? tri)
      (let* ((str (string-join #\space (map number->string (car tri))))
             (len (string-length str)))
        (display (make-string (quotient (- width len) 2) #\space))
        (display str)
        (newline))
      (loop (cdr tri)))))

(display-pascal 35 (pascal 10))


Output:
1
2
3
4
5
6
7
8
9
10
11
                 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
    1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1


Create a new paste based on this one


Comments: