USING: infix io io.encodings.ascii io.files kernel literals math math.vectors sbufs sequences sorting.human splitting ; IN: aoc2022.day05 CONSTANT: input $[ "vocab:aoc2022/day05/input.txt" ascii file-lines ] :: parse-crates ( -- seq ) ! parse as a sequence of string buffers input { "" } split1 drop but-last ! [A] { SBUF" ACF" [| s | [infix s[1::4] infix] ] map flip ! [C] [Z] => SBUF" S" [ reverse [ CHAR: space = ] trim-tail >sbuf ] map ; ! [F] [S] [M] SBUF" MZ" } : parse-instructions ( -- seq ) ! parse as a sequence of sequences of integers input { "" } split1 nip ! "move 3 from 2 to 7" { { 3 2 7 } [ find-numbers [ real? ] filter { 0 1 1 } v- ] map ; ! "move 1 from 3 to 5" => { 1 3 5 } } : move-crates ( crates instruction -- ) setup-move '[ _ _ pop swap push ] times ; : move-stack ( crates instruction -- ) setup-move rot 2dup tail* rotd append! drop swap '[ _ pop* ] times ; : top-by ( ... quot: ( ... seq1 seq2 -- ... ) -- ... seq ) [ parse-crates dup parse-instructions ] dip with each [ last ] map ; inline : part1 ( -- ) [ move-crates ] top-by print ; : part2 ( -- ) [ move-stack ] top-by print ; : day05 ( -- ) part1 part2 ; MAIN: day05