Paste: AoC day 9
Author: | switchy |
Mode: | factor |
Date: | Sat, 10 Dec 2022 06:16:18 |
Plain Text |
USING: advent kernel assocs sequences math math.order math.parser math.vectors arrays accessors combinators sets ;
IN: advent.day9
TUPLE: state knots seen ;
: <state> ( n -- state )
1 + { 0 0 } <array> HS{ { 0 0 } } clone state boa ;
<PRIVATE
: (delta) ( dir -- delta )
{
{ CHAR: U { 0 1 } }
{ CHAR: D { 0 -1 } }
{ CHAR: L { -1 0 } }
{ CHAR: R { 1 0 } }
} at ;
: (input) ( -- input )
"day9.in" get-input
[ [ first (delta) ] [ 2 tail string>number ] bi 2array ] map
;
: (update-pair) ( head tail -- tail' )
tuck v- dup vabs [ 1 > ] any?
[ [ sgn ] map v+ ]
[ drop ] if
;
: (update-tails) ( state -- state' )
[
unclip
[ (update-pair) ] accumulate swap suffix
] change-knots
dup
[ knots>> last ] [ seen>> adjoin ] bi
;
: (step) ( state insn -- state' )
first2 swap
'[
[ knots>> [ first _ v+ ] keep set-first ] keep
(update-tails)
]
times
;
PRIVATE>
: day9-part1 ( -- n )
(input)
1 <state>
[ (step) ] reduce
seen>> cardinality
;
: day9-part2 ( -- n )
(input)
9 <state>
[ (step) ] reduce
seen>> cardinality
;
New Annotation