--- /dev/null
+#!/usr/bin/perl -w
+
+use strict;
+
+my $rounds;
+($rounds, $_) = @ARGV;
+
+my @cups_nums = split //;
+my @cups_pos;
+my $i;
+for (@cups_nums) {
+ $cups_pos[$_] = $i++;
+}
+
+my $max = 1_000_000;
+
+my ($prev, @cups, $one);
+for (@cups_nums, 10 .. $max) {
+ my $cup = {
+ num => $_,
+ prev_num => $prev,
+ next => undef,
+ };
+ push @cups, $cup;
+ $one = $cup if $cup->{num} == 1;
+ $prev = $cup;
+}
+
+$prev = $cups[-1];
+for my $cup (@cups) {
+ $cup->{prev_num} = $cups[$cups_pos[$cup->{num}-1]]
+ if $cup->{num} > 1 && $cup->{num} <= 10;
+ $cup->{prev_num} = $cups[-1]
+ if $cup->{num} == 1;
+ $prev->{next} = $cup;
+ $prev = $cup;
+}
+
+# for my $cup (@cups) {
+# print $cup->{num}, ": >", $cup->{next}->{num}, " <", $cup->{prev_num}->{num}, "\n";
+# }
+
+my $cur = $cups[0];
+
+while ($rounds--) {
+ my @pickup;
+ my $cup = $cur->{next};
+ my $dest = $cur->{prev_num};
+ my %num_seen;
+ # print "pickup: ";
+ for (1..3) {
+ push @pickup, $cup;
+ $num_seen{ $cup->{num} } = 1;
+ # print $cup->{num}, ' ';
+ $cup = $cup->{next};
+ }
+ $dest = $dest->{prev_num} while $num_seen{$dest->{num}};
+ # print " dest: ", $dest->{num}, "\n";
+ $cur->{next} = $cup;
+ my $end = $dest->{next};
+ $dest->{next} = $pickup[0];
+ $pickup[-1]->{next} = $end;
+
+ $cur = $cur->{next};
+ # $end = $cur;
+ # do {
+ # print $end->{num}, ',';
+ # $end = $end->{next};
+ # } while ($end->{num} != $cur->{num});
+ # print "\n";
+ print "round $rounds\n" if $rounds % 100_000 == 0;
+}
+
+print "one -> ", $one->{next}->{num}, '*', $one->{next}->{next}->{num},
+ "=", $one->{next}->{num} * $one->{next}->{next}->{num}, "\n";