/
13.clj
36 lines (30 loc) · 1.04 KB
/
13.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
(ns aoc.2022.13
(:require
[clojure.test :refer [deftest is]]))
(defn parse [s]
(read-string (str "[" s "]")))
(defn cmp [l r]
(cond
(and (int? l) (int? r)) (compare l r)
(int? l) (recur (vector l) r)
(int? r) (recur l (vector r))
:else (if (or (empty? l) (empty? r))
(compare l r)
(let [c (cmp (first l) (first r))]
(if (zero? c)
(recur (subvec l 1) (subvec r 1))
c)))))
(defn part-1 [packets]
(->> (partition 2 packets)
(keep-indexed (fn [i [l r]] (when (neg? (cmp l r)) (inc i))))
(apply +)))
(defn part-2 [packets]
(let [sorted (sort cmp (conj packets [[2]] [[6]]))]
(* (inc (.indexOf sorted [[2]])) (inc (.indexOf sorted [[6]])))))
(def example
"[1,1,3,1,1] [1,1,5,1,1] [[1],[2,3,4]] [[1],4] [9] [[8,7,6]] [[4,4],4,4]
[[4,4],4,4,4] [7,7,7,7] [7,7,7] [] [3] [[[]]] [[]]
[1,[2,[3,[4,[5,6,7]]]],8,9] [1,[2,[3,[4,[5,6,0]]]],8,9]")
(deftest test-example
(is (= 13 (part-1 (parse example))))
(is (= 140 (part-2 (parse example)))))