Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- $| = 1;
- my @ring;
- my ($curr, $prev);
- # Read in file, building ring
- chomp( my $input = <> );
- foreach (split( //, $input )) {
- $_ = int($_);
- $curr //= $_;
- $ring[$prev] = $_ if (defined $prev);
- $prev = $_;
- }
- # add in remaining cups:
- foreach my $i (10 .. 1_000_000) {
- $ring[$prev] = $i;
- $prev = $i;
- }
- $ring[1_000_000] = $curr;
- foreach my $t (1 .. 10_000_000) {
- print "Turn: $t\r" if ($t % 100000 == 0);
- # Advance ptr marking cups (cup 0 doesn't exist, marked as "grabbed" too)
- my $ptr = $curr;
- my %grab = (0 => 1);
- foreach (1 .. 3) {
- $ptr = $ring[$ptr];
- $grab{$ptr} = 1;
- }
- # calculate destination
- my $dest = $curr - 1;
- $dest = ($dest - 1) % 1_000_001 while (exists $grab{$dest});
- # relink ring
- my $old = $ring[$curr]; # save ptr from curr to start of block
- $ring[$curr] = $ring[$ptr]; # link curr to after block
- $ring[$ptr] = $ring[$dest]; # link last of block to after dest
- $ring[$dest] = $old; # link dest to start of block
- $curr = $ring[$curr];
- }
- print "\nPart 2: ", $ring[1] * $ring[$ring[1]], "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement