my $n = 20; my $k = 5; for (my $t=0;$t<10;$t++) { my @l = map { int(rand($k)) } 1..$n; my $best_start = 0; my $best_direction = 1; for (my $s = 0;$s<$n;$s++) { foreach my $d (-1,1) { my $f1 = $s; my $f2 = $best_start; for (my $i=0;$i<$n;$i++) { my $c = $l[($f1+$n)%$n] <=> $l[($f2+$n)%$n]; if ($c!=0) { if ($c<0) { $best_start = $s; $best_direction = $d; } last; } $f1 += $d; $f2 += $best_direction; } } } my @n = @l[map { ($best_direction*$_+$best_start+$n)%$n } 0..$n-1]; print "original: @l\n"; print "normal: @n\n"; print "\n"; }