Advertisement
musifter

AoC 2023 day 7 part 1 (Perl)

Dec 7th, 2023
905
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.78 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
  12.     $hand =~ y#AKQJT#EDCBA#;
  13.  
  14.     # Collect groups with hash
  15.     my %cards = map { $_ => 0 } (2 .. 9, 'A' .. 'E');
  16.     $cards{$_}++  foreach(split( '', $hand ));
  17.  
  18.     # Sort by group size
  19.     my @str = sort { $cards{$b} <=> $cards{$a} } keys %cards;
  20.  
  21.     return ($hand, join('', map {$cards{$_}} @str));
  22. }
  23.  
  24. # Parse into array of [hand (hexified), match signature, bid]
  25. my @hands = map { m#(\w+) (\d+)#; [&matches($1),$2] } <>;
  26.  
  27. @hands = sort { $a->[1] <=> $b->[1] or hex($a->[0]) <=> hex($b->[0]) } @hands;
  28.  
  29. # Winnings is rank (low to high) * bid
  30. say "Part 1: ", sum zip_by {$_[0] * $_[1][2]} [1 .. @hands], \@hands;
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement