! Copyright (C) 2022 Your name. ! See http://factorcode.org/license.txt for BSD license. USING: strings vectors accessors splitting aoc math math.matrices sequences kernel peg.parsers peg.search ; IN: aoc2022-5 : split-input ( seqstring -- seqstring seqstring ) { "" } split1 ; : not-space ( x -- ? ) 32 = not ; : parse-crates ( seqstring -- seqseq ) transpose ! Use numbers as guide for the columns [ last not-space ] filter ! clean columns from empty spaces and strip guide [ [ not-space ] filter but-last >vector ] map ; ! parse crates as vectors, requires a reversal or anti transpose TUPLE: inst { move read-only } { from read-only } { to read-only } ; C: inst : parse-instruction ( seqstring -- seqvec ) [ integer-parser search first3 ] map ; : parse-input ( seqstr -- seqses seqinst ) split-input [ parse-crates ] [ parse-instruction ] bi* swap ; : popk ( n i seq -- elts ) [ swap cut ] change-nth ; : pushk ( elts i seq -- ) [ append ] change-nth ; : movek ( n i j seq quot -- ) '[ nip popk @ ] 2keep pushk ; inline : inst>movek ( inst seq quot -- ) [ [ move>> ] [ from>> 1 - ] [ to>> 1 - ] tri ] 2dip movek ; inline : tops ( seq -- seq ) [ first ] map ; : part1 ( -- x ) "resource:work/aoc2022-5/input.txt" load-file parse-input [ '[ _ [ reverse ] inst>movek ] each ] keep tops >string ; : part2 ( -- x ) "resource:work/aoc2022-5/input.txt" load-file parse-input [ '[ _ [ ] inst>movek ] each ] keep tops >string ;