day 1, part 2
This commit is contained in:
parent
509e797ba9
commit
ad04115853
@ -1,7 +1,7 @@
|
|||||||
(ns day01
|
(ns day01
|
||||||
(:require [clojure.string :as string]))
|
(:require [clojure.string :as string]))
|
||||||
|
|
||||||
(def input (-> "inputs/day01.test.1"
|
(def input (-> "inputs/day01"
|
||||||
slurp
|
slurp
|
||||||
(string/split #"\n")))
|
(string/split #"\n")))
|
||||||
|
|
||||||
@ -20,11 +20,7 @@
|
|||||||
|
|
||||||
;; part two
|
;; part two
|
||||||
|
|
||||||
(def input2 (-> "inputs/day01.test.2"
|
(def replacements
|
||||||
slurp
|
|
||||||
(string/split #"\n")))
|
|
||||||
|
|
||||||
(def replace-digits
|
|
||||||
{"one" "1"
|
{"one" "1"
|
||||||
"two" "2"
|
"two" "2"
|
||||||
"three" "3"
|
"three" "3"
|
||||||
@ -35,15 +31,29 @@
|
|||||||
"eight" "8"
|
"eight" "8"
|
||||||
"nine" "9"})
|
"nine" "9"})
|
||||||
|
|
||||||
(defn fix-line [l]
|
(defn replace-digit [d]
|
||||||
(let [replacements (->> (keys replace-digits)
|
(if-let [d' (replacements d)]
|
||||||
(mapcat (fn [d] {d (string/index-of l d)}))
|
d' d))
|
||||||
(filter (fn [[_ v]] (not (nil? v))))
|
|
||||||
(sort-by second))
|
(defn find-indices [s d]
|
||||||
fix-fn (apply comp
|
(loop [is []
|
||||||
(map (fn [[r _]] (fn [s] (string/replace s r (replace-digits r))))
|
i (string/index-of s d)]
|
||||||
replacements))]
|
(if (nil? i)
|
||||||
(fix-fn l)))
|
is
|
||||||
|
(recur (conj is i)
|
||||||
|
(string/index-of s d (inc i))))))
|
||||||
|
|
||||||
|
(defn actual-calibration-value [s]
|
||||||
|
(let [indexed-digits
|
||||||
|
(->> (mapcat seq replacements)
|
||||||
|
(mapcat (fn [d] {d (find-indices s (str d))}))
|
||||||
|
(remove (fn [[_ is]] (empty? is)))
|
||||||
|
(mapcat (fn [[d is]] (zipmap is (repeat d))))
|
||||||
|
(sort-by key))
|
||||||
|
f (val (first indexed-digits))
|
||||||
|
l (val (last indexed-digits))]
|
||||||
|
(read-string (str (replace-digit f)
|
||||||
|
(replace-digit l)))))
|
||||||
|
|
||||||
(def sum-of-actual-calibration-values
|
(def sum-of-actual-calibration-values
|
||||||
(reduce + (map (comp calibration-value fix-line) input2)))
|
(reduce + (map actual-calibration-value input)))
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user