A Scrambled Words Variant
October 11, 2019
In the previous exercise, we wrote a program to scramble the letters in each word of a string, retaining capitalization and punctuation: “Programming Praxis is fun!” became something like “Grprnimaogm Srxpia is unf!” Today’s exercise is the same, but with a simple variation: the first and last letters of each word must remain unchanged, so we might see something like “Prgrnimaomg Prxias is fun!”
Your task is to modify your previous program in the minimal possible way into a program that scrambles the letters in the interior of the words in a string, retaining capitalization and punctuation. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Again I’ll perl this – it just needs a tweak to the regular expression.
[soucecode lang=”bash”]
echo ‘Programming Praxis is a FUN thing to do!’ |\
perl -pe ‘s{(?<=[a-z])([a-z]+)(?=[a-z])}{$1^uc$1|join””,map{$->[0]}sort{$a->[1]<=>$b->[1]}map{[$,rand]}split//,uc$1}ieg’
[/sourcecode]
Actually realised I didn’t need to do the split last time and so my previous answer can be shortened.
[soucecode lang=”bash”]
echo ‘Programming Praxis is a FUN thing to do!’ |\
perl -pe ‘s{([a-z]+)}{$1^uc$1|join””,map{$->[0]}sort{$a->[1]<=>$b->[1]}map{[$,rand]}split//,uc$1}ieg’
[/sourcecode]
The only difference between these is the regular expression needed to find interior words … In the former I’m using non-negative-lookbehind “(?<= )” and non-negative-lookahead “(?= )” to strip the first and last letters off the word strings….
Here’s a solution in Python.
Output:
C++ as before. This one uses a better RNG and reads input from std::cin.
A Haskell version. The change is the addition of interiorA and its helper function, surround.