Skip to content

Instantly share code, notes, and snippets.

@jackcallister
Created May 10, 2020 07:44
Show Gist options
  • Save jackcallister/14c6a1b72ef207ac0ce4418b70b1b451 to your computer and use it in GitHub Desktop.
Save jackcallister/14c6a1b72ef207ac0ce4418b70b1b451 to your computer and use it in GitHub Desktop.
;; Objective ; print out x rows of pascals trianlge
;; https://www.mathsisfun.com/pascals-triangle.html
;; (factorial 4) => 4 * 3 * 2 * 1 = 24
(defn factorial [n]
(reduce * (range 1 (inc n))))
;; (binomial-coefficient n k) => n! / k!(n-k)!
;;
;; (binomial-coefficient 4 2) => 24 / 2 * 2 => 24 / 4 => 6
;;
(defn binomial-coefficient [a b]
(/ (factorial a)
(* (factorial b) (factorial (- a b)))))
;; (row 4) => (1 3 3 1)
;;
(defn row [n]
(map (fn [i] binomial-coefficient (dec n) i) (range n)))
;; (row 3) => (1 2 1)
;; Infinite Sequence!
;;
;; This constant function is an unrealized sequence
;; of pascals triangle numbers. The calculation to
;; realize the numbers only takes place on execution.
;;
;; (take 4 triangle) => (1) (1 1) (1 2 1) (1 3 3 1)
;;
(def triangle
(map #(row (inc %)) (range)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment