Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use List::AllUtils qw(notall indexes product);
- $/ = '';
- my @valid;
- my @f_valid;
- # Read ranges:
- $_ = <>;
- my $f_num = 0;
- foreach (split( "\n" )) {
- foreach my $range (map { s#-#..#r } (m#\d+-\d+#g)) {
- foreach (eval( $range )) {
- $valid[ $_ ] = 1;
- $f_valid[ $f_num ][ $_ ] = 1;
- }
- }
- $f_num++;
- }
- $f_num--;
- # Read my ticket:
- $_ = <>;
- my @mine = m#\d+#g;
- print "My ticket: ", join( ":", @mine ), "\n";
- # Read nearby tickets:
- $_ = <>;
- my @f_table;
- foreach my $i (0 .. $f_num) {
- %{$f_table[$i]} = map { $_ => 1 } (0 .. $f_num); # init table to all valid
- }
- foreach (split( "\n" )) {
- my @ticket = m#\d+#g;
- next if (!@ticket || notall { $valid[$_] } @ticket); # toss out invalid ones
- # scan to remove invalid possibilities from table:
- foreach my $i (0 .. $f_num) {
- foreach my $f (0 .. $f_num) {
- delete $f_table[$i]{$f} if (!$f_valid[$f][ $ticket[$i] ]);
- }
- }
- }
- printf "\nTable:\n";
- foreach my $i (0 .. $f_num) {
- foreach my $j (0 .. $f_num) {
- print (($f_table[$i]{$j}) ? '.' : 'X');
- }
- print "\n";
- }
- # Find the ones with only one choice, mark them in the key, delete for others, repeat
- printf "\nSolving:\n";
- my @answer_key;
- foreach (0 .. $f_num) {
- foreach my $i (indexes { keys %$_ == 1 } @f_table) {
- my $ans = (keys %{$f_table[$i]})[0];
- print "found $ans => $i\n";
- $answer_key[$ans] = $i;
- delete $f_table[$_]{$ans} foreach (0 .. $f_num);
- }
- }
- print "\nPart 2: ", product( map { $mine[ $answer_key[$_] ] } (0 .. 5) ), "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement