LoginSignup
0
0

More than 5 years have passed since last update.

Pascal's triangle

Last updated at Posted at 2016-09-23
pascal.lisp
(defun ncr (n r)
  "異なるN個のものから、異なるR個のものを選ぶ組合せの総数。"
  (if (or (= n r) (zerop r))
      1
      (/ (* (ncr n (1- r)) (1+ (- n r))) r)))

(defun pascal (n)
  "N+1行のパスカルの三角形を表すリスト。
(pascal 3) => ((1) (1 1) (1 2 1) (1 3 3 1)\)"
  (let ((lines nil))
    (dotimes (i (1+ n))
      (let ((l nil))
        (dotimes (j (1+ i))
          (setq l (append l (list (ncr i j)))))
        (setq lines (append lines (list l)))))
    lines))

(defun display-pascal (n)
  "N+1行のパスカルの三角形を表示する。"
  (let ((i 1) (lines (pascal n)) len)
    (setq len (length lines))
    (dolist (l lines)
      (format t "~vT~a~%" (* (- len i) 2) (format nil "~{~4D~}" l))
      (incf i))))

(display-pascal 10)

実行結果

% sbcl --script pascal.lisp
                       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

11行目がなんかズレる……。

改訂版

pascal.lisp
(defun ncr (n r)
  "異なるN個のものから、異なるR個のものを選ぶ組合せの総数。"
  (if (or (= n r) (zerop r))
      1
      (/ (* (ncr n (1- r)) (1+ (- n r))) r)))

(defun pascal (n)
  "N+1行のパスカルの三角形を表すリスト。
(pascal 3) => ((1) (1 1) (1 2 1) (1 3 3 1)\)"
  (let ((lines nil))
    (dotimes (i (1+ n))
      (let ((l nil))
        (dotimes (j (1+ i))
          (setq l (append l (list (ncr i j)))))
        (setq lines (append lines (list l)))))
    lines))

(defun display-pascal (n)
  "N+1行のパスカルの三角形を表示する。"
  (let ((i 1) (lines (pascal n)) len)
    (setq len (length lines))
    (dolist (l lines)
      (format t "~v,0T~a~%" (* (- len i) 2) (format nil "~{~4D~}" l))
      (incf i))))

(display-pascal 10)

実行結果

% sbcl --script pascal.lisp
                       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

ズレが無くなった!
anohana様、ありがとうございますm(_ _)m

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0