Last active
December 28, 2015 15:39
-
-
Save hadronzoo/7522948 to your computer and use it in GitHub Desktop.
Find gaps in a collection containing a sequence of monotonic integers
This file contains hidden or 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
(defn gaps [coll] | |
"Find gaps in collection coll, containing a sequence of monotonic integers" | |
(letfn [(intervals [[cur & rst] prev] | |
(when cur | |
(cons [(inc prev) (dec cur)] | |
(lazy-seq (intervals rst cur)))))] | |
(lazy-seq | |
(when-let [[cur & rst] (seq coll)] | |
(remove (fn [[x y]] (> x y)) | |
(intervals rst cur)))))) | |
(defn gaps< [ch] | |
(let [result (chan)] | |
"Takes a source channel containing a sequence of monotonic integers, and | |
returns a channel which contains gap intervals." | |
(go-loop [prev (<! ch)] | |
(if-let [cur (<! ch)] | |
(let [x (inc prev) | |
y (dec cur)] | |
(when (<= x y) | |
(>! result [x y])) | |
(recur cur)) | |
(close! result))) | |
result)) | |
(gaps [1 3 50]) | |
;; => ([2 2] [4 49]) | |
(def xs (concat (range 5) (range 8 11) (range 15 20))) | |
;; => (0 1 2 3 4 8 9 10 15 16 17 18 19) | |
(gaps xs) | |
;; => ([5 7] [11 14]) | |
(def g (gaps< (to-chan (concat (range 5) (range 8 11) (range 15 20))))) | |
(<!! g) | |
;; => [5 6] | |
(<!! g) | |
;; => [11 14] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment