Paste: AoC day 13

Author: Garklein
Mode: factor
Date: Tue, 13 Dec 2022 23:51:43
Plain Text |
USING: arrays classes combinators generalizations
io.encodings.utf8 io.files json.reader kernel math math.order
math.unicode prettyprint sequences sequences.extras sorting
splitting ;
IN: aoc.13

: input ( -- lines ) "~/factor/aoc/13/13.in" utf8 file-lines ;
: I ( -- pairs ) input { "" } split [ [ json> ] map ] map ;

: imp ( x y -- z ) [ [ +eq+ ≠ ] keep ] dip ? ;
: arrayify ( x -- x ) dup class-of fixnum = [ 1array ] when ;
: cmp ( x y -- z ) 2dup [ class-of ] bi@ 2array {
    { { fixnum fixnum } [ <=> ] }
    { { array  array  } [
        [ 2dup min-length '[ _ head ] bi@ [ cmp ] 2map +eq+ [ imp ] reduce ]
        [ [ length ] bi@ <=> ]
        2bi imp ] }
    [ drop [ arrayify ] bi@ cmp ]
    } case ;
: part1 ( -- n ) I [ first2 cmp ] map +lt+ swap indices [ 1 + ] map-sum ;
CONSTANT: dividers { { { 2 } } { { 6 } } }
: part2 ( -- n ) I concat dividers append [ cmp ] sort '[ _ index ] dividers swap map [ 1 + ] map-product ;

: solve ( -- ) part1 . part2 . ;

Annotation: Improvements

Author: Garklein
Mode: factor
Date: Wed, 14 Dec 2022 22:40:19
Plain Text |
USING: arrays classes combinators generalizations
io.encodings.utf8 io.files json.reader kernel math math.order
math.unicode prettyprint sequences sequences.extras sorting
splitting ;
IN: aoc.13

: input ( -- lines ) "~/factor/aoc/13/13.in" utf8 file-lines ;
: I ( -- pairs ) input { "" } split [ [ json> ] map ] map ;

: imp ( ord ord -- ord ) [ [ +eq+ ≠ ] keep ] dip ? ;
: arrayify ( x -- x ) dup number? [ 1array ] when ;
: cmp ( x y -- z ) 2dup [ class-of ] bi@ 2array {
    { { fixnum fixnum } [ <=> ] }
    { { array  array  } [
        [ [ cmp ] 2map +eq+ [ imp ] reduce ]
        [ [ length ] bi@ <=> ]
        2bi imp ] }
    [ drop [ arrayify ] bi@ cmp ]
    } case ;
: part1 ( -- n ) I [ first2 cmp ] map +lt+ swap indices [ 1 + ] map-sum ;
CONSTANT: dividers { { { 2 } } { { 6 } } }
: part2 ( -- n ) I concat dividers append [ cmp ] sort '[ _ index ] dividers swap map [ 1 + ] map-product ;

: solve ( -- ) part1 . part2 . ;

New Annotation

Summary:
Author:
Mode:
Body: