Paste: aoc 5

Author: Kren/chunes
Mode: factor
Date: Mon, 5 Dec 2022 06:37:47
Plain Text |
USING: infix io io.encodings.ascii io.files kernel literals math
math.vectors sbufs sequences sorting.human splitting ;
IN: aoc2022.day05

CONSTANT: input $[
    "vocab:aoc2022/day05/input.txt" ascii file-lines
]

:: parse-crates ( -- seq )                                ! parse as a sequence of string buffers
    input { "" } split1 drop but-last                     ! [A]              {  SBUF" ACF"                     
    [| s | [infix s[1::4] infix] ] map flip               ! [C]     [Z]  =>     SBUF" S"
    [ reverse [ CHAR: space = ] trim-tail >sbuf ] map ;   ! [F] [S] [M]         SBUF" MZ" }

: parse-instructions ( -- seq )                           ! parse as a sequence of sequences of integers
    input { "" } split1 nip                               ! "move 3 from 2 to 7"      { { 3 2 7 }
    [ find-numbers [ real? ] filter { 0 1 1 } v- ] map ;  ! "move 1 from 3 to 5"   =>   { 1 3 5 } }

<PRIVATE

: setup-move ( crates instruction -- n from to )
    unclip spin nths first2 swap ;

PRIVATE>

: move-crates ( crates instruction -- )
    setup-move '[ _ _ pop swap push ] times ;

: move-stack ( crates instruction -- )
    setup-move rot 2dup tail* rotd append! drop swap
    '[ _ pop* ] times ;

: top-by ( ... quot: ( ... seq1 seq2 -- ... ) -- ... seq )
    [ parse-crates dup parse-instructions ] dip with each
    [ last ] map ; inline

: part1 ( -- ) [ move-crates ] top-by print ;
: part2 ( -- ) [ move-stack ] top-by print ;
: day05 ( -- ) part1 part2 ;

MAIN: day05

Annotation: correction

Author: Kren/chunes
Mode: factor
Date: Mon, 5 Dec 2022 06:40:41
Plain Text |
! parse as a sequence of string buffers
! [A]              {  SBUF" FCA"                     
! [C]     [Z]  =>     SBUF" S"
! [F] [S] [M]         SBUF" MZ" }

Annotation: correction #2

Author: Kren/chunes
Mode: factor
Date: Mon, 5 Dec 2022 06:42:51
Plain Text |
! It's 1-indexed, so
! parse as a sequence of sequences of integers
! "move 3 from 2 to 7"      { { 3 1 6 }
! "move 1 from 3 to 5"   =>   { 1 2 4 } }

New Annotation

Summary:
Author:
Mode:
Body: