Paste: AOC 2021, day 22

Author: gifti
Mode: factor
Date: Thu, 23 Dec 2021 13:36:59
Plain Text |
USING: arrays combinators generalizations io.encodings.utf8
io.files kernel math math.intervals math.order math.parser
math.ranges multiline namespaces peg.ebnf prettyprint sequences
sequences.generalizations ;
IN: 2021.22

EBNF: parse [=[
    number = [0-9-]+ => [[ dec> ]]
    range = [x-z]~ "="~ number ".."~ number (","?)~
    rule = ("on"|"off") " "~ range range range
]=]

: merge ( seq -- pair )
    [ first2 <= ] filter
    [ first first ] [ last second ] bi 2array ;

: split-cuboid ( cuboid1 cuboid2 -- cuboids ) [
        [ first ] [ second ] [ bi@ 2array ] bi-curry@ 2bi {
            [ drop infimum ]
            [ [ second 1 - ] [ first min ] bi* ]
            [ [ supremum ] [ infimum dup 1 + ] bi* ]
            [ [ first max ] [ first ] bi* ]
        } 2cleave [ 2array ] 2tri@ 3array
    ] 2map first3 {
        [ [ first ] [ merge ] [ merge ] tri* ]
        [ [ third ] [ merge ] [ merge ] tri* ]
        [ [ second ] [ first ] [ merge ] tri* ]
        [ [ second ] [ third ] [ merge ] tri* ]
        [ [ second ] [ second ] [ first ] tri* ]
        [ [ second ] [ second ] [ third ] tri* ]
    } 3cleave [ 3array ] 3 6 mnapply 6 narray
    [ [ first2 <= ] all? ] filter ;

: intersect? ( seq seq -- ? ) [
        [ first ] [ second ] [ bi@ 2array ] bi-curry@ 2bi
        [ supremum ] [ infimum ] bi* 2array
    ] 2map [ first2 <= ] all? ;

: reboot ( seq -- n )
    1 cut [ [ rest ] map ] dip [
        unclip [ [
            V{ } clone -rot [
                2dup intersect?
                [ split-cuboid append ] [ drop suffix ] if
            ] curry each
        ] keep ] dip "on" = [ suffix ] [ drop ] if
    ] each [ [ first2 swap - 1 + ] map product ] map-sum ;

"input22" utf8 file-lines [ parse ] map [
    [ rest [ first2 [ -50 >= ] [ 50 <= and ] bi* ] all? ] filter
] keep [ reboot . ] bi@

New Annotation

Summary:
Author:
Mode:
Body: