Paste: AoC 2022 Day 21

Author: Kacarott
Mode: factor
Date: Wed, 21 Dec 2022 08:07:50
Plain Text |
! Copyright (C) 2022 Keldan Chapman.
! See http://factorcode.org/license.txt for BSD license.
USING: kernel AOC prettyprint splitting peg.ebnf multiline strings assocs math
       math.parser sequences ;
IN: AOC.2022.21

: eval-monkey ( assoc key -- res )
    over at dup number? [ nip ]
    [ first3 pickd rot [ [ eval-monkey ] 2bi@ ] dip call( x y -- r ) ] if ;

EBNF: parse [=[
    name = [a-z]+ => [[ >string ]]
    ops = [-+*/] => [[ { { 43 [ + ] } { 45 [ - ] } { 42 [ * ] } { 47 [ / ] } } at ]]
    num = [0-9]+ => [[ dec> ]]
    monkey = name ": "~ {num | name ops name}
]=]

: part-1 ( input -- result ) split-lines [ parse ] map "root" eval-monkey  ;
: part-2 ( input -- result )
    split-lines [ parse ] map "root" over at [ - ] 1 rot set-nth
    { 0 1 } [ "humn" pick set-at dup "root" eval-monkey ] map nip ! Only works for linear complexities, but could be extended?
    [ first ] [ first2 - ] bi / ;

MAIN: [ 21 read-day-input [ part-1 . ] [ part-2 . ] bi ]

New Annotation

Summary:
Author:
Mode:
Body: