Skip to content

Instantly share code, notes, and snippets.

@vitalipe
Created November 13, 2019 18:17
Show Gist options
  • Select an option

  • Save vitalipe/30cc634f0872836c035ece48ced92eec to your computer and use it in GitHub Desktop.

Select an option

Save vitalipe/30cc634f0872836c035ece48ced92eec to your computer and use it in GitHub Desktop.
(ns adventofcode.playground.d4
(:require [clojure.string :as s]))
(defn line->date+event [line]
(let [[_ date-string event-string] (s/split line #"\[(.*?)\]")]
{:date (.getTime (doto (new js/Date date-string)
(.setSeconds 0)
(.setMilliseconds 0)))
:event (case (s/trim event-string)
"wakes up" :wakeup
"falls asleep" :sleep
;; otherwise just blindly assume its a new shift :D
(re-find #"\d+" event-string))}))
(defn str->shifts-log [text]
(let [shift-change? (fn [{e :event}] (contains? #{:sleep :wakeup} e))]
(->> (s/split-lines text)
(map s/trim)
(remove empty?)
(map line->date+event)
(sort-by :date)
(partition-by shift-change?)
(partition 2)
(map flatten))))
(defn shifts-log->guards-log [log]
(-> (fn [guards-log [{guard :event} & shift]]
(update guards-log guard concat shift))
(reduce {} log)))
(defn solve [input]
(let [guards-log (->> input
(str->shifts-log)
(shifts-log->guards-log))
[guard sleepy-ms] (->> guards-log
(map
(fn [[id shift]]
[id (->> shift
(map :date)
(partition 2)
(map reverse)
(map (partial apply -))
(reduce +))]))
(sort-by second)
(last))
[m _] (->> (guards-log guard)
(map :date)
(partition 2)
(mapcat (fn [[a b]]
(let [start (.getMinutes (new js/Date a))
end (+ start (/ (- b a) (* 1000 60)))]
(range start end))))
(frequencies)
(sort-by second)
(last))]
(* guard m)))
(comment
(println
(solve
"
[1518-11-01 00:00] Guard #10 begins shift
[1518-11-01 00:05] falls asleep
[1518-11-01 00:25] wakes up
[1518-11-01 00:30] falls asleep
[1518-11-01 00:55] wakes up
[1518-11-01 23:58] Guard #99 begins shift
[1518-11-02 00:40] falls asleep
[1518-11-02 00:50] wakes up
[1518-11-03 00:05] Guard #10 begins shift
[1518-11-03 00:24] falls asleep
[1518-11-03 00:29] wakes up
[1518-11-04 00:02] Guard #99 begins shift
[1518-11-04 00:36] falls asleep
[1518-11-04 00:46] wakes up
[1518-11-05 00:03] Guard #99 begins shift
[1518-11-05 00:45] falls asleep
[1518-11-05 00:55] wakes up")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment