Paste: AOC day 12

Author: chunes
Mode: factor
Date: Sun, 13 Dec 2020 17:30:20
Plain Text |
USING: math.distances ;
IN: aoc.2020.12

CONSTANT: input $[
    "input.txt" ascii file-lines
    [ unclip [ dec> ] dip 2array ] map
]

TUPLE: turtle
    { loc initial: { 0 0 } } { heading initial: { 0 1 } } ;

: move ( t loc -- t' ) [ v+ ] curry change-loc ;
: north ( t n -- t' ) neg 0 2array move ;
: south ( t n -- t' ) 0 2array move ;
: east ( t n -- t' ) 0 swap 2array move ;
: west ( t n -- t' ) neg 0 swap 2array move ;
: (left) ( seq -- newseq ) first2 neg swap 2array ;
: (right) ( seq -- newseq ) first2 swap neg 2array ;

: turn ( t n quot -- t' )
    [ 90 / ] dip [ change-heading ] curry times ; inline

: left ( t n -- t' ) [ (left) ] turn ;
: right ( t n -- t' ) [ (right) ] turn ;
: forward ( t n -- t' ) over heading>> n*v move ;

: go ( t n ch -- t' )
    {
        { CHAR: N [ north ] }
        { CHAR: S [ south ] }
        { CHAR: E [ east ] }
        { CHAR: W [ west ] }
        { CHAR: L [ left ] }
        { CHAR: R [ right ] }
        { CHAR: F [ forward ] }
    } case ;

: part1 ( -- )
    turtle new input [ go ] assoc-each loc>> { 0 0 }
    manhattan-distance . ;


! ========== PART 2 ==========

TUPLE: wpturtle
    { loc initial: { 0 0 } } { wp initial: { -1 10 } } ;

: wpmove ( t loc -- t' ) [ v+ ] curry change-wp ;
: wpnorth ( t n -- t' ) neg 0 2array wpmove ;
: wpsouth ( t n -- t' ) 0 2array wpmove ;
: wpeast ( t n -- t' ) 0 swap 2array wpmove ;
: wpwest ( t n -- t' ) neg 0 swap 2array wpmove ;

: wpturn ( t n quot -- t' )
    [ 90 / ] dip [ change-wp ] curry times ; inline

: wpleft ( t n -- t' ) [ (left) ] wpturn ;
: wpright ( t n -- t' ) [ (right) ] wpturn ;
: wpforward ( t n -- t' ) over wp>> n*v move ;

: wpgo ( t n ch -- t' )
    {
        { CHAR: N [ wpnorth ] }
        { CHAR: S [ wpsouth ] }
        { CHAR: E [ wpeast ] }
        { CHAR: W [ wpwest ] }
        { CHAR: L [ wpleft ] }
        { CHAR: R [ wpright ] }
        { CHAR: F [ wpforward ] }
    } case ;

: part2 ( -- )
    wpturtle new input [ wpgo ] assoc-each loc>> { 0 0 }
    manhattan-distance . ;

New Annotation

Summary:
Author:
Mode:
Body: