]> code.bitgloo.com Git - clyne/advent-of-code.git/commitdiff
add day 8
authorClyne Sullivan <clyne@bitgloo.com>
Wed, 8 Dec 2021 14:55:12 +0000 (09:55 -0500)
committerClyne Sullivan <clyne@bitgloo.com>
Wed, 8 Dec 2021 14:55:12 +0000 (09:55 -0500)
day8/part1.clj [new file with mode: 0644]
day8/part2.clj [new file with mode: 0644]

diff --git a/day8/part1.clj b/day8/part1.clj
new file mode 100644 (file)
index 0000000..6c8cd0f
--- /dev/null
@@ -0,0 +1,28 @@
+(require '[clojure.string :as str])
+
+(loop [sum 0]
+  (let [line (read-line)]
+    (if (empty? line)
+      (println sum)
+      (recur
+        (+
+         sum
+         (reduce
+           #(let [c (count %2)]
+              (if (or (= 2 c) (= 3 c) (= 4 c) (= 7 c))
+                (inc %1)
+                %1
+                )
+             )
+           0
+           (subvec
+             (mapv (comp str/join sort) (str/split line #" "))
+             11 15
+             )
+           )
+         )
+        )
+      )
+    )
+  )
+
diff --git a/day8/part2.clj b/day8/part2.clj
new file mode 100644 (file)
index 0000000..7fbaf92
--- /dev/null
@@ -0,0 +1,65 @@
+(require '[clojure.string :as str])
+(require '[clojure.set :as set])
+
+(defn find-match
+  "
+  Searches for digit that `has segs-left` segments remaining
+  after the segments of `dig-to-cmp` are removed from the
+  digits in `cnts` with `grp-to-cmp` segments.
+  "
+  [segs-left dig-to-cmp cnts grp-to-cmp]
+  (second
+    (first
+      (filter
+        #(-> (second %)
+             (str/replace (re-pattern (str/join ["[" dig-to-cmp "]"])) "")
+             (count)
+             (= segs-left)
+             )
+        (filterv #(= (first %) grp-to-cmp) cnts)
+        )
+      )
+    )
+  )
+
+(defn determine-digits [line]
+  (let [counts (mapv #(do [(count %) %]) (take 10 line))
+        mcounts (into {} counts)]
+    (as-> {} $
+        (assoc $ 1 (mcounts 2)
+                 4 (mcounts 4)
+                 7 (mcounts 3)
+                 8 (mcounts 7)
+                 )
+        (assoc $ 3 (find-match 2 ($ 7) counts 5))
+        (assoc $ 2 (find-match 3 ($ 4) counts 5))
+        (assoc $ 5 (find-match 2 ($ 2) counts 5))
+        (assoc $ 0 (find-match 2 ($ 5) counts 6))
+        (assoc $ 9 (find-match 2 ($ 4) counts 6))
+        (assoc $ 6 (find-match 4 ($ 7) counts 6))
+        )
+    )
+  )
+
+(loop [sum 0]
+  (let [rl (read-line)]
+    (if (empty? rl)
+      (println sum)
+      (let [line (as-> rl $
+                   (str/split $ #" ")
+                   (mapv (comp str/join sort) $)
+                   )
+            number (subvec line 11 15)
+            decoder (set/map-invert (determine-digits line))]
+        (recur (->> number
+                    (map (comp str decoder))
+                    (str/join)
+                    (#(Integer/parseInt %))
+                    (+ sum)
+                    )
+               )
+        )
+      )
+    )
+  )
+