Advertisement
musifter

day 21, Perl

Dec 21st, 2020
1,617
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.19 KB | None | 0 0
  1. use strict;
  2. use warnings;
  3.  
  4. my %Ingred;
  5. my %Allerg;
  6.  
  7. # Read file:
  8. while (<>) {
  9.     my ($ingred_str, $allerg_str) = m#^(.*) \(contains (.*)\)$#;
  10.  
  11.     my @ings = split( " ", $ingred_str );
  12.     foreach my $i (@ings) {
  13.         $Ingred{$i}{num}++;
  14.     }
  15.  
  16.     foreach my $a (split( /, /, $allerg_str )) {
  17.         $Allerg{$a}{num}++;
  18.         foreach my $i (@ings) {
  19.             $Allerg{$a}{counts}{$i}++;
  20.         }
  21.     }
  22. }
  23.  
  24. # Part 1:
  25. my %poss;
  26. foreach my $a (keys %Allerg) {
  27.     foreach my $i (keys %{$Allerg{$a}{counts}}) {
  28.         $poss{$i}{$a}++  if ($Allerg{$a}{counts}{$i} == $Allerg{$a}{num});
  29.     }
  30. }
  31.  
  32. my $part1 = 0;
  33. $part1 += $Ingred{$_}{num} foreach (grep { !exists $poss{$_} } (keys %Ingred));
  34.  
  35. print "Part 1: $part1\n";
  36.  
  37. # Part 2 (day 16 deja vu):
  38. my %ans_key;
  39. my $solved = 0;
  40. my $num_allerg = keys %Allerg;
  41.  
  42. while ($solved < $num_allerg) {
  43.     foreach my $ingred (grep { keys %{$poss{$_}} == 1 } keys %poss) {
  44.         my $allerg = (keys %{$poss{$ingred}})[0];
  45.  
  46.         $ans_key{$allerg} = $ingred;
  47.         $solved++;
  48.         delete $poss{$_}{$allerg}  foreach (keys %poss);
  49.     }
  50. }
  51.  
  52. print "Part 2: ", join( ',', map { $ans_key{$_} } sort keys %ans_key ), "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement