From d07a16bbf95678c6134244b2b68ac0c1f18a79d3 Mon Sep 17 00:00:00 2001 From: Luke Hubmayer-Werner Date: Sat, 3 Dec 2022 20:56:27 +1030 Subject: [PATCH] 2022 Day 3 Clojure --- 2022/day3.clj | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 2022/day3.clj diff --git a/2022/day3.clj b/2022/day3.clj new file mode 100644 index 0000000..d50f090 --- /dev/null +++ b/2022/day3.clj @@ -0,0 +1,38 @@ +(require '[clojure.string :as str]) +(require '[clojure.set]) +(require '[clojure.zip :as zip]) + +(def elves (str/split-lines (slurp "input/3"))) +(defn priority [char] + (let [ + c (int char) + a (int \a) + z (int \z) + A (int \A) + ] + (if (<= a c z) + (+ (- c a) 1) + (+ (- c A) 27)))) + +; Part 1 +(defn two-knapsacks [line] ( + let [ + half (/ (count line) 2) + [knapsack-1 knapsack-2] (map set (split-at half line)) + ] + (priority (first (clojure.set/intersection knapsack-1 knapsack-2) +)))) +(println (reduce + (map two-knapsacks elves))) + +; Part 2 +(defn chunker [sequence num] + (if (<= (count sequence) num) + [sequence] + (let [[head tail] (split-at num sequence)] (lazy-seq (cons head (chunker tail num)))))) +(defn three-elves [lines] ( + let [ + sets (map set lines) + common (apply clojure.set/intersection sets) + ] + (priority (first common)))) +(println (reduce + (map three-elves (chunker elves 3)))) \ No newline at end of file