Advertisement
musifter

AoC 2023 day 4 (Perl)

Dec 4th, 2023
1,050
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.83 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use v5.16;
  4. use warnings;
  5.  
  6. use List::AllUtils  qw(true sum);
  7.  
  8. # ASSUME: cards are listed in order
  9. # Array of number of wins for the N+1th card
  10. my @card_wins = map {
  11.                     my @p = split( /[:|]/ );
  12.                     my %win = map { $_ => 1 } split(' ', $p[1]);
  13.  
  14.                     true { exists $win{$_} } split(' ', $p[2])
  15.                 } <>;
  16.  
  17. # Recursive function: returns number of cards for scratching a card (including self)
  18. my %memo;
  19. sub scratch_card {
  20.     my $num = shift;
  21.     my $ret = 1;
  22.  
  23.     return ($memo{$num}) if (exists $memo{$num});
  24.  
  25.     $ret += &scratch_card( $num + $_ ) foreach (1 .. $card_wins[$num]);
  26.  
  27.     return ($memo{$num} = $ret);
  28. }
  29.  
  30. say "Part 1: ", sum map { $_ ? 1 << ($_ - 1) : 0 } @card_wins;
  31. say "Part 2: ", sum map { &scratch_card( $_ ) } (0 .. $#card_wins);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement