From e0509be163f774eddc3b394cd02b9e21d5735cb1 Mon Sep 17 00:00:00 2001 From: Aleh Suprunovich Date: Wed, 4 Dec 2024 14:13:10 +0300 Subject: [PATCH] day 4 --- src/day4.clj | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 src/day4.clj diff --git a/src/day4.clj b/src/day4.clj new file mode 100644 index 0000000..d61b627 --- /dev/null +++ b/src/day4.clj @@ -0,0 +1,88 @@ +(ns day4 + (:require [clojure.string :as string] + [helpers :refer [get-input]])) + +(def input-example +"MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX") + +;(def input (string/split-lines input-example)) +(def input (string/split-lines (get-input 4))) +(def line-len (count input)) +(def column-len (count (first input))) + +(defn get-string [coords] + (->> + coords + (map #(get-in input %)) + (apply str))) + +(defn diag [[x0 y0]] + (loop [x x0 y y0 d []] + (if (or (< x 0) (< y 0) (> x column-len ) (> y line-len)) + d (recur (dec x) (inc y) (conj d [x y]))))) + +(defn flip [d] + (mapv (fn [[x y]] [(dec (- line-len x)) y]) d)) + +(def diagonals + (let [diagonals + (->> + (concat + (map #(vector % 0) (range line-len)) + (map #(vector (dec line-len) %) (range 1 column-len))) + (map diag))] + (->> + (concat diagonals (map flip diagonals)) + (map get-string)))) + +(defn check-line [l] + (re-seq #"XMAS" l)) + +(def result + (let [lines input + columns (->> (map seq lines) + (apply interleave) + (partition column-len) + (map (partial apply str))) + rev-fn (fn [i] (map #(apply str (reverse %)) i))] + (->> + (concat + lines (rev-fn lines) + columns (rev-fn columns) + diagonals (rev-fn diagonals)) + (map check-line) + (apply concat)))) + +(println "XMAS appears" (count result) "times.") + +(defn x-mas? [[x y]] + (let [w1 (get-string [[(dec x) (dec y)] [x y] [(inc x) (inc y)]]) + w2 (get-string [[(dec x) (inc y)] [x y] [(inc x) (dec y)]])] + (and (or (= w1 "MAS") (= w1 "SAM")) + (or (= w2 "MAS") (= w2 "SAM"))))) + +(def result2 + (let [m (mapv vec input)] + (->> + (map-indexed + (fn [x l] + (map-indexed + (fn [y c] + (when (= \A c) [x y])) + l)) + m) + (apply concat) + (remove nil?) + (map x-mas?) + (filter true?)))) + +(println "X-MAS appears" (count result2) "times")