From 2c34d596504eabe01fd7002982588d797dfaa905 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Odd=20Andreas=20S=C3=B8rs=C3=A6ther?= Date: Fri, 3 Jan 2025 21:45:01 +0100 Subject: [PATCH] matrix utils --- notebooks/y2024/d25.clj | 6 +++--- src/advent_of_code_clj/matrix.clj | 19 +++++++++++++++++++ src/advent_of_code_clj/utils.clj | 19 +++++-------------- 3 files changed, 27 insertions(+), 17 deletions(-) create mode 100644 src/advent_of_code_clj/matrix.clj diff --git a/notebooks/y2024/d25.clj b/notebooks/y2024/d25.clj index 3026c5a..775c5f7 100644 --- a/notebooks/y2024/d25.clj +++ b/notebooks/y2024/d25.clj @@ -1,7 +1,7 @@ (ns y2024.d25 (:require [advent-of-code-clj.input :as input] - [advent-of-code-clj.utils :as utils])) + [advent-of-code-clj.matrix :as mx])) (def test-input "##### .#### @@ -54,11 +54,11 @@ (defn parse-key [input] (map (fn [line] (dec (count (filter #{\.} line)))) - (apply mapv vector (utils/text->matrix input)))) + (mx/transpose (mx/text->matrix input)))) (defn parse-lock [input] (map (fn [line] (dec (count (filter #{\#} line)))) - (apply mapv vector (utils/text->matrix input)))) + (mx/transpose (mx/text->matrix input)))) (defn parse [input] (let [lock-or-key (.split input "\n\n") diff --git a/src/advent_of_code_clj/matrix.clj b/src/advent_of_code_clj/matrix.clj new file mode 100644 index 0000000..d903706 --- /dev/null +++ b/src/advent_of_code_clj/matrix.clj @@ -0,0 +1,19 @@ +(ns advent-of-code-clj.matrix) + +(defn transpose [xs-of-xses] + (apply mapv vector xs-of-xses)) + +(defn coord-map-fixed + {:malli/schema [:-> [:sequential [:sequential :any]] [:map-of [:tuple :int :int] :any]]} + [xs-of-xses] + (->> xs-of-xses + (map-indexed (fn [idy xs] + (map-indexed (fn [idx v] + [[idy idx] v]) + xs))) + (transduce cat merge))) + +(defn text->matrix + {:malli/schema [:-> :string [:vector [:vector char?]]]} + [text] + (mapv vec (.split text "\n"))) diff --git a/src/advent_of_code_clj/utils.clj b/src/advent_of_code_clj/utils.clj index 2f79089..f317388 100644 --- a/src/advent_of_code_clj/utils.clj +++ b/src/advent_of_code_clj/utils.clj @@ -1,5 +1,7 @@ (ns advent-of-code-clj.utils - (:import [java.util HashSet])) + (:import [java.util HashSet]) + (:require + [advent-of-code-clj.matrix :as mx])) (defn coord-map {:malli/schema [:-> [:sequential [:sequential :any]] [:map-of [:tuple :int :int] :any]]} @@ -11,20 +13,9 @@ xs))) (transduce cat merge))) -(defn coord-map-fixed - {:malli/schema [:-> [:sequential [:sequential :any]] [:map-of [:tuple :int :int] :any]]} - [xs-of-xses] - (->> xs-of-xses - (map-indexed (fn [idy xs] - (map-indexed (fn [idx v] - [[idy idx] v]) - xs))) - (transduce cat merge))) +(def coord-map-fixed mx/coord-map-fixed) -(defn text->matrix - {:malli/schema [:-> :string [:vector [:vector char?]]]} - [text] - (mapv vec (.split text "\n"))) +(def text->matrix mx/text->matrix) (defn adjacent-hv "Find adjacent coordinates, without diagonals"