September 23, 2018
Just Juxt #40: Intervals (4clojure #171)
Write a function that takes a sequence of integers and returns a sequence of "intervals". Each interval is a a vector of two integers, start and end, such that all integers between start and end (inclusive) are contained in the input sequence.
(ns live.test
(:require [cljs.test :refer-macros [deftest is run-tests]]))
(defn intervals [c]
(let [s (set c)]
(map (juxt first last)
(take-nth 2 (partition-by #(contains? s %)
(and (seq s)
(range (apply min s) (inc (apply max s)))))))))
(deftest intervals-test
(is (= (intervals [1 2 3]) [[1 3]]))
(is (= (intervals [10 9 8 1 2 3]) [[1 3] [8 10]]))
(is (= (intervals [1 1 1 1 1 1 1]) [[1 1]]))
(is (= (intervals []) []))
(is (= (intervals [19 4 17 1 3 10 2 13 13 2 16 4 2 15 13 9 6 14 2 11])
[[1 4] [6 6] [9 11] [13 17] [19 19]])))
(run-tests)