Skip to content

Instantly share code, notes, and snippets.

@maruks
Created November 20, 2012 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maruks/4117537 to your computer and use it in GitHub Desktop.
Save maruks/4117537 to your computer and use it in GitHub Desktop.
Zeckendorf's_theorem in clojure
(ns sandbox.fibo-dojo)
(def fib (cons 1 (cons 2 (lazy-seq (map + (rest fib) fib)))))
(def indexes (iterate inc 0))
(defn cons-one? [xs prev]
(if (seq xs)
(if (and (= 1 prev) (= (first xs) prev)) true
(recur (rest xs) (first xs)))))
(defn encode [sum idxs acc target]
(cond (= sum target) (if (cons-one? acc 0) '() (list (vec acc)))
(or (> sum target) (> (nth fib (first idxs)) target)) '()
:else (concat (encode sum (rest idxs) (cons 0 acc) target)
(encode (+ sum (nth fib (first idxs))) (rest idxs) (cons 1 acc) target))))
(defn enc [num]
(encode 0 indexes '() num))
(defn print-table [n]
(let [xs (drop 1 (take n indexes))
res (map #(cons % (enc %)) xs)]
(doseq [r res] (println r) )))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment