1
0
Fork 0
advent-23/p01.janet

55 lines
1.2 KiB
Plaintext
Executable File

#!/usr/bin/env janet
(use spork/test)
(def peg
'{:main
(+ (<- :d)
(/ "one" "1")
(/ "two" "2")
(/ "three" "3")
(/ "four" "4")
(/ "five" "5")
(/ "six" "6")
(/ "seven" "7")
(/ "eight" "8")
(/ "nine" "9"))})
(defn match-digits [input]
"Do a peg match character by character. Unfortunately couldn't figure out how to do overlap another way"
(var arr @[])
(loop [i :range [0 (length input)]]
(let [match (first (peg/match peg input i))]
(if match
(array/push arr (first (peg/match peg input i))))))
arr)
(defn first+last [input]
(let [m (match-digits input)]
(scan-number
(string/join [(first m) (last m)]))))
(defn solve [lines]
(sum (map first+last lines)))
(start-suite)
(assert (deep= @["1"] (match-digits "one")))
(assert (deep= @["1" "2"] (match-digits "onetwo")))
(assert (deep= @["1" "2" "3"] (match-digits "one2three")))
(assert (deep= @["8" "3"] (match-digits "eighthree")))
(def example
["two1nine"
"eighthree"
"abcone2threexyz"
"xtwone3four"
"4nineightseven2"
"onefour"
"7pqrstsixteen"])
(assert (= 281 (solve example)))
(end-suite)
(pp (with [f (file/open "p01.txt")] (solve (file/lines f))))