#!/usr/bin/perl -w

use strict;

my ($rounds, $max, $cups) = @ARGV;

my @next_cup = (1 .. $max);
my $i = 0;
my $prev = @next_cup - 1;
my $cur;
for my $cup (split //, $cups) {
	$cup--; # count cup numbers from 0, not from 1
	$next_cup[$prev] = $cup;
	$prev = $cup;
	$cur //= $cup; # The first one
}
# $next_cup[6] = 2;

while ($rounds--) {
	my @pickup;
	my $cup = $next_cup[$cur];
	my %num_seen = ($cur => 1);
	# print "pickup: ";
	for (1..3) {
		push @pickup, $cup;
		$num_seen{ $cup } = 1;
		# print $cup + 1, ' ';
		$cup = $next_cup[$cup];
	}
	my $dest = $cur;
	while ($num_seen{$dest}) {
		$dest--;
		$dest = $max-1 if $dest < 0;
	}
	# print " dest: ", $dest + 1, "\n";
	$next_cup[$cur] = $cup;
	my $end = $next_cup[$dest];
	$next_cup[$dest] = $pickup[0];
	$next_cup[$pickup[-1]] = $end;

	$cur = $next_cup[$cur];
	$end = $cur;
	# do {
	#  	print $end+1, ',';
	# 	$end = $next_cup[$end];
	# } while ($end != $cur);
	# print "\n";
	print "round $rounds\n" if $rounds % 100_000 == 0;
}

print "one -> ", $next_cup[0] + 1, '*', $next_cup[$next_cup[0]] + 1,
	"=", ($next_cup[0]+1) * ($next_cup[$next_cup[0]]+1), "\n";
