Advertisement
musifter

AoC day 22 (pt1), Perl

Dec 22nd, 2020
1,787
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.81 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. $/ = '';
  7.  
  8. # Read decks:
  9. my @deck;
  10. foreach my $p (0 .. 1) {
  11.     $_ = <>;
  12.     $deck[$p]->@* = split( "\n" );
  13.     shift @{$deck[$p]};
  14. }
  15.  
  16. foreach my $p (0 .. 1) {
  17.     print "deck $p: ", join( ',', @{$deck[$p]} ), "\n";
  18. }
  19.  
  20. sub score_deck {
  21.     print "winning deck: ", join( ',', @_ ), "\n";
  22.  
  23.     my $score = 0;
  24.     my $i = 1;
  25.     while (@_) {
  26.         $score += ($i * pop @_);
  27.         $i++;
  28.     }
  29.     return ($score);
  30. }
  31.  
  32. # Play game:
  33. while (@{$deck[0]} && @{$deck[1]}) {
  34.     my ($card0, $card1) = (shift @{$deck[0]}, shift @{$deck[1]});
  35.     if ($card0 > $card1) {
  36.         push( @{$deck[0]}, ($card0, $card1) );
  37.     } else {
  38.         push( @{$deck[1]}, ($card1, $card0) );
  39.     }
  40. }
  41.  
  42. # Score:
  43. print "Score: ", &score_deck( @{$deck[0]} || @{$deck[1]} ), "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement