Paste: AoC 2022 day 5
Author: | zip |
Mode: | factor |
Date: | Mon, 5 Dec 2022 14:02:35 |
Plain Text |
USING: arrays io io.encodings.utf8 io.files kernel sequences math math.functions ranges sets splitting ui.clipboards namespaces math.parser ;
IN: dec-5
: paste ( -- array ) clipboard get clipboard-contents "\n" split ;
: row-crates ( string -- array ) dup length 4 / floor 0 swap [a..b] [ 4 * 1 + dup 1 + pick subseq ] map nip ;
: >crates ( array -- array ) [ row-crates ] map flip [ reverse " " swap remove ] map ;
: cleanup-moves ( array -- array ) "" split1 nip "" swap remove ;
: parse-input ( array -- crates commands ) [ CHAR: [ swap in? not ] split1-when-slice [ >crates ] dip cleanup-moves ;
: command>action ( string -- from to count ) "move " split1 nip " from " split1 [ string>number ] dip " to " split1 [ string>number 1 - ] dip string>number 1 - rot ;
: index-stacks ( array number number -- array array array ) [ dup ] 2dip [ over ] dip [ swap nth ] 2bi@ ;
: move-items ( array array number -- array array ) pick length - neg swap [ 1array split-indices first2 reverse ] dip prepend ;
: move-items2 ( array array number -- array array ) pick length - neg swap [ 1array split-indices first2 ] dip prepend ;
: execute-action ( array number number number -- array ) [ [ index-stacks ] 2keep ] dip -rot [ move-items ] 2dip [ swap ] dip [ pick set-nth ] 2dip pick set-nth ;
: execute-action2 ( array number number number -- array ) [ [ index-stacks ] 2keep ] dip -rot [ move-items2 ] 2dip [ swap ] dip [ pick set-nth ] 2dip pick set-nth ;
: process-crates ( crates commands -- crates ) [ command>action execute-action ] each ;
: process-crates2 ( crates commands -- crates ) [ command>action execute-action2 ] each ;
: input ( -- array ) "/Users/zip/Desktop/aoc2022/dec-5/input.txt" utf8 file-lines ;
: part1 ( -- string ) input parse-input process-crates [ last ] map "" join ;
: part2 ( -- string ) input parse-input process-crates2 [ last ] map "" join ;
New Annotation