musifter

AoC day 23 (pt1), Perl

Dec 23rd, 2020 (edited)
746
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.86 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. my @ring;
  7. my ($curr, $prev);
  8.  
  9. # Read in file, building ring
  10. chomp( my $input = <> );
  11. foreach (split( //, $input )) {
  12.     $curr //= $_;
  13.     $ring[$prev] = $_  if (defined $prev);
  14.     $prev = $_;
  15. }
  16. $ring[$prev] = $curr;
  17.  
  18. # run 100 turns
  19. foreach (1 .. 100) {
  20.     # Advance ptr marking cups (cup 0 doesn't exist, marked as "grabbed" too)
  21.     my $ptr = $curr;
  22.     my %grab = (0 => 1, map { $ptr = $ring[$ptr]; $ptr => 1 } (1 .. 3));
  23.  
  24.     # Calculate destination (assuming cups 1-9 in input)
  25.     my $dest = $curr - 1;
  26.     $dest = ($dest - 1) % 10 while (exists $grab{$dest});
  27.  
  28.     # Relink ring
  29.     ($ring[$curr], $ring[$ptr], $ring[$dest]) = ($ring[$ptr], $ring[$dest], $ring[$curr]);
  30.  
  31.     $curr = $ring[$curr];
  32. }
  33.  
  34. print "Part 1: ";
  35. $curr = 1;
  36. print $curr while (($curr = $ring[$curr]) != 1);
  37. print "\n";
Add Comment
Please, Sign In to add comment