Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: More while issues

by FalseVinylShrub (Chaplain)
on Mar 03, 2011 at 21:39 UTC ( [id://891312]=note: print w/replies, xml ) Need Help??


in reply to More while issues

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:

# code not tested because I've not got perl available # and I renamed your variables while ( $str =~ tr{a}{} # count the 'a's in $str && $count_y < $min_y # do we still want more 'y's? ) { # replace a random 'a' with a 'y' }

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.

Replies are listed 'Best First'.
Re^2: More while issues
by Dandello (Monk) on Mar 03, 2011 at 21:49 UTC

    To say that you guys are great is understating it SO much.

    Between the pointers given above and whatever other suggestions come in, I'm sure I'll have this licked in no time.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://891312]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (3)
As of 2024-04-24 19:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found