advent-23/p01.janet
2023-12-03 04:57:58 -05:00

49 lines
1 KiB
Plaintext
Executable file

#!/usr/bin/env janet
(use spork/test)
(def peg
'{:number
(+ (<- :d)
(/ (if "one" "on") "1")
(/ (if "two" "tw") "2")
(/ (if "three" "thre") "3")
(/ (if "four" "fou") "4")
(/ (if "five" "fiv") "5")
(/ (if "six" "si") "6")
(/ (if "seven" "seve") "7")
(/ (if "eight" "eigh") "8")
(/ (if "nine" "nin") "9"))
:main (any (thru :number))})
(defn pmatch [input] (peg/match peg input))
(defn first+last [input]
(var m (pmatch input))
(scan-number
(string/join [(first m) (last m)])))
(defn solve [lines]
(sum (map first+last lines)))
(start-suite)
(assert (deep= @["1"] (pmatch "one")))
(assert (deep= @["1" "2"] (pmatch "onetwo")))
(assert (deep= @["1" "2" "3"] (pmatch "one2three")))
(assert (deep= @["8" "3"] (pmatch "eighthree")))
(def example
["two1nine"
"eighthree"
"abcone2threexyz"
"xtwone3four"
"4nineightseven2"
"onefour"
"7pqrstsixteen"])
(assert (= 281 (solve example)))
(end-suite)
(print (with [f (file/open "p01.txt")] (solve (file/lines f))))