$| = 1;

my $word = "a";
my %psi = qw(a ab b ac c a);
my %pos = ();	# letter => @positions

sub get {
	my $letter = shift;
	my $n = shift;

	while ($n-1 > $#{$pos{$letter}}) {
		$word =~ s,[abc],$psi{$&},ge;

		%pos = ();
		foreach my $pos (0..length($word)) {
			push @{$pos{substr($word, $pos, 1)}} => 1+$pos;
		}
	}

	return $pos{$letter}[$n-1];
}

sub A003144 {
	return get("a", shift);
}
sub A003145 {
	return get("b", shift);
}
sub A003146 {
	return get("c", shift);
}

foreach my $n (1..10_000) {
	print $n, " ", A003144(A003146($n)), "\n";
}