git.alexw.nyc home about git garden
    1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
f<< /sys/file.fs
f<< /sys/io.fs
    
f" /aoc/input"

: str0 ( a u -- ) rfor 0 i c! next  ;

9 stringlist snums "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"

0 value t
: wordnum ( a -- n or 0 ) 
  to t 3 5 rfor t i []>str snums sfind if 1+ break then i 5 = if 0 then next 
;  
 
: _getdigit ( a -- n ) c@ dup 0-9? if 48 - else drop 0 then ;
: getdigit-withtext ( a -- n ) >r r@ _getdigit ?dup not if r@ wordnum then rdrop ;  

alias noop getdigit

: first ( s -- n ) 
  c@+ rfor i getdigit ?dup if break then next 
;

: last ( s -- n ) 
  c@+ for dup i + 1- getdigit ?dup if break then next nip
;
: calibration ( s -- n ) dup first swap last swap 10 * + ;

0 value totala
0 value totalb
: solve begin file :readline ?dup while 
['] _getdigit ['] getdigit realias
dup calibration to+ totala
['] getdigit-withtext ['] getdigit realias
dup calibration to+ totalb
c@+ str0 
repeat 
totala . nl> totalb . nl> ;