Created
October 2, 2019 13:55
-
-
Save maruks/a84acde8f17581b73097bd10241bbc72 to your computer and use it in GitHub Desktop.
cloudy day
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 queue [] | |
(java.util.PriorityQueue.)) | |
(defn peek [pqueue] | |
(.peek pqueue)) | |
(defn poll [pqueue] | |
(.poll pqueue) | |
pqueue) | |
(defn size [pqueue] | |
(.size pqueue)) | |
(defn add [pqueue elem] | |
(.add pqueue elem) | |
pqueue) | |
(defn dedupe-towns [location population xs] | |
(lazy-seq | |
(when location | |
(if-let [[l p] (first xs)] | |
(if (= location l) | |
(dedupe-towns location (+ population p) (rest xs)) | |
(cons [location population] (dedupe-towns l p (rest xs)))) | |
(cons [location population] (dedupe-towns nil nil nil)))))) | |
(defn dedupe [xs] | |
(let [[[l p] & r] xs] | |
(dedupe-towns l p r))) | |
(defn find-max [clouds towns max-so-far current-max sunny queue location] | |
(if-let [[town population] (first towns)] | |
(let [[cloud extent] (first clouds) | |
[next-town _] (first towns) | |
cloud-end (peek queue) | |
cloud-start (when (and cloud extent) | |
(- cloud extent))] | |
(cond (and cloud-end (< cloud-end location)) (recur clouds towns (max max-so-far current-max) 0 sunny (poll queue) location) | |
(and cloud-start (= location cloud-start)) (recur (rest clouds) towns (max max-so-far current-max) 0 sunny (add queue (+ cloud extent)) location) | |
(= location town) (let [number-of-clouds (size queue) | |
next-curr-max (if (= 1 number-of-clouds) (+ current-max population) 0) | |
next-sunny (if (zero? number-of-clouds) (+ sunny population) sunny)] | |
(recur clouds (rest towns) max-so-far next-curr-max next-sunny queue location)) | |
:else (let [next-location (min town (or cloud-start Long/MAX_VALUE))] | |
(recur clouds towns max-so-far current-max sunny queue next-location)))) | |
[(max max-so-far current-max) sunny])) | |
; (maximumPeople [10 100] [5 100] [4] [1]) | |
; (maximumPeople [9 9 1 5 8] [1 7 7 11 7] [2 3] [4 11]) | |
(defn maximumPeople [p x y r] | |
(let [clouds (sort-by (fn [[a b]] (- a b)) (map vector y r)) | |
towns (dedupe (sort-by first (map vector x p))) | |
[max-ppl sunny] (find-max clouds towns 0 0 0 (queue) 0)] | |
(+ max-ppl sunny))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment