Paste: aoc2023 day 1
Author: | erg |
Mode: | factor |
Date: | Fri, 1 Dec 2023 19:53:18 |
Plain Text |
USING: aoc2023 arrays ascii assocs http.client io.encodings.utf8
io.files kernel math math.parser sequences sorting splitting
strings ;
IN: aoc2023-1
: day1-input ( -- string ) 1 ?download-aoc2023-input ;
: aoc-day1-part1 ( -- n )
day1-input
split-lines [
[ [ digit? ] find nip ]
[ [ digit? ] find-last nip ] bi 2array >string string>number
] map-sum ;
CONSTANT: all-numbers {
"one" "two" "three" "four" "five" "six" "seven" "eight" "nine"
"1" "2" "3" "4" "5" "6" "7" "8" "9"
}
CONSTANT: number-words { f "one" "two" "three" "four" "five" "six" "seven" "eight" "nine" }
: find-first-number ( string number-strings -- number-string )
[ subseq-index ] with zip-with sift-values sort-values first first ;
: lookup-number ( string -- number-string )
dup length 1 > [
[ number-words ] dip '[ _ = ] find drop number>string
] when ;
: aoc-day1-part2 ( -- n )
day1-input
split-lines [
[
all-numbers find-first-number lookup-number
] [
reverse
all-numbers [ reverse ] map find-first-number
reverse
lookup-number
] bi
append string>number
] map-sum ;
New Annotation