Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using transducers.. needs clojure 1.7.0
(ns solutions-4clojure.solution-53
(:import (java.util ArrayDeque)))
(defn subseq-by [f]
(fn [rf]
(let [deq (ArrayDeque.)]
(fn
([] (rf))
([result]
(let [result (if (or (.isEmpty deq) (< (.size deq) 2))
result
(let [v (vec deq)]
(.clear deq)
(rf result v)))]
(rf result)))
([result input]
(cond
(or (.isEmpty deq) (= input (f (.getLast deq)))) (do (.add deq input) result)
(> (.size deq) 1) (let [v (vec deq)]
(.clear deq)
(.add deq input)
(rf result v))
:else (do (.clear deq) (.add deq input) result)))))))
(def filter-by-max-count
(fn [rf]
(let [maxv (volatile! 0)]
(fn
([] (rf))
([result]
(rf result))
([result input]
(let [max @maxv
size (count input)]
(cond
(> size max) (do (vreset! maxv size)
(rf (rf) input))
;(= size max) (rf result input)
:else result)))))))
(defn solve-53 [seq]
(let [tx (comp (subseq-by inc) filter-by-max-count)]
(flatten (transduce tx conj seq))))
(defn solve-53-by [seq f]
(let [tx (comp (subseq-by f) filter-by-max-count)]
(flatten (transduce tx conj seq))))
(println (= (solve-53 [1 0 1 2 3 0 4 5]) [0 1 2 3])
(= (solve-53 [5 6 1 3 2 7]) [5 6])
(= (solve-53 [2 3 3 4 5]) [3 4 5])
(= (solve-53 [7 6 5 4]) []))
(println (= (solve-53-by [1 0 1 2 3 0 1 2 4 8 5] (partial * 2)) [1 2 4 8]))
(println (= (solve-53-by [1 0 1 2 3 2 1 5] dec) [3 2 1]))
(println (= (solve-53-by [ 0 1 2 3 1 5] dec) []))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment