Scripting Games, Sudden Death Challenge 3

Some really good text munging in this one.  And a chance for some great Perl-style obfuscated code:-)  Note that I sympathise with Richard’s opinion when it comes to production level scripts and really wouldn’t do this kind of thing in real life (at least not without lots of comments!) but this is for my own entertainment, you’ve been warned:-)

The idea here was to take the names of US presidents ($p=get-content c:\scripts\presidents.txt) and:

  1. Output the name of the president with the longest first name
  2. Output a list of letters that don’t occur as presidents initials
  3. Count the number of vowels in all the presidents’ names

So here are the three sections as PowerShell one-liners (split here to improve presentation and comprehension!):

"Longest First Name:{1} {0}" -f
	$($p|%{$l=0}{$pl=$_.split()[1].length; if ($pl -gt $l){$l=$pl; $name=$_}}{$name.Split(',')})

This keeps a record of the longest name found so far ($l=0), it then splits off the next president’s first name and gets its length ($pl=$_.split()[1].length) and compares that to current longest.  If this name is longer it saves the name (in $name) and updates the longest value accordingly.  Finally it outputs the resulting longest name, splitting at "," to give surname and firstname and uses the -f operator to swap the names around in the displayed output as required.

The next part of the answer finds letters not represented in the presidents’ initials:

	compare-object $("ABCDEFGHIJKLMNOPQRSTUVWXYZ".tochararray())|
	ft @{l="Missing Initials"; e={$_.inputobject}} -auto

This does the following:

  • Gets the firstnames and surnames by splitting each input line at ","
  • Removes any leading spaces and takes the first real character ($_.trimstart()[0])
  • Sorts the first characters (the initials) and passes on unique occurrences
  • Compares the resulting array of initials to an array of [A..Z] (thus revealing missing letters), formatting appropriately

Finally, to count vowels:

"Total vowels used: $(($p|%{$_.tochararray() -match '[aeiou]'}).count)"

This takes all the names and splits them into individual characters.  Each is compared to a list of vowels and characters matching are counted and displayed.

The complete output looks like this:

Longest First Name: Rutherford Hayes

Missing Initials

Total vowels used: 192

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s