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 ] ] 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 [ ] [ 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