]> code.bitgloo.com Git - clyne/advent-of-code.git/commitdiff
add day3
authorClyne Sullivan <clyne@bitgloo.com>
Fri, 3 Dec 2021 14:20:32 +0000 (09:20 -0500)
committerClyne Sullivan <clyne@bitgloo.com>
Fri, 3 Dec 2021 14:20:32 +0000 (09:20 -0500)
day3/part1.clj [new file with mode: 0644]
day3/part2.clj [new file with mode: 0644]

diff --git a/day3/part1.clj b/day3/part1.clj
new file mode 100644 (file)
index 0000000..3c09ff8
--- /dev/null
@@ -0,0 +1,33 @@
+(def counts
+  (loop [line (read-line)
+         tot (repeat (count line) 0)
+         ]
+    (if (empty? line)
+      tot
+      (recur
+        (read-line)
+        (map + tot (map #(if (= % \1) 1 0) line))
+        )
+      )
+    )
+  )
+
+(println counts)
+
+(loop [cnts counts gamma 0 epsilon 0]
+  (if (empty? cnts)
+    (println (* gamma epsilon))
+    (recur
+      (rest cnts)
+      (if (> (first cnts) 500)
+        (inc (* 2 gamma))
+        (* 2 gamma)
+        )
+      (if (< (first cnts) 500)
+        (inc (* 2 epsilon))
+        (* 2 epsilon)
+        )
+      )
+    )
+  )
+
diff --git a/day3/part2.clj b/day3/part2.clj
new file mode 100644 (file)
index 0000000..cbbe35f
--- /dev/null
@@ -0,0 +1,47 @@
+(def bitcount 12)
+(def input
+  (loop [tot []]
+    (let [line (read-line)]
+      (if (empty? line)
+        tot
+        (recur (conj tot (Integer/parseInt line 2)))
+        )
+      )
+    )
+  )
+
+(defn countbit [lst bit]
+  (->> lst
+       (map #(if (bit-test % bit) 1 0))
+       (apply +)
+       )
+  )
+(defn filterbit [lst bit v]
+  (if (= 1 (count lst))
+    lst
+    (loop [l lst r []]
+      (if (empty? l)
+        r
+        (recur
+          (rest l)
+          (if (= (bit-test (first l) bit) v)
+            (conj r (first l))
+            r
+            )
+          )
+        )
+      )
+    )
+  )
+
+(loop [bit (dec bitcount) lst0 input lst1 input]
+  (if (and (= 1 (count lst0)) (= 1 (count lst1)))
+    (println (* (first lst0) (first lst1)))
+    (recur
+      (dec bit)
+      (filterbit lst0 bit (>= (countbit lst0 bit) (/ (count lst0) 2)))
+      (filterbit lst1 bit (< (countbit lst1 bit) (/ (count lst1) 2)))
+      )
+    )
+  )
+