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 : destructure-nth ( crates len n -- crates' list ) swap [ cut ] curry amend swap ; : prepend-nth ( crates list n -- crates' ) swap [ swap append ] curry amend ; : pick-up ( crates {n,from,to} -- crates' up ) first2 destructure-nth ; : put-down ( crates up {n,from,to} -- crates' ) last prepend-nth ; :: crane ( fn -- str ) input [ [ pick-up fn call ] keep put-down ] reduce [ first ] map >string ; inline : part1 ( -- str ) [ reverse ] crane ; : part2 ( -- str ) [ ] crane ; : solve ( -- ) part2 part1 . . ;