{ my @next = (10, 1..9); # d -> next number not yet used ending with digit d my $carry = ""; # concatenation of first n terms minus n first digits sub nexta { if ($carry ne "") { my $d = substr($carry, 0, 1); my $a = $next[$d]; $next[$d] += 10; $carry = substr($carry, 1) . $a; return $a; } else { my $a = -1; foreach my $next (@next) { if (substr($next,0,1) eq substr($next,-1)) { if ($a==-1 || $a > $next) { $a = $next; } } } $next[$a%10] += 10; $carry = substr($a, 1); return $a; } } } foreach my $n (1..10_000) { my $a = nexta(); print "$n $a\n"; }