Paste: aoc 8

Author: Kren/chunes
Mode: factor
Date: Thu, 8 Dec 2022 09:23:55
Plain Text |
USING: arrays io.encodings.ascii io.files kernel literals math
math.extras math.matrices math.statistics math.vectors
prettyprint sequences sequences.extras ;
IN: aoc2022.day08

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

<PRIVATE

:: recombine ( ... seq quot1: ( ... seq -- ... newseq ) quot2: ( ... seq -- ... newseq ) quot3: ( ... seq seq -- ... newseq ) -- ... newseq )
    seq quot1 call seq quot2 call quot1 call quot2 call quot3 call ; inline

: chop ( seq -- slice ) rest-slice but-last-slice ;

: interior ( matrix -- newmatrix ) chop [ chop ] map ;

: explode ( seq m -- seq n )
    cut [ <reversed> ] dip 1 cut swap last [ 2array ] dip ;

: (view) ( seq n -- count )
    dupd [ < ] curry count-head dup rot length = 0 1 ? + ;

PRIVATE>

: visible ( seq -- newseq )                         ! map tree heights in a sequence to visibility
    [ cum-max [ < ] monotonic-count ]               ! nonzero for visible
    [ <reversed> ] [ v+ ] recombine ;

: matrix-visible ( matrix -- newmatrix )            ! map tree heights in a matrix to visibility
    [ [ visible ] map ] [ flip ] [ m+ ] recombine ;

: count-interior-visible-trees ( matrix -- n )
    matrix-visible interior concat [ 0 > ] count ;

: count-edge-trees ( matrix -- n )
    dimension { 1 2 } v* { 2 0 } v- { 2 1 } v* sum ;

: part1 ( -- )
    input count-edge-trees
    input count-interior-visible-trees + . ;

: view ( seq m -- n ) explode [ (view) ] curry map product ;   ! find horizontal view score for nth tree in a seq

: views ( seq -- newseq ) dup [ view nip ] with map-index ;    ! map heights to horizontal view scores in a seq

: part2 ( -- )
    input [ [ views ] map ] [ flip ] [ m* mmax ] recombine . ; ! get horizontal and vertical view score matrices,
                                                               ! multiply them together, and take the max
: day08 ( -- ) part1 part2 ;

MAIN: day08

New Annotation

Summary:
Author:
Mode:
Body: