$| = 1; sub tobin { my $n = shift; my @b = (); do { my $b = $n % 2; $n -= $b; $n /= 2; @b = ($b, @b); } while ($n); return @b; } my $current = "*"; # A108737 sub a { my $n = shift; my $b = join("" => tobin($n)); if (index($current, $b)<0) { foreach my $r (1..length($b)) { my $l = length($b) - $r; if ($l <= length($current)) { if (substr($current, length($current)-$l) eq substr($b, 0, $l)) { $current .= substr($b, $l); last; } } } } return index($current, $b); } foreach my $n (0..10_000) { print $n, " ", a($n), "\n"; }