Advent of Code 2022 - Day 02

1 minute read

Day 02

To solve this problem I had to first find a score for the input (game of rock, paper, scissors), and then sum them up. I decided to encode each outcome in a map where the key is the game and the output is the number of points which that game awards.

 1(def ROCK       1)
 2(def PAPER      2)
 3(def SCISSORS   3)
 4
 5(def LOSE       0)
 6(def DRAW       3)
 7(def WIN        6)
 8
 9(def scores1 {
10              "A X" (+ ROCK DRAW)
11              "A Y" (+ PAPER WIN)
12              "A Z" (+ SCISSORS LOSE)
13
14              "B X" (+ ROCK LOSE)
15              "B Y" (+ PAPER DRAW)
16              "B Z" (+ SCISSORS WIN)
17
18              "C X" (+ ROCK WIN)
19              "C Y" (+ PAPER LOSE)
20              "C Z" (+ SCISSORS DRAW)
21              })

Part 1

Then the actual solving is pretty easy just split the input into lines and then map over it with scores1. In Clojure we can use a map as a function that accepts a key as and argument and returns the associated value. If you think about it maps and functions are the same, they both just map an input to an output.

1(defn part1
2  "Solves the first part"
3  [s]
4  (->> (map scores1 (to-lines s))
5       (apply +)))

Part 2

For the second part we just change the results map to reflect the changes in the task and do the same.

 1(def scores2 {
 2              "A X" (+ SCISSORS LOSE)
 3              "A Y" (+ ROCK DRAW)
 4              "A Z" (+ PAPER WIN)
 5
 6              "B X" (+ ROCK LOSE)
 7              "B Y" (+ PAPER DRAW)
 8              "B Z" (+ SCISSORS WIN)
 9
10              "C X" (+ PAPER LOSE)
11              "C Y" (+ SCISSORS DRAW)
12              "C Z" (+ ROCK WIN)
13              })
14
15(defn part2
16  [s]
17  (->> (map scores2 (to-lines s))
18       (apply +)))