feat: day 1 part 2

This commit is contained in:
Fernando Araoz 2024-11-11 11:01:55 -05:00
parent 1330e091a2
commit 5ba3b822e1
2 changed files with 29 additions and 40 deletions

View File

@ -63,50 +63,35 @@
'("four" "4") '("five" "5") '("six" "6") '("four" "4") '("five" "5") '("six" "6")
'("seven" "7") '("eight" "8") '("nine" "9")]) '("seven" "7") '("eight" "8") '("nine" "9")])
; the search tree ; Replaces the character at position `pos` with `replace`
; a node is a list with `:n` as first element, and then
; many options list. Each list option is a (Char, Node|Leaf).
; A leaf is (:l Int)
; Tree :: Vec of Node | Leaf
;
; Node :: (Char, Tree)
; Leaf :: String
;
; tree [
; (\a "1")
; ]
;
; ;
; string-replace-at :: String Int String -> String
(defn string-replace-at [input pos replace]
(let [input-length (count input)
first-part (.substring input 0 pos)
second-part (.substring input (inc pos) input-length)]
(str first-part replace second-part)))
; adds a new word to the current search tree ; tests every character on every number
(defn build-search-tree (defn sanitize-2
([] '()) "String -> String"
; (Tree, String, String) -> Tree [input] (reduce (fn [acc str-pos]
([prev-tree new-word new-value] ; find which, if any, of the patterns matches on this pos
(let ; match :: Maybe (String String)
; Vec of Char (let [match (utils/find-first (fn [pattern]
[new-letters (sequence new-word)]))) (= str-pos (.indexOf acc (first pattern))))
patterns)]
(defn new-leaf [value] value) ; if no number is found, return the acc as is,
(defn new-node [char tree] (list char tree)) ; otherwise, replace the first character with the corresponding number
(if (nil? match)
(def tree (new-node \a (new-leaf "A"))) acc
; replace the character at `str-pos` with the matched number
; (build-search-tree "a" "1") (string-replace-at acc str-pos (last match)))))
input
; Search tree that, given a starting index `idx`, (range (count input))))
; attempt to find a textual digit at that position.
(defn digit-at? [letters idx])
; Given "one3two4six" returns "13246"
; Given "eighttwothree" should include "823" somewhere, in that order
; String -> String
(defn sanitize-str [input]
(reduce (fn [acc next] (clojure.string/replace acc (first next) (last next))) input patterns))
(defn part2 [] (defn part2 []
(let [sanitized-lines (map sanitize-str lines) (let [sanitized-lines (map sanitize-2 lines)
numbers-str (map calibration-value-1 sanitized-lines) numbers-str (map calibration-value-1 sanitized-lines)
numbers (map Integer/parseInt numbers-str) numbers (map Integer/parseInt numbers-str)
sum (reduce + 0 numbers)] sum (reduce + 0 numbers)]

View File

@ -5,3 +5,7 @@
([day] (slurp (str "./input/" day ".txt"))) ([day] (slurp (str "./input/" day ".txt")))
([day test?] (slurp (str "./input" (if test? "_test/" "/") day ".txt")))) ([day test?] (slurp (str "./input" (if test? "_test/" "/") day ".txt"))))
(defn find-first
[f coll]
(first (filter f coll)))