Perhaps I was a little optimistic when I said "slight error" :-)
In the code that I posted note how I discover the positions of the 'a' and 'c' letters before I start to modify the string. Note also that I don't have to count how many 'a's there are, only 'y's. This is because, according to your spec, the process of turning letters ('a's first then 'c's) into 'y's only continues until there are enough 'y's so the number of them in the string is the crucial factor. You have rather mangled the logic by forgetting about discovering where the 'a's are and assuming that all them will be changed, and then actually doing so willy nilly in a global substitution. You also move the discovery of letter 'c's inside while loop of the letter 'c' replacement stage when it should actually be done once before the string is modified.
In short, your implementation has almost nothing in common with the code I posted so it is perhaps not surprising that the results differ. A few points about your subroutine:
I think it would be better to pass and return the actual string being transformed rather than an index into an array, $yb, which you use to read then write to a particular array element.
You don't seem to use the second parameter, $chntot, at all.
Your logic breaks if there are more than enough 'a's to change.
Similarly, what happens if there are not enough 'c's and you exhaust the @Posns array?
I've already mentioned the problem with moving position finding inside the letter changing loop.
Putting all that together your subroutine might look like this.
...
$aod[$yb] = rankdwn( $aod[$yb], $howManyYsDoWeWant );
...
sub rankdwn {
my ( $str, $incrsdel ) = @_;
my $cnd_y = $str =~ tr/y/y/;
my @aPosns;
push @aPosns, pos $str while $str =~ m{(?=a)}g;
my @cPosns;
push @cPosns, pos $str while $str =~ m{(?=c)}g;
while ( ( $cnd_y < $incrsdel ) && @aPosns )
{
my $offset = splice @aPosns, rand @aPosns, 1;
substr $str, $offset, 1, q{y};
$cnd_y ++;
}
while ( ( $cnd_y < $incrsdel ) && @cPosns )
{
my $offset = splice @cPosns, rand @cPosns, 1;
substr $str, $offset, 1, q{y};
$cnd_y ++;
}
return $str;
}
I hope this will help you move onward with your code.
|