]> www.fi.muni.cz Git - aoc.git/blobdiff - 2020/14.pl
Moved 2020 to a subdir
[aoc.git] / 2020 / 14.pl
diff --git a/2020/14.pl b/2020/14.pl
new file mode 100755 (executable)
index 0000000..ab8f8b4
--- /dev/null
@@ -0,0 +1,38 @@
+#!/usr/bin/perl -w
+
+use strict;
+
+my %graph;
+my $count = 0;
+
+while (<>) {
+       my ($bag, $rest) = /\A(.*) bags? contain (.*)./;
+       if ($rest eq 'no other bags') {
+               $graph{$bag} = []; # ale neprojevi se
+       } else {
+               for my $contain (split /, /, $rest) {
+                       my ($count, $color) = ($contain =~ /\A(\d+) (.*) bag/);
+                       push @{ $graph{$bag} }, [ $color => $count ];
+               }
+       }
+}
+
+my %seen = ('shiny gold' => 1);
+my %total;
+
+sub walk {
+       my ($color) = @_;
+       
+       return $total{$color}
+               if defined $total{$color};
+
+       $total{$color} = 1;
+       for my $next (@{ $graph{$color} }) {
+               my ($ncol, $ncount) = @$next;
+               $total{$color} += $ncount*walk($ncol);
+       }
+
+       return $total{$color};
+}
+
+print "Result is ", walk('shiny gold') - 1, "\n";