Skip to content

Instantly share code, notes, and snippets.

@escherize
Created July 15, 2019 19:44
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 escherize/263090f2ff33eefa6b6e852cc99bbe6f to your computer and use it in GitHub Desktop.
Save escherize/263090f2ff33eefa6b6e852cc99bbe6f to your computer and use it in GitHub Desktop.
(ns super-sratch.minstack)
(defprotocol Stack (push [this x]) (peek [this]) (pop [this]))
(defprotocol FindMin (find-min [this]))
(defprotocol FindMax (find-max [this]))
(defrecord fmm-stack [stack minstack maxstack]
Stack
(push [this x]
(merge this {:stack (vec (conj stack x))}
(when (<= x (or (last minstack) Integer/MAX_VALUE))
{:minstack (vec (conj minstack x))})
(when (>= x (or (last maxstack) Integer/MIN_VALUE))
{:maxstack (vec (conj maxstack x))})))
(peek [this] (last stack))
(pop [this]
(let [[new popped] ((juxt drop-last last) stack)
new (vec new)]
(merge this {:stack new}
(when (= popped (last minstack))
{:minstack (vec (drop-last minstack))})
(when (= popped (last maxstack))
{:maxstack (vec (drop-last maxstack))}))))
FindMin
(find-min [this] (last minstack))
FindMax
(find-max [this] (last maxstack)))
(defn find-stack
([& ns]
(let [fs (atom (->fmm-stack [] [] []))]
(doseq [n ns]
(swap! fs push n))
@fs)))
(find-min (pop (find-stack 1 2 10 -5)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment