From 898532fd6d2a37fe044f766d41e75eed41853eba Mon Sep 17 00:00:00 2001 From: Adam Jeniski Date: Sat, 9 Dec 2023 12:37:23 -0500 Subject: [PATCH] golf --- 2023/src/core.clj | 30 ++++++++++++++++++++++++++++-- 2023/src/day09.clj | 15 ++++++--------- 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/2023/src/core.clj b/2023/src/core.clj index c677e12..7f22c8e 100644 --- a/2023/src/core.clj +++ b/2023/src/core.clj @@ -5,7 +5,9 @@ (def input-cache (atom {})) (def cookie (str "session=" (slurp "session"))) -(defn get-puzzle-input [day] +(defn get-puzzle-input + "retrieves and caches aoc input for 2023 given a day" + [day] (or (@input-cache day) (swap! input-cache assoc day (-> (str "https://adventofcode.com/2023/day/" day "/input") @@ -14,12 +16,36 @@ :body string/split-lines)))) -(defn re-seq-pos [pattern string] +(defn re-seq-pos + "re-seq that produces a seq of {:start :end :group}" + [pattern string] (let [m (re-matcher pattern string)] ((fn step [] (when (. m find) (cons {:start (. m start) :end (. m end) :group (. m group)} (lazy-seq (step)))))))) +(defn split-spaces [s] + (string/split s #" ")) + +(defmacro comp> + "comp, but fn-args are applied from left to right" + [& ls] (let [r (reverse ls)] + `(comp ~@r))) + +(defmacro static-fn + "wraps java static methods in a lambda so they can be passed as function objects" + [f] `#(~f %)) + +(defn mapvf + "returns a function that does mapv over f when called with a coll" + [f] #(mapv f %)) + +(defn reducef + "returns a function that reduces over f when called with a coll" + ([f] #(reduce f %)) + ([f init] #(reduce f init %))) + (comment + (map (static-fn Long/parseLong) ["123" "456"]) input-cache) diff --git a/2023/src/day09.clj b/2023/src/day09.clj index b3427f3..50bd5bb 100644 --- a/2023/src/day09.clj +++ b/2023/src/day09.clj @@ -1,8 +1,5 @@ -(ns day09 (:require [core :refer [get-puzzle-input]] - [clojure.string :as str])) - -(defn parse-line [line] (->> (str/split line #" ") - (mapv #(Long/parseLong %)))) +(ns day09 (:require + [core :refer [comp> get-puzzle-input mapvf reducef split-spaces]])) (defn generate-pyramid [nums] (loop [pyramid [nums]] @@ -11,10 +8,10 @@ pyramid (recur (conj pyramid (mapv - (rest last-line) last-line))))))) -(defn solve [reduction] (->> (get-puzzle-input 9) - (map (comp reverse generate-pyramid parse-line)) - (map #(reduce reduction 0 %)) - (reduce +))) +(defn solve [reduction] + (reduce + (map (comp> split-spaces (mapvf parse-long) generate-pyramid reverse + (reducef reduction 0)) + (get-puzzle-input 9)))) ;; part 1 (solve (fn [num line] (+ (peek line) num)))