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