This commit is contained in:
Aleh Suprunovich 2024-12-11 08:38:41 +03:00
parent f0b98f04ca
commit 4a3a494bac

88
src/day4.clj Normal file
View File

@ -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")