Paste: AOC day 5
        
	
	
	
		| Author: | chunes | 
|---|
		| Mode: | factor | 
|---|
		| Date: | Sun, 5 Dec 2021 08:21:51 | 
|---|
	
	Plain Text |
	
	USING: assocs io.encodings.ascii io.files kernel literals math
math.matrices math.parser math.ranges prettyprint sequences
sequences.extras sets splitting ;
IN: aoc.2021.05
<<
CONSTANT: vents $[                        
    "input.txt" ascii file-lines [        
        "->" without " " split harvest    
        [ "," split [ dec> ] map ] map    
    ] map                                 
]
: straight? ( pair pair -- ? ) [ = ] 2count 1 = ;
: straight ( seq -- newseq ) [ straight? ] assoc-filter ;
>>
CONSTANT: straight-vents $[ vents straight ]
: <ocean-floor> ( -- matrix )
    vents concat unzip [ supremum 1 + ] bi@ <zero-matrix> ;
: matrix-change-nth ( ..a pair matrix quot: ( ..a elt -- ..b newelt ) -- ..b )
    '[ matrix-nth @ ] [ matrix-set-nth ] 2bi ; inline
: matrix-inc ( pair matrix -- ) [ 1 + ] matrix-change-nth ;
: expand-straight-line ( seq -- newseq )
    unzip [ first2 [a,b] ] bi@ cartesian-product concat ;
: expand-diagonal-line ( seq -- newseq )
    flip first2 [ first2 [a,b] ] bi@ zip ;
: expand-line ( seq -- newseq )
    dup first2 straight?
    [ expand-straight-line ] [ expand-diagonal-line ] if ;
: expand-lines ( seq -- newseq ) [ expand-line ] map-concat ;
: <mapped-ocean-floor> ( seq -- matrix )
    <ocean-floor> tuck [ matrix-inc ] curry each ;
: .danger-count ( seq -- )
    expand-lines <mapped-ocean-floor> concat [ 1 > ] count . ;
: part1 ( -- ) straight-vents .danger-count ;
: part2 ( -- ) vents .danger-count ;
: main ( -- ) part1 part2 ;
MAIN: main
	
	
		New Annotation