clean up regex. compute not hardcode

This commit is contained in:
Adam Jeniski 2023-12-01 01:13:26 -05:00
parent 0ce843f177
commit 574d0888cc

View File

@ -6,14 +6,14 @@
(def input (get-puzzle-input 1)) (def input (get-puzzle-input 1))
(def numeric-value-map {"one" 1 (def numeric-value-map {"one" 1
"two" 2 "two" 2
"three" 3 "three" 3
"four" 4 "four" 4
"five" 5 "five" 5
"six" 6 "six" 6
"seven" 7 "seven" 7
"eight" 8 "eight" 8
"nine" 9}) "nine" 9})
(defn numeric-value [s] (defn numeric-value [s]
(or (numeric-value-map s) s)) (or (numeric-value-map s) s))
@ -28,10 +28,18 @@
(reduce +)) (reduce +))
;; part 2 ;; part 2
(def forawrd-search-regex (->> (conj (keys numeric-value-map) "\\d")
(string/join "|")
re-pattern))
(def backwards-search-regex (->> (conj (->> numeric-value-map keys (map string/reverse)) "\\d")
(string/join "|")
re-pattern))
(->> input (->> input
(map (fn [line] (map (fn [line]
(let [f (re-find #"one|two|three|four|five|six|seven|eight|nine|\d" line) (let [f (re-find forawrd-search-regex line)
l (string/reverse (re-find #"eno|owt|eerht|ruof|evif|xis|neves|thgie|enin|\d" (string/reverse line)))] l (string/reverse (re-find backwards-search-regex (string/reverse line)))]
(str (numeric-value f) (numeric-value l))))) (str (numeric-value f) (numeric-value l)))))
(map #(Integer/parseInt %)) (map #(Integer/parseInt %))
(reduce +)) (reduce +))