in reply to YET another regexp puzzle
I read through the responses so far and figured that it might be useful to someone to examine how someone might solve this problem using regular expressions (since that's how the problem was originally framed), even though I'd probably do something with substr() myself. Here are my thought processes.
First I thought, "how would I do this manually?" and I came up with the following REs
s/^(.)(.)(.*)/$2$1$3/s; # 12345 -> 21345 s/^(.)(.)(.)(.*)/$1$3$2$4/s; # 12345 -> 13245 s/^(..)(.)(.)(.*)/$1$3$2$4/s; # 12345 -> 12435 s/^(...)(.)(.)(.*)/$1$3$2$4/s; # 12345 -> 12354
The "(.)(.)" part matches the two characters we're going to swap and the "(.*)" part matches whatever is left in the string. I put the /s modifier on there in case a linefeed character was in the string.
Then I got to thinking ... it sure would be nice if that first s/// looked like all the others. So, of course, I got
s/^()(.)(.)(.*)/$1$3$2$4/s;
So now how do I put that stuff in a loop? One of the many cool things in perl is that you can interpolate your patterns like so:
my $dots = ".."; s/^($dots)(.)(.)(.*)/$1$3$2$4/s; # 12345 -> 12435
So, all I need to do is loop until length($dots) is greater than length($str)-2 (the -2 is because of the pair of characters we are swapping). So that gives me this final bit of code:
my $str = "12345"; my $dots = ""; while (length($dots) <= length($str)-2) { $_ = $str; s/^($dots)(.)(.)(.*)/$1$3$2$4/s; print; $dots .= "."; }
Hope this helps,
|
|---|