Skip to content

Instantly share code, notes, and snippets.

@RussellAndrewEdson
Last active August 29, 2015 14:12
Show Gist options
  • Save RussellAndrewEdson/de9352753d2969b85197 to your computer and use it in GitHub Desktop.
Save RussellAndrewEdson/de9352753d2969b85197 to your computer and use it in GitHub Desktop.
Clojure code for Pascal's Triangle.
(defn pascal
"Returns the number in the given row and column of
Pascal's triangle."
[row column]
(cond (= column 1) 1
(= column row) 1
(> column row) 0
:else (+ (pascal (- row 1) (- column 1))
(pascal (- row 1) column)))))
(defn make-pascal-triangle
"Creates an nxn matrix containing Pascal's triangle."
[n]
(vec (for [i (range 1 (inc n))]
(into [] (for [j (range 1 (inc n))]
(pascal i j))))))
(println (apply str
(map #(str % "\n")
(for [row (make-pascal-triangle 5)]
(clojure.string/join " " row)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment