Skip to content

Instantly share code, notes, and snippets.

@JFFail
Created June 30, 2015 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JFFail/073cd38b427d1be24668 to your computer and use it in GitHub Desktop.
Save JFFail/073cd38b427d1be24668 to your computer and use it in GitHub Desktop.
Solution to Reddit Daily Programmer #220 - Mangle Sentence
#Solution to Reddit Daily Programmer #220
#http://www.reddit.com/r/dailyprogrammer/comments/3aqvjn/20150622_challenge_220_easy_mangling_sentences/
#Original input.
#$sentence = "This challenge doesn't seem so hard."
#$sentence = "Eye of Newt, and Toe of Frog, Wool of Bat, and Tongue of Dog."
#$sentence = "For a charm of powerful trouble, like a hell-broth boil and bubble."
$sentence = "Adder's fork, and Blind-worm's sting, Lizard's leg, and Howlet's wing."
#Make it into an array of words.
$sentenceArray = $sentence.Split(" ")
#Loop through it.
foreach($word in $sentenceArray)
{
#Test each word to see if the first letter is a capital.
$isCapital = $false
if(($word[0].ToString()).ToUpper() -ceq $word[0].ToString())
{
$isCapital = $true
}
#Turn the word into an array.
$charArray = $word.ToCharArray()
#Initialize some variables to store the string very and a hash for special characters.
$strArray = @()
$specialHash = @{}
#Make it an array of single item strings rather than characters to facilitate sorting.
$counter = 0
foreach($character in $charArray)
{
$strArray += ($character.ToString()).ToLower()
#Check to see if the value does or does not match a special character.
if(-not($strArray[$counter] -match "\w"))
{
#If it does, throw that into the hash, with the index in the word as the Key.
$specialHash[$counter] = $strArray[$counter]
}
#Keep the counter incremented so we know the index of special characters.
$counter++
}
#Sort the array of single character strings.
$strArray = $strArray | Sort-Object
#Reset the counter.
$counter = 0
$firstLetter = $true
$highest = 0
#Loop through the array of single character strings and print each one.
foreach($letter in $strArray)
{
#Only act on letters since special characters get auto-sorted to the front.
if($letter -match "\w")
{
#Now proceed with printing each character either upper or lowercase.
if($isCapital -and $firstLetter)
{
Write-Host $letter.ToUpper() -NoNewline
$firstLetter = $false
}
else
{
Write-Host $letter -NoNewline
}
#See if we need a special character in here.
if($specialHash.ContainsKey($counter-($specialHash.Count - 1)))
{
Write-Host $specialHash[$counter-($specialHash.Count - 1)] -NoNewline
#Bump the counter to make up for lost time because we'll insert 2 characters.
$counter++
}
}
$counter++
}
#Write a space between words.
Write-Host " " -NoNewline
}
#Final CRLF.
Write-Host ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment