AOC 2021 day2 problem

A great excuse to learn about reduce:

user> (let [input ["forward 5"
                   "down 5"
                   "forward 8"
                   "up 3"
                   "down 8"
                   "forward 2"]]
        (reduce (fn [eax s]
                  (let [[dir amount] (clojure.string/split s #"\s+")]
                    (condp = dir
                      "forward" (update eax :x + (Long. amount))
                      "down"    (update eax :y + (Long. amount))
                      "up"      (update eax :y - (Long. amount)))))
                {:x 0 :y 0}
                input))
{:x 15, :y 10}

Some questions stemming from the order of arguments passed to the update function, and the commutativity of subtraction - worth of some tests and further exploration.

1 Like