Paste: AoC 2022 day 08

Author: xr
Mode: factor
Date: Wed, 14 Dec 2022 22:42:44
Plain Text |
! Copyright (C) 2022 Your name.
! See http://factorcode.org/license.txt for BSD license.
USING: sequences.deep peg.ebnf multiline math.matrices aoc kernel sequences arrays combinators math math.order ;
IN: aoc2022-8

: >1 ( ? -- 1/0 ) 1 0 ? ; inline

: visible-row* ( row -- state bitmap )
  0 swap [ [ max ] [ < >1 ] 2bi ] map ;

: visible-row ( row -- bitmap ) visible-row* nip ;

: visible* ( grid -- bitmap bitmap bitmap bitmap )
  {
    [ [ visible-row ] map ]
    [ [ reverse visible-row reverse ] map ]
    [ transpose [ visible-row ] map transpose ]
    [ transpose [ reverse visible-row reverse ] map transpose ]
  }
  cleave ;

: visible ( grid -- grid )
  visible* m+ m+ m+ ;

EBNF: parse [=[
  n= [0-9]+
]=]

: input ( -- n )
  P"work/aoc2022-8/input.txt" load-file
  [ parse ] map
;

: test-input ( -- n )
  P"work/aoc2022-8/test.txt" load-file
  [ parse ] map
;

: count-row ( row -- n )
  0 [ 0 = not 1 0 ? + ] reduce ;

: count-matrix ( matrix -- n )
  [ count-row ] map-sum ;

: part1 ( -- n )
  input
  visible
  count-matrix ;

:: rightbound ( index seq -- n )
index seq nth :> val
index 1 + seq
[ val - 0 >= ] find-from drop [ ] [ seq length 1 - ] if* ;

:: leftbound ( index seq -- n )
index seq nth :> val
index 1 - seq
[ val - 0 >= ] find-last-from drop [ ] [ 0 ] if* ;

:: scenic-row-elm ( index seq -- n )
  index seq [ rightbound index - ] [ leftbound index - ] 2bi * abs ;

: scenic-row ( seq -- seq )
  [ ] [ length <iota> ] bi [ [ swap scenic-row-elm ] keepd swap ] map nip ;

: scenic* ( matrix -- matrix matrix )
  [ [ scenic-row ] map ]
  [ transpose [ scenic-row ] map transpose ]
  bi ;

: scenic ( matrix -- matrix )
  scenic* m* ;

: part2 ( -- matrix )
  input
  scenic
  flatten
  supremum ;

New Annotation

Summary:
Author:
Mode:
Body: