Advertisement
musifter

AoC day 16 (pt2), Perl

Dec 16th, 2020
1,412
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.67 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use List::AllUtils  qw(notall indexes product);
  7.  
  8. $/ = '';
  9.  
  10. my @valid;
  11. my @f_valid;
  12.  
  13. # Read ranges:
  14. $_ = <>;
  15.  
  16. my $f_num = 0;
  17. foreach (split( "\n" )) {
  18.     foreach my $range (map { s#-#..#r } (m#\d+-\d+#g)) {
  19.         foreach (eval( $range )) {
  20.             $valid[ $_ ] = 1;
  21.             $f_valid[ $f_num ][ $_ ] = 1;
  22.         }
  23.     }
  24.     $f_num++;
  25. }
  26. $f_num--;
  27.  
  28. # Read my ticket:
  29. $_ = <>;
  30.  
  31. my @mine = m#\d+#g;
  32. print "My ticket: ", join( ":", @mine ), "\n";
  33.  
  34.  
  35. # Read nearby tickets:
  36. $_ = <>;
  37.  
  38. my @f_table;
  39. foreach my $i (0 .. $f_num) {
  40.     %{$f_table[$i]} = map { $_ => 1 } (0 .. $f_num);    # init table to all valid
  41. }
  42.  
  43. foreach (split( "\n" )) {
  44.     my @ticket = m#\d+#g;
  45.  
  46.     next if (!@ticket || notall { $valid[$_] } @ticket);    # toss out invalid ones
  47.  
  48.     # scan to remove invalid possibilities from table:
  49.     foreach my $i (0 .. $f_num) {
  50.         foreach my $f (0 .. $f_num) {
  51.             delete $f_table[$i]{$f}  if (!$f_valid[$f][ $ticket[$i] ]);
  52.         }
  53.     }
  54. }
  55.  
  56. printf "\nTable:\n";
  57. foreach my $i (0 .. $f_num) {
  58.     foreach my $j (0 .. $f_num) {
  59.         print (($f_table[$i]{$j}) ? '.' : 'X');
  60.     }
  61.     print "\n";
  62. }
  63.  
  64. # Find the ones with only one choice, mark them in the key, delete for others, repeat
  65. printf "\nSolving:\n";
  66. my @answer_key;
  67. foreach (0 .. $f_num) {
  68.     foreach my $i (indexes { keys %$_ == 1 } @f_table) {
  69.         my $ans = (keys %{$f_table[$i]})[0];
  70.  
  71.         print "found $ans => $i\n";
  72.         $answer_key[$ans] = $i;
  73.         delete $f_table[$_]{$ans} foreach (0 .. $f_num);
  74.     }
  75. }
  76.  
  77. print "\nPart 2: ", product( map { $mine[ $answer_key[$_] ] } (0 .. 5) ), "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement