Skip to main content

Day 1: Dusty Shed

Advent of Code is back, baby!

Oh no, on the North Pole the weather is bad and the planes are not flying. If only there was somebody that could help…


Some quick notes before we start:


We’ve got an easy one for the start. We have a list of IDs that looks like this:

(def example "57
57
55
57
76
78
57
45
43
78
43
76
43
78
57
45
57
76
43
43
76")

Input parsing

The input consists only of integers, there’s no need to do anything fancy with it, so we’ll just use aoc/integers function.

(defn parse-data [input]
  (aoc/integers input))
(def example-data (parse-data example))
(def data (parse-data (aoc/read-input 1)))
example-data
[57 57 55 57 76 78 57 45 43 78 43 76 43 78 57 45 57 76 43 43 76]

Solution

We need to find three most (Part 1) and least (Part 2) frequent IDs. The logic is the same for both parts, so we’ll write it only once.

There is, aptly named, frequencies function, which gives us a map from an ID to its frequency. Once we sort that map by its values, we’re 80% done.

(defn sort-by-freq [data]
  (->> data
       frequencies
       (sort-by val)))
(sort-by-freq example-data)
([55 1] [45 2] [78 3] [76 4] [43 5] [57 6])

This is exactly what we need. For Part 1 we need to take-last three elements, and for Part 2 we take first three.

(defn id-mult [freqs take-fn]
  (->> freqs
       (take-fn 3)
       (aoc/prod-map first))) ; [1]

The aoc/prod-map function is a helper function that does the same that (reduce * (map f ,,,)) would do, but since I have it in my arsenal, I might as well use it. Every element is a vector of [id freq], we need first to extract just the ID. [1]

(defn solve [data]
  (let [sorted-freqs (sort-by-freq data)]
    [(id-mult sorted-freqs take-last)
     (id-mult sorted-freqs take)]))
(solve example-data)
[186276 193050]
(solve data)
[165807936 302342992]

Woohoo! First stars are here!

Conclusion

This was a nice and easy task to get our feet wet. A simple input to parse, and Part 2 without any gotchas.

Today’s highlights:

  • frequencies: map of item counts
source: clojure/src/day01.clj