Paste: AoC 2022 Day 11

Author: Kacarott
Mode: factor
Date: Sun, 11 Dec 2022 13:28:22
Plain Text |
! Copyright (C) 2022 Keldan Chapman.
! See http://factorcode.org/license.txt for BSD license.
USING: kernel AOC 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 rotd '[ _ _ compose call( x -- r ) [ _ call( r -- n ) ] keep 2array ] map ; inline

EBNF: parse [=[
    ws      = (" " | "\n")*
    rest    = (!("\n") .)*
    num     = [0-9]+ => [[ dec> ]]
    sqr     = "old * old"~ => [[ [ sq ] ]]
    plus    = "old + "~ num => [[ '[ _ + ] ]]
    times   = "old * "~ num => [[ '[ _ * ] ]]
    items   = "Starting items: "~ ((", "?)~ num)*
    op      = "Operation: new = "~ (sqr | plus | times)
    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 ( input -- result ) parse 20 [ 3 /i ] run-sim ;

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

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

New Annotation

Summary:
Author:
Mode:
Body: