Paste: Debugging AOC

Author: Kacarott
Mode: factor
Date: Sun, 11 Dec 2022 12:42:44
Plain Text |
! Copyright (C) 2022 Keldan Chapman.
! See http://factorcode.org/license.txt for BSD license.
USING: kernel AOC infix.parser infix.private math math.parser
       multiline peg.ebnf prettyprint strings splitting math.functions
       sequences arrays accessors combinators sorting math.order ;
IN: AOC.2022.11

TUPLE: monkey items worry next inspects ;
: throw-items ( monkey reducer -- seq ) swap {
        [ [ items>> ] keep over length '[ _ + ] change-inspects drop ]
        [ V{ } clone swap items<< ]
        [ worry>> ] [ next>> ]
    } cleave [ rot ] dip '[ _ _ compose call( x -- r ) [ _ call( r -- n ) ] keep 2array ] map ; inline

EBNF: parse [=[
    ws      = (" " | "\n")*
    rest    = (!("\n") .)*
    num     = [0-9]+ => [[ dec> ]]
    items   = "Starting items: "~ ((", "?)~ num)*
    op      = "Operation: new = "~ rest:func => [[ [ func "old" rot >dec replace >string dup . build-infix-ast infix-codegen ] ]]
    branch  = "If "~ ("true" | "false")~ ": throw to monkey "~ num ws~
    test    = "Test: divisible by "~ num:n ws~ branch:a branch:b => [[ [ n divisor? a b ? ] ]]
    monkey  = { "Monkey"~ num~ ":"~ items op test ws~ } => [[ first3 0 monkey boa ]]
    monkeys = monkey+
]=]

: run-sim ( parsed iterations reducer -- result ) '[
        dup [ _ throw-items [ first2 [ over nth items>> ] dip swap push ] each
        ] each ] times [ inspects>> ] map [ >=< ] sort first2 * ; inline

: part-1 ( parsed -- result ) 20 [ 3 /i ] run-sim ;

: part-2 ( parsed -- result ) 10000 over 1 [ next>> first lcm ] reduce '[ _ mod ] run-sim ;

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

New Annotation

Summary:
Author:
Mode:
Body: