Paste: AoC 2022 day 11
Author: | xr |
Mode: | factor |
Date: | Fri, 6 Jan 2023 16:52:36 |
Plain Text |
USING: accessors combinators combinators.smart continuations
io.encodings.utf8 io.files kernel math math.functions
math.parser math.statistics multiline namespaces peg.ebnf
peg.parsers peg.search prettyprint quotations sequences
sequences.deep splitting strings words ;
IN: aoc.2022.11
TUPLE: monkey items operation divisible tmonkey fmonkey count ;
C: <monkey> monkey
: find-integers ( string -- nseq ) integer-parser search ;
: find-integer ( string -- n ) find-integers first ;
/* rewrite with tokenizer
Use tokenizer as operation-token? in a search?
*/
EBNF: operation [=[
digit = [0-9]+ => [[ dec> ]]
val = "old" => [[ [ dup ] ]] | digit
op = [*+] => [[ 1string "math" lookup-word ]]
space = " "
spaces = space*
rule = spaces~ "Operation: new = "~ val~ " "~ op " "~ val => [[ reverse flatten >quotation ]]
]=]
: tokenize-monkies ( file -- seq ) utf8 file-lines { "" } split ;
: parse-monkey ( seq -- monkey )
rest
[ { [ find-integers ] [ operation ] [ find-integer ] [ find-integer ] [ find-integer ] } spread 0 <monkey> ]
with-datastack first
;
: parse-monkies ( seq -- seq ) tokenize-monkies [ parse-monkey ] map ;
: bored ( n -- n ) 3 / floor ;
SYMBOLS: monkies monkies-mod (inspect) ;
: test ( n monkey -- n n )
[ divisible>> mod 0 = ] [ tmonkey>> ] [ fmonkey>> ] smart-if ;
: throw ( monkey -- quot: ( n -- ) ) '[ _ test monkies get nth items>> push ] ;
: (inspect-part1) ( monkey -- quot: ( n -- n ) ) operation>> '[ @ bored ] ; inline
: (inspect-part2) ( monkey -- quot: ( n -- n ) ) operation>> monkies-mod get '[ @ _ mod ] ; inline
: inspect ( monkey -- quot: ( n -- n ) ) (inspect) get [ ] 2sequence call( -- quot: ( n -- n ) ) ;
: (inc-count) ( monkey -- quot: ( -- ) ) '[ _ [ 1 + ] change-count drop ] ;
: turn ( monkey -- ) { [ items>> ] [ (inc-count) ] [ inspect ] [ throw ] [ V{ } clone >>items drop ] } cleave compose compose '[ _ call( n -- ) ] each ;
: round ( monkies -- ) monkies over '[ _ [ turn ] each ] with-variable ;
: rounds ( monkies n -- monkies ) over [ divisible>> ] map product monkies-mod [ [ dup round ] times ] with-variable ;
: monkey-business ( monkies -- n ) [ count>> ] map { 0 1 } kth-largests first2 * ;
CONSTANT: test-input P"resource:work/aoc/2022/11/example.txt"
CONSTANT: input P"resource:work/aoc/2022/11/input.txt"
: part1 ( file -- n ) \ (inspect-part1) (inspect) [ parse-monkies 20 rounds monkey-business ] with-variable ;
: part2 ( file -- n ) \ (inspect-part2) (inspect) [ parse-monkies 10000 rounds monkey-business ] with-variable ;
: day11 ( -- ) input part1 . input part2 . ;
MAIN: day11
New Annotation