--- /dev/null
+#!/usr/bin/perl -w
+
+use strict;
+
+local $/ = "\n\n";
+my @ranges;
+for (split /\n/, <>) {
+ my (@cls) = /\A(.*): (\d+)-(\d+) or (\d+)-(\d+)/;
+ print "$2:$3,$4:$5.\n";
+ push @ranges, [$2, $3], [$4, $5];
+}
+
+$_ = <>;
+my @your = /(\d+)/g;
+print "Your:", join("|", @your), "\n";
+
+my $sum = 0;
+# my @nearby;
+for (split /\n/, <>) {
+ next if !/\d/;
+ my @n = /(\d+)/g;
+ # print "nearby:", join("|", @n), "\n";
+ # push @nearby, \@n;
+ NUM:
+ for my $num (@n) {
+ for my $r (@ranges) {
+ if ($num >= $r->[0] && $num <= $r->[1]) {
+ next NUM;
+ }
+ }
+ print "$num is invalid\n";
+ $sum += $num;
+ }
+}
+
+print "sum=$sum\n";
--- /dev/null
+#!/usr/bin/perl -w
+
+use strict;
+
+local $/ = "\n\n";
+my @classes;
+for (split /\n/, <>) {
+ my (@cls) = /\A(.*): (\d+)-(\d+) or (\d+)-(\d+)/;
+ print "$2:$3,$4:$5.\n";
+ push @classes, \@cls;
+}
+
+$_ = <>;
+my @your = /(\d+)/g;
+print "Your:", join("|", @your), "\n";
+
+my @nearby;
+TICKET:
+for (split /\n/, <>) {
+ next if !/\d/;
+ my @n = /(\d+)/g;
+ NUM:
+ for my $num (@n) {
+ for my $r (@classes) {
+ if (($num >= $r->[1] && $num <= $r->[2])
+ || $num >= $r->[3] && $num <= $r->[4]) {
+ next NUM;
+ }
+ }
+ next TICKET;
+ }
+ # print "nearby:", join("|", @n), "\n";
+ push @nearby, \@n;
+}
+
+my %valid_cols;
+for my $cls (@classes) {
+ my ($name, $f1, $t1, $f2, $t2) = @$cls;
+ # print "Class $name:\n";
+ COL:
+ for my $col (0 .. $#your) {
+ # print "col $col\n";
+ for my $ticket (@nearby) {
+ if (($ticket->[$col] < $f1 || $ticket->[$col] > $t1)
+ && $ticket->[$col] < $f2 || $ticket->[$col] > $t2) {
+ next COL;
+ }
+ }
+ $valid_cols{$name}->{$col} = 1;
+ print "$name can be $col\n";
+ }
+}
+
+my $mul = 1;
+LOOP:
+while (keys %valid_cols) {
+ for my $class (keys %valid_cols) {
+ if (keys %{ $valid_cols{$class} } == 1) {
+ my ($col) = keys %{ $valid_cols{$class} };
+ print "$class is $col\n";
+ delete $valid_cols{$class};
+ for my $cl1 (keys %valid_cols) {
+ delete $valid_cols{$cl1}->{$col};
+ }
+ $mul *= $your[$col] if $class =~ /\Adeparture/;
+ next LOOP;
+ }
+ }
+}
+
+print "Total: $mul\n";