Paste: AOC day 2

Author: chunes
Mode: factor
Date: Thu, 2 Dec 2021 06:11:55
Plain Text |
USING: accessors arrays assocs assocs.extras io.encodings.ascii
io.files kernel literals math math.parser prettyprint sequences
splitting words ;
IN: aoc.2021.02

! Parse input into alist that looks like
! { { "forward" 15 } { "down" 5 } ... }
CONSTANT: instructions $[
    "input.txt" ascii file-lines [ " " split1 dec> 2array ] map
]

: part1 ( -- )
    instructions expand-values-push-at [ sum ] map-values
    [ "down" of ] [ "up" of - ] [ "forward" of * . ] tri ;

TUPLE: position aim horizontal depth ;
: <position> ( -- p ) 0 0 0 position boa ;
: down ( p n -- ) '[ _ + ] change-aim drop ;
: up ( p n -- ) '[ _ - ] change-aim drop ;
: forward-h ( p n -- ) '[ _ + ] change-horizontal drop ;
: forward-a ( p n -- ) over aim>> * '[ _ + ] change-depth drop ;
: forward ( p n -- ) [ forward-h ] [ forward-a ] 2bi ;

: do-command ( p pair -- )
    first2 swap "aoc.2021.02" lookup-word execute( p n -- ) ;

: do-commands ( -- p )
    <position> instructions [ dupd do-command ] each ;

: part2 ( -- )
    do-commands [ depth>> ] [ horizontal>> ] bi * . ;

part1 part2

New Annotation

Summary:
Author:
Mode:
Body: