Advertisement
musifter

AoC 2023 day 7 part 2 (Perl)

Dec 7th, 2023 (edited)
919
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.89 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use v5.16;
  4. use warnings;
  5.  
  6. use List::AllUtils  qw(sum zip_by);
  7.  
  8. sub matches {
  9.     my $hand = shift;
  10.  
  11.     # Change cards to hexdigits... Jack to 0, as wild is low
  12.     $hand =~ y#AKQJT#EDC0A#;
  13.  
  14.     # Collect groups with hash
  15.     my %cards = map { $_ => 0 } (0 .. 9, 'A' .. 'E');
  16.     $cards{$_}++  foreach(split( '', $hand ));
  17.  
  18.     # Sort by group size (ignoring Jacks), add wild Jacks to best
  19.     my @str = sort { $cards{$b} <=> $cards{$a} } (2 .. 9, 'A' .. 'E');
  20.     $cards{$str[0]} += $cards{0};
  21.  
  22.     return ($hand, join('', map {$cards{$_}} @str));
  23. }
  24.  
  25. # Parse into array of [hand (hexified), match signature, bid]
  26. my @hands = map { m#(\w+) (\d+)#; [&matches($1),$2] } <>;
  27.  
  28. @hands = sort { $a->[1] <=> $b->[1] or hex($a->[0]) <=> hex($b->[0]) } @hands;
  29.  
  30. # Winnings is rank (low to high) * bid
  31. say "Part 2: ", sum zip_by {$_[0] * $_[1][2]} [1 .. @hands], \@hands;
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement