Last active
December 2, 2023 04:32
-
-
Save esciafardini/c2b2a238d6b8b217c59013ad96d231e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns core | |
(:require | |
[clojure.string :as string])) | |
;;day 1 | |
(defn string->arr-of-chars [string] | |
(mapv (fn [character] (Character/getNumericValue character)) string)) | |
(defn remove-non-integers [arr-of-chars] | |
(remove (fn [n] (> n 9)) arr-of-chars)) | |
(defn get-first-last-tuples [arr-of-ints] | |
[(first arr-of-ints) (last arr-of-ints)]) | |
(defn make-nums [[k v]] | |
(+ (* 10 k) v)) | |
;solution to part 1 | |
(->> (string/split-lines (slurp "input")) | |
(mapv (comp make-nums get-first-last-tuples remove-non-integers string->arr-of-chars)) | |
(reduce +)) | |
;;;PART 2 | |
(defn digit? [c] (and (>= 0 (compare \0 c)) | |
(>= 0 (compare c \9)))) | |
(def digit-regexes | |
#{#"seven" | |
#"nine" | |
#"two" | |
#"eight" | |
#"four" | |
#"six" | |
#"five" | |
#"one" | |
#"three"}) | |
(def reversed-regexes | |
#{#"eno" | |
#"owt" | |
#"eerht" | |
#"ruof" | |
#"evif" | |
#"xis" | |
#"neves" | |
#"thgie" | |
#"enin"}) | |
(def str-digit-lookup | |
{"one" 1 | |
"two" 2 | |
"three" 3 | |
"four" 4 | |
"five" 5 | |
"six" 6 | |
"seven" 7 | |
"eight" 8 | |
"nine" 9}) | |
(defn str->num [s] | |
(get str-digit-lookup s)) | |
(defn reversed-str->num [s] | |
(get (into {} (mapv (fn [[k v]] [(string/reverse k) v]) str-digit-lookup)) s)) | |
(defn extract [which s] | |
(let [first? (= which :first) | |
conversion-fn (if first? | |
str->num | |
reversed-str->num)] | |
(loop [seq-of-chars (if first? | |
(seq s) | |
(reverse (seq s))) | |
acc []] | |
(let [string-num (->> (mapv (fn [reg] (re-find reg (string/join "" acc))) | |
(if first? digit-regexes reversed-regexes)) | |
(remove nil?) | |
first | |
conversion-fn)] | |
(cond | |
(not (seq seq-of-chars)) | |
0 | |
(some? string-num) | |
string-num | |
(digit? (first seq-of-chars)) | |
(Character/getNumericValue (first seq-of-chars)) | |
:else | |
(recur (rest seq-of-chars) (conj acc (first seq-of-chars)))))))) | |
(->> (string/split-lines (slurp "input")) | |
(mapv (fn [s] (+ (* 10 (extract :first s)) (extract :last s)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment