Clear questions and runnable code get the best and fastest answer |
|
PerlMonks |
Re: More while issuesby FalseVinylShrub (Chaplain) |
on Mar 03, 2011 at 21:39 UTC ( [id://891312]=note: print w/replies, xml ) | Need Help?? |
Hi While there are more Perlish ways to do this, such as using tr to count characters, for example, your real problem is with your algorithm. You don't want to use last to break out of the loop like that, that will break out of the a-replacement loop after replacing just one 'a'. What you want to do is stop the a-replacement loop when there are no 'a's left:
The code to replace a random 'a' with a 'y' looks like it would work, but it could go on forever randomly choosing elements before it finds an 'a'. Better to get a list of all the positions with an 'a' and choose randomly between them - and keep track of those that have been replaced already. I don't see why you need to count the 'y's again after the first while loop. Just increment the counter e.g. $count_y++ when you replace an 'a' with a 'y' in the first while loop. I don't think you need to count the 'a's again at all: if there still aren't enough 'y's then you must have replaced all 'a's; if there are enough 'y's, you don't care. You can use exactly the same code to replace 'c's with 'y's as was used to replace 'a's with 'y's. A subroutine would be great here. Hope this helps. FalseVinylShrub Disclaimer: Please review and test code, and use at your own risk... If I answer a question, I would like to hear if and how you solved your problem.
In Section
Seekers of Perl Wisdom
|
|