$| = 1; my $sum = 0; my @seen = (); my $min = 1; sub other { my $n = shift; my $bn = sprintf("%b", $n); my $v = $min; while (1) { my $bsumv = sprintf("%b", $sum ^ $v); if (not $seen[$v] and index($bsumv, $bn)>=0) { last; } $v++; } $sum ^= $v; $seen[$v] = 1; while ($seen[$min]) { $min++; } return $v; } foreach my $n (1..10_000) { print $n, " ", other($n), "\n"; }