Skip to content

Instantly share code, notes, and snippets.

@gatorcse
Last active August 29, 2015 14:27
Show Gist options
  • Save gatorcse/4bc5e6b6b1c53bdbf7a0 to your computer and use it in GitHub Desktop.
Save gatorcse/4bc5e6b6b1c53bdbf7a0 to your computer and use it in GitHub Desktop.
Solves reddit challenge 220
package tlo.reddit
object SentenceMangle {
val sampleInputs = Seq(
"This challenge doesn't seem so hard.",
"There are more things between heaven and earth, Horatio, than are dreamt of in your philosophy."
)
val challengeInputs = Seq(
"Eye of Newt, and Toe of Frog, Wool of Bat, and Tongue of Dog.",
"Adder's fork, and Blind-worm's sting, Lizard's leg, and Howlet's wing.",
"For a charm of powerful trouble, like a hell-broth boil and bubble."
)
def main(args: Array[String]) {
sampleInputs.zipWithIndex.foreach { case (sentence, index) =>
println(s"==== Sentence $index ====")
println(s"Input: ${sentence + 1}")
println(s"Output: ${mangle(sentence)}")
println("")
}
}
def mangle(original: String): String = {
original.split(' ')
.map(sortWord)
.mkString(" ")
}
def sortWord(word: String): String = {
val sortedLetters = word.toLowerCase.filter(_.isLetter).sorted.toList
val startingState = (sortedLetters, "")
// Uses a poor man's Iteratee to do the sort. If a letter, we pop a letter off the front of sorted letter list, and
// append it to the word accumulator. The next state is the remainder of the sorted letters, and the accumulated
// sentence so far.
val newWord = word.foldLeft(startingState) {
case ((letters, acc), thisChar) =>
thisChar.isLetter match {
case true => (letters.tail, acc + letters.head)
case false => (letters, acc + thisChar)
}
}._2
if (word(0).isUpper) newWord.capitalize else newWord
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment