! 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* ; ! multistack/kstack operations : popk ( i seq -- elt ) nth pop ; : pushk ( elt i seq -- ) nth push ; : movek ( i j seq -- ) [ nip popk ] 2keep pushk ; : nmovek ( n i j seq -- ) '[ _ _ _ movek ] times ; : inst>nmovek ( inst seq -- ) [ [ move>> ] [ from>> 1 - ] [ to>> 1 - ] tri ] dip nmovek ; : tops ( seq -- seq ) [ pop ] map ; : part1 ( -- x ) "resource:work/aoc2022-5/input.txt" load-file parse-input swap [ reverse ] map [ '[ _ inst>nmovek ] each ] keep tops >string ; ! 9001 operations : popk2 ( n i seq -- elts ) [ swap cut ] change-nth ; : pushk2 ( elts i seq -- ) [ append ] change-nth ; : movek2 ( n i j seq -- ) [ nip popk2 ] 2keep pushk2 ; : inst>nmovek2 ( inst seq -- ) [ [ move>> ] [ from>> 1 - ] [ to>> 1 - ] tri ] dip movek2 ; : tops2 ( seq -- seq ) [ first ] map ; : part2 ( -- x ) "resource:work/aoc2022-5/input.txt" load-file parse-input swap [ '[ _ inst>nmovek2 ] each ] keep tops2 >string ;