explanation email: third in a series :)

This time I had a method that only one or two other people seemed to have used.

The solution was:

pos=$i++/2,//g,print"$`",$_=reverse,/^$'/?$/:redo for pop (57)

Basically, it takes the argument into a single iteration loop (for pop), with a
redo if it doesn't work out.

Making a palindrome is straightforward. We take something off the start of the
string, reverse it, and add it to the end. If we use one character to begin
with, then two, then three etc, we end up with the shortest palindrome (as per
the instructions) if we only print out the first concatenation that is the
reverse of itself.

Unfortunately it's made slightly more complicated by being able to add to the
start of the string, too, so for each length of end or start we check, we have
to do it to both the original string, and its reversed form.

I started out by setting pos

pos=$i++/2

giving pos = 0, .5, 1, 1.5, 2 etc. When pos is .5, it is 'int'ed to 0. Then I
match an empty string at that position, and go for the print, test, redo bit.

Arguments to print are:

$` - the prematch. I had to quote it, since by matching later in the statement,
It'd become something different. This way I'm printing a copy of the original
prematch.

$_=reverse - so instead of adding the reverse of $` (the start of the string) to
the end of $_, I'm adding the unreversed $` to the start of a reversed $_. Same
difference.

/^$'/?$/:redo -  I print $/ ("\n") and finish if the match is true, otherwise I
redo, which breaks out of the print (none of the stuff is printed), and tries
the whole thing again with the reverse of $_.

Why /^$'/?

$`.reverse($_) =~ /^$_/

is true if the LHS is a palindrome. (for monkey -> 'monke' . 'yeknom' =~
/^monkey/ )

Unfortunately, I'd reversed $_, so I couldn't use it in the regex. I still had
$` and $', though, so the above became

($`.($_=reverse)) =~ /^$`$'/

then when you take the $` off each side, we get the final

$_=reverse,/^$'/

mtve has post-mortemly improved the pos setting part (he used this technique to
do something only very slightly different in his solution) to:

pos=$$_++

very clever indeed (gives a 54). If the string is 'monkey', for each iteration
pos is $monkey++, then $yeknom++, then $monkey++ etc. I wish I'd thought of
that.

I hope that's all resonably clear. I think it is, anyway.

Jasper
-- 
Bucky: Hey, don't worry about Bucky Katt. I can withstand any form of
       interrogation.
Rob:   Are you kidding? An unpadded chair, a forty-watt bulb, and you'd
       crack like a plumber's backside.

Reply via email to