aboutsummaryrefslogtreecommitdiffstats
path: root/year2021/day3
diff options
context:
space:
mode:
authorClyne Sullivan <clyne@bitgloo.com>2022-11-30 19:55:31 -0500
committerClyne Sullivan <clyne@bitgloo.com>2022-11-30 19:55:31 -0500
commit8d43e37df99f280377bed90284d6ac2428334804 (patch)
tree3a5042c9af29da52b4bac38fd78b3ccde77a1dbc /year2021/day3
parent66ed0b9d27850dc653abc8baa75884f3de311bfa (diff)
move 2021 days to folder; update README
Diffstat (limited to 'year2021/day3')
-rw-r--r--year2021/day3/part1.clj25
-rw-r--r--year2021/day3/part2.clj36
2 files changed, 61 insertions, 0 deletions
diff --git a/year2021/day3/part1.clj b/year2021/day3/part1.clj
new file mode 100644
index 0000000..3fe888e
--- /dev/null
+++ b/year2021/day3/part1.clj
@@ -0,0 +1,25 @@
+(require '[clojure.string :as str])
+
+(->> "./in"
+ (slurp)
+ (str/split-lines)
+ (map (fn [l] (map #(if (= % \1) 1 0) l)))
+ (apply (partial map +))
+ (map #(if (< % 500) \1 \0))
+ (str/join)
+ (#(Integer/parseInt % 2))
+ (#(* % (bit-xor % (dec (int (Math/pow 2 12))))))
+ (println)
+ )
+
+; (->> input data file name
+; read in entire contents
+; split contents into array of lines
+; for each line, transform characters '1'/'0' to numbers
+; build sum array using the lines
+; convert back to array of characters
+; join characters into single string
+; convert binary string to a number (gamma)
+; multiply gamma by its bit-inverse (bit length hard-coded)
+; print results
+
diff --git a/year2021/day3/part2.clj b/year2021/day3/part2.clj
new file mode 100644
index 0000000..00e656f
--- /dev/null
+++ b/year2021/day3/part2.clj
@@ -0,0 +1,36 @@
+(require '[clojure.string :as str])
+
+(def bitcount 12)
+(def input
+ (->> "./in"
+ (slurp)
+ (str/split-lines)
+ (map #(Integer/parseInt % 2))
+ )
+ )
+
+(defn countbit [lst bit]
+ (->> lst
+ (map #(if (bit-test % bit) 1 0))
+ (apply +)
+ )
+ )
+
+(defn filterbit [lst bit v]
+ (if (= 1 (count lst))
+ lst
+ (filter #(= (bit-test % bit) v) lst)
+ )
+ )
+
+(loop [bit (dec bitcount) lst0 input lst1 input]
+ (if (and (= 1 (count lst0)) (= 1 (count lst1)))
+ (println (map * lst0 lst1))
+ (recur
+ (dec bit)
+ (filterbit lst0 bit (>= (countbit lst0 bit) (/ (count lst0) 2)))
+ (filterbit lst1 bit (< (countbit lst1 bit) (/ (count lst1) 2)))
+ )
+ )
+ )
+