Wednesday, November 11, 2009

 

Puzzle solving with regular expressions.

The puzzle this week from NPR's Weekend Edition is
If you write "WOW" in capital letters and hold up a mirror at the side of the word, you'll see "WOW" perfectly reflected in the mirror. Here's the puzzle: Think of a nationality and write it in capital letters. If you remove one stroke from the first letter, and one stroke from the last letter, and hold up a mirror at the side, the name of the nationality will be perfectly reflected in the mirror. What nationality is it?


The steps to my solution were:
  1. Grab a list of nationalities.
  2. Delete all entries which consisted of multiple words.
  3. Make the remaining words singular and all upper case letters.
  4. Search for items which matched the regular expression /^.[AHIMOTUVWXYZ]+.$/
  5. Pick the obvious answer out of the six matches.

Comments:
In VIM at 3am, because my headache won't let me sleep and my latest round of performance tests won't finish for another 90 minutes or so.

1. Ctrl-V
2. :%s/\s\+\*//
3. :%s/.*\s.*\n//
4. :%s/.*/\U&/
5. :%s/S$//
6. /^.[AHIMOTUVWXYZ]\+.$

Yields (unless you also chose ethnicity lists) the six answers referred to. Only one is a palindrome if you remove the first and last letters.

Oh, and "Z" doesn't give you errors, but it's also not symmetric, so it would only be allowable as the first or last letter, not as the reflected palindromic center of the word.

Fun stuff, even if you did the heavy lifting. But then again, my brain isn't used to functioning at this time of night anymore, so I'm content just to implement the pseudo-code and try (again) to go to sleep. And I don't have to be curious, because I know the answer.
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?