Here is my solution to Advent of Code, Day 1:
(def input (slurp "day1.txt"))
(def elf-totals
(->> (clojure.string/split input #"\n\n")
(map (fn [elf-row] (clojure.string/split elf-row #"\n")))
(map (fn [elf-row]
(map (fn [calorie-value] (Integer/parseInt calorie-value)) elf-row)))
(into [])
(map (fn [elf-row] (reduce + elf-row)))
(sort (fn [x y] (> x y)))
(take 3)))
(def answer
(list (reduce + elf-totals) (first elf-totals)))
It is an overuse of maps and reduces, but let’s go through it step-by-step.
I start by slurping in the input day1.txt
, which is a collection of newline delimited numbers representing multiple elves.
Then, I push that input through a series of transforms with the thread-last macro ->>
.
Splitting the input by a double newline gives me each elf in it’s own sequence. The elves are delimited by blank lines (an additional newline character). Then I split each row by the newline character to give me every number in a row.
Next, I run Java’s Integer/parseInt
to get the numerical values of each number in an elf row, then I coerce those values into
a vector using into
.
After, I reduce the elf rows by summing each one, sort the rows in descending order, and take 3 elements from the front of the sequence. My answer is then the first of the top 3 elf totals, and the sum of the top 3 elf totals.
Looking forward to the rest of the puzzles!