USING: arrays io.encodings.utf8 io.files kernel math math.parser math.unicode math.vectors prettyprint sequences splitting strings vectors ; IN: aoc.5 : parse-crates ( strings -- crates ) flip [ last 32 ≠ ] filter [ [ 32 ≠ ] filter >vector ] map ; : parse-instructions ( strings -- instrs ) [ " " split [ dec> ] map sift { 0 1 1 } v- ] map ; : input ( -- instrs crates ) "~/factor/aoc/5/5.in" utf8 file-lines { "" } split first2 swap [ parse-instructions ] [ parse-crates ] bi* ; :: amend ( seq n quote: ( elt -- ... newelt ) -- ... seq ) n seq nth quote call n seq set-nth seq ; inline : pick-up ( crates len from -- crates' up ) swap [ cut ] curry amend swap ; : put-down ( crates up to -- crates' ) swap [ swap append ] curry amend ; :: crane ( fn -- str ) input [ first3 [ pick-up fn call ] dip put-down ] reduce [ first ] map >string ; inline : part1 ( -- str ) [ reverse ] crane ; : part2 ( -- str ) [ ] crane ; : solve ( -- ) part2 part1 . . ;