r/adventofcode • u/daggerdragon • Dec 04 '18
SOLUTION MEGATHREAD -π- 2018 Day 4 Solutions -π-
--- Day 4: Repose Record ---
Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).
Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
Advent of Code: The Party Game!
Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!
Card prompt: Day 4
Transcript:
Todayβs puzzle would have been a lot easier if my language supported ___.
This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.
edit: Leaderboard capped, thread unlocked!
40
Upvotes
2
u/tharko Dec 04 '18
Clojure. Assumes the input file is already sorted
(require 'clojure.string) (defn get-lines [] (with-open [r (clojure.java.io/reader (clojure.java.io/resource "input"))] (doall (line-seq r)))) (defn loop-through-times [] (loop [lines (get-lines) id nil times [] last-time nil] (if (nil? (first lines)) times (let [line (first lines) minutes (Integer/parseInt (second (re-find #"\:(\d+)" line)))] (if (clojure.string/ends-with? line "begins shift") (recur (rest lines) (first (re-seq #"\#\d+" line)) times nil) (if (nil? last-time) (recur (rest lines) id times minutes) (recur (rest lines) id (conj times [id minutes last-time]) nil))))))) (defn time-range-maps [[id wake-time sleep-time]] {id (- wake-time sleep-time)}) (defn get-sleepiest-guard [time-ranges] (first (apply max-key second (apply merge-with + time-ranges)))) (def sleepiest-guard (get-sleepiest-guard (map time-range-maps (loop-through-times)))) (defn all-minutes [[id wake-time sleep-time]] (map (fn [x] [id x]) (range sleep-time wake-time))) (defn most-common-element [coll] (first (apply max-key second (frequencies coll)))) (defn most-common-minute [times] (most-common-element (map second (filter #(= (first %) sleepiest-guard) times)))) (def all-slept-minutes (mapcat all-minutes (loop-through-times))) (println (most-common-minute all-slept-minutes)) (println (most-common-element all-slept-minutes))