Paste: AOC day 7

Author: chunes
Mode: factor
Date: Mon, 7 Dec 2020 20:06:19
Plain Text |
USING: arrays assocs combinators hashtables io.encodings.ascii
io.files kernel literals math math.parser memoize prettyprint
sequences splitting ;
IN: aoc.2020.07

CONSTANT: input $[                                    ! Parse the input into an adjacency list hash table.
    "input.txt" ascii file-lines                      ! It looks like this:
    [                                                 ! H{
        " bags contain " split1                       !     { "shiny gold" { { 2 "clear maroon" } { 1 "dark red" } } }
        dup "no other bags." =                        !     { "dark blue" { { 5 "dark green" } { 3 "dark violet" } } }
        [ drop { } ] [                                !     { "dark red" { } }  ! has no bags
            ", " split-subseq                         !     ...
            [                                         ! }
                " " split first4 drop " " glue swap
                string>number swap 2array
            ] map
        ] if 2array
    ] map >hashtable
]

MEMO: contains-shiny-gold? ( key -- ? )
    input at values
    {
        { [ dup empty? ] [ drop f ] }
        { [ "shiny gold" over member? ] [ drop t ] }
        [ [ contains-shiny-gold? ] any? ]
    } cond ;

: part1 ( -- ) input keys [ contains-shiny-gold? ] count . ;

: bags-inside ( n key -- m )
    input at
    [ [ first2 bags-inside ] map-sum dupd * + ] unless-empty ;

: part2 ( -- ) 1 "shiny gold" bags-inside 1 - . ;

New Annotation

Summary:
Author:
Mode:
Body: