]> www.fi.muni.cz Git - aoc2020.git/blob - 14.pl
Task 9 Perl Golf-style
[aoc2020.git] / 14.pl
1 #!/usr/bin/perl -w
2
3 use strict;
4
5 my %graph;
6 my $count = 0;
7
8 while (<>) {
9         my ($bag, $rest) = /\A(.*) bags? contain (.*)./;
10         if ($rest eq 'no other bags') {
11                 $graph{$bag} = []; # ale neprojevi se
12         } else {
13                 for my $contain (split /, /, $rest) {
14                         my ($count, $color) = ($contain =~ /\A(\d+) (.*) bag/);
15                         push @{ $graph{$bag} }, [ $color => $count ];
16                 }
17         }
18 }
19
20 my %seen = ('shiny gold' => 1);
21 my %total;
22
23 sub walk {
24         my ($color) = @_;
25         
26         return $total{$color}
27                 if defined $total{$color};
28
29         $total{$color} = 1;
30         for my $next (@{ $graph{$color} }) {
31                 my ($ncol, $ncount) = @$next;
32                 $total{$color} += $ncount*walk($ncol);
33         }
34
35         return $total{$color};
36 }
37
38 print "Result is ", walk('shiny gold') - 1, "\n";