Skip to content

Instantly share code, notes, and snippets.

@kanwei
Last active December 12, 2015 02:08
Show Gist options
  • Save kanwei/4696105 to your computer and use it in GitHub Desktop.
Save kanwei/4696105 to your computer and use it in GitHub Desktop.
HackerRank Median Clojure (passes)
(ns solution (:gen-class))
(set! *warn-on-reflection* true)
(defn median [^java.util.PriorityQueue max-heap ^java.util.PriorityQueue min-heap]
(let [max-size (.size max-heap)
min-size (.size min-heap)]
(cond
(and (zero? max-size)
(zero? min-size)) "Wrong!"
(= max-size min-size) (/ (+ (.peek min-heap) (.peek max-heap)) 2)
:else (.peek max-heap))))
(defn balance-heap [^java.util.PriorityQueue max-heap ^java.util.PriorityQueue min-heap]
; (println "balance: " max-heap min-heap)
(let [max-size (.size max-heap)
min-size (.size min-heap)]
(cond
(zero? max-size) nil
(> max-size (inc min-size)) (.add min-heap (.poll max-heap))
(< max-size min-size) (.add max-heap (.poll min-heap))
(and (pos? min-size)
(> max-size min-size)
(> (.peek max-heap) (.peek min-heap)))
(let [max-root (.poll max-heap)
min-root (.poll min-heap)]
(.add min-heap max-root)
(.add max-heap min-root)))))
(defn ^String format-answer [x]
(if (instance? clojure.lang.Ratio x)
(format "%.1f" (double x))
(str x)))
(defn solve [src dest]
(let [in (clojure.java.io/reader src)
out (clojure.java.io/writer dest)
_ (.readLine in)
min-heap (java.util.PriorityQueue. 1000)
max-heap (java.util.PriorityQueue. 1000 (java.util.Collections/reverseOrder))]
(try
(loop [seen (hash-set)]
(let [op (.read in)
_ (.read in)
n (Integer/parseInt (.readLine in))]
(case op
114 (if (and (contains? seen n)
(if (<= n (.peek max-heap))
(.remove max-heap n)
(.remove min-heap n)))
(do
(balance-heap max-heap min-heap)
(.write out (format-answer (median max-heap min-heap)))
(.newLine out)
(recur seen))
(do
(.write out "Wrong!\n")
(recur seen)))
97 (do
(.add max-heap n)
(balance-heap max-heap min-heap)
(.write out (format-answer (median max-heap min-heap)))
(.newLine out)
(recur (conj seen n))))))
(catch Exception e)
(finally (.flush out)))))
(defn -main []
(solve *in* *out*))
;(time (solve "/Users/kanwei/Projects/istreet/median/input01.txt" (doto (java.io.File/createTempFile "medians" ".out") .deleteOnExit)))
;(time (solve "/Users/kanwei/Projects/istreet/median/worst.txt" (doto (java.io.File/createTempFile "medians" ".out") .deleteOnExit)))
;(time (solve "/Users/kanwei/Projects/istreet/median/input01.txt") *out*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment