Created
August 16, 2011 20:36
-
-
Save mamboking/1150106 to your computer and use it in GitHub Desktop.
Cyclic sorted list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;cyclic list insertion | |
(def start-node (atom [1 (fn [] start-node)])) | |
(defn insert-after [node val] | |
(let [new-node (atom [val (last @node)])] | |
(swap! node (fn [n] [(first n) (fn [] new-node)])))) | |
(defn find-insert-spot [node val] | |
(loop [cnode node | |
ctr 0] | |
(let [next-node ((last @cnode)) | |
cval (first @cnode) | |
nval (first @next-node)] | |
(if (= next-node node) | |
cnode | |
(if (or (<= cval val nval) | |
(and (> cval nval) (or (>= val cval) | |
(<= val nval)))) | |
cnode | |
(recur next-node (inc ctr))))))) | |
(defn insert-val [node val] | |
(insert-after (find-insert-spot node val) val)) | |
(defn get-nth-after [start cnt] | |
(loop [cnode start i cnt] | |
(if (= i 0) | |
cnode | |
(recur ((last @cnode)) (dec i))))) | |
(defn ring-vals [start] | |
(loop [cnode start | |
acc []] | |
(let [next-node ((last @cnode)) | |
cval (first @cnode)] | |
(if (= next-node start) | |
(conj acc cval) | |
(recur next-node (conj acc cval)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment