Skip to content

Instantly share code, notes, and snippets.

# Realtin/pascal-triangle.clj Last active Feb 10, 2016

 ;; take a vector v and index i ;; index n + index n-1 (defn add [v i] (+ ;; 0 is default when return value is nil (get v i 0) (get v (- i 1) 0))) ; calculates the next row of a given row (defn new-row [v] ; cnt is the number of times the loop runs with initial value 0 ; nv is 'new vector' with initial value [] (loop [cnt 0 nv []] ; run as long as cnt is less or equal the lenght/size of the vector (if (<= cnt (count v)) ; each run do: ; increase cnt by 1 ; use add function with vector and cnt & add it into nv ('new vector') (recur (inc cnt) (conj nv (add v cnt))) ; else retun new vector nv))) ; the actual function that puts everything together ; takes a number that represents the row in the pascal triangle (defn the-function [number] ; we need only the last vector in our vector of results... (last ; cnt is the number of times the loop runs with initial value 1 ; nv is 'new vector' with initial value [[1]] because first row is always [1] (loop [cnt 1 nv [[1]]] ; run as long as cnt is less the provided number 'number' (if (< cnt number) ; each run do: ; increase cnt by 1 ; use new-row function with the last vector in 'new-vector' & add it into nv ('new vector') (recur (inc cnt) (conj nv (new-row (last nv)))) ; else return 'new vector' nv nv)))) ; same function as above just with cool macro (-->) usage! (defn the-function-cool [number] (last (loop [cnt 1 nv [[1]]] (if (< cnt number ) (recur (inc cnt) (->> nv last new-row (conj nv))) nv)))) ;; 4clojure #97 (= (the-function-cool 1) [1]) (= (map the-function-cool (range 1 6)) [ [1] [1 1] [1 2 1] [1 3 3 1] [1 4 6 4 1]]) (= (the-function-cool 11) [1 10 45 120 210 252 210 120 45 10 1]) ;; last until intager overflow (the-function-cool 66)
to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.