Advent of Code 2022 - Day 04
Day 04
This challenge didn’t involve a whole lot of programming just some clever math. To solve it we first parse the input so each row is a vector of four numbers. We then filter this structure by the needs of the challenge
1(defn number-list
2 [s]
3 (map
4 (comp (partial map parse-long) #(string/split % #"[-,]"))
5 (string/split s #"\n *")))
First split the rows and then split numbers which are divided by - or ,. I also included a step of converting the strings
to numbers for easier use later.
Part 1
For one range to be contained in another it start must be greater and its end must be less. We need to cover cases when the first is contained in second, and when the second is contained in the first
1; a b c d
2; 2 6 3 4
3; a(2) <= c(3) <= d(4) <= b(6)
4(defn fully-contains?
5 [[a b c d]]
6 (or
7 (<= a c d b)
8 (<= c a b d)))
For the solution we filter with this function and count the elements.
1(defn part1
2 [s]
3 (->> (number-list s)
4 (filter fully-contains?)
5 (count)))
Part 2
For the second part we need to find if they overlap. For this I first thought up how to check if they don’t overlap and just took the complement
of that function to see if they do overlap.
1(defn no-overlap?
2 [[a b c d]]
3 (or
4 (< b c)
5 (< d a)))
6
7(defn part2
8 [s]
9 (->> (number-list s)
10 (filter (complement no-overlap?))
11 (count)))