2023 day 13 in Clojure

$ time clj -M -m day13 input
2.87s user 0.12s system 345% cpu 0.866 total

$ time bb --init day13.clj -e '(day13/-main "input")
0.15s user 0.04s system 366% cpu 0.052 total
This commit is contained in:
aru 2023-12-13 15:01:17 +01:00
parent 981dcba505
commit d8a19b1fc6
3 changed files with 76 additions and 0 deletions

56
2023/13/day13.clj Normal file
View File

@ -0,0 +1,56 @@
(ns day13
(:require [clojure.string :as s]
[clojure.edn :as edn]))
(defn parse-input [input]
(->> (s/split input #"\n\n")
(map s/split-lines)))
(defn different-field-count [c1 c2]
(->> (map = c1 c2)
(filter not)
count))
(defn different-field-counts [c1 c2]
(reduce + 0 (map different-field-count c1 c2)))
(defn is-mirrored? [smudge-count l r]
(let [ll (count l)
lr (count r)
size (min ll lr)
l (take size (drop (abs (- size ll)) l))
r (reverse (take size r))
diff (different-field-counts l r)]
(= diff smudge-count)))
(defn transpose [coll]
(for [i (range 0 (count (first coll)))]
(apply str (map #(nth %1 i) coll))))
(defn reflection-line-at [smudge-count pattern]
(->> (range 1 (count pattern))
(filter (fn [i] (apply (partial is-mirrored? smudge-count) (split-at i pattern))))
first))
(defn reflection-line [smudge-count pattern]
(let [with-smudge-count (partial reflection-line-at smudge-count)
v (with-smudge-count pattern)]
(if (nil? v)
(with-smudge-count (transpose pattern))
(* 100 v))))
(defn solution [smudge-count input]
(reduce + 0 (pmap #(reflection-line smudge-count %1) input)))
(defn part1 [input] (solution 0 input))
(defn part2 [input] (solution 1 input))
;; Invoke with clj -M -m day13 input
;; Or with bb --init day13.clj -e '(day13/-main "input")'
(defn -main [file & args]
(let [input (parse-input (slurp file))
[p1 p2] (map #(%1 input) [part1 part2])]
(do
(println (str "Part 1: " p1))
(println (str "Part 2: " p2))
(shutdown-agents))))

5
2023/13/deps.edn Normal file
View File

@ -0,0 +1,5 @@
{:paths ["."]
:aliases
{:nREPL {:extra-deps
{nrepl/nrepl {:mvn/version "1.0.0"}}}}}

15
2023/13/example Normal file
View File

@ -0,0 +1,15 @@
#.##..##.
..#.##.#.
##......#
##......#
..#.##.#.
..##..##.
#.#.##.#.
#...##..#
#....#..#
..##..###
#####.##.
#####.##.
..##..###
#....#..#