This commit is contained in:
Adam Jeniski 2023-12-09 12:37:23 -05:00
parent 3bfcd41f4f
commit 898532fd6d
2 changed files with 34 additions and 11 deletions

View File

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

View File

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