08 December 2007

Powershell Palindromes

A palindrome is a word or phrase that reads the same forwards or backwards. A well-known example is Madam, I am Adam. Another example is Weird Al Yankovic's song Bob, which is composed of rhyming palindromes. If you have a list of words in a file, here's how you can find palindromes using a one-liner in PowerShell.

> Get-Content <file> | Where-Object {[string]::Join("",$_[-1..-$_.Length]) -eq $_ }
…
aha
ala
dud
mm
mum
pap
pip
…

The one-liner translates to: for every line in an input file, display only lines which are the same forward and backward.

The complex part of this pipeline is the filter in Where-Object. In this filter, we …

  1. Convert the input string, $_, into an array of characters in reverse order: $_[-1..-$_.Length].
  2. Convert the array back into a string by using the Join() function with an empty separator: [string]::Join("",<array>).
  3. Compare the reversed and original strings using <s1> -eq <s2>.

Where-Object only outputs a line when comparison operator returns True.