Skip to content

Instantly share code, notes, and snippets.

@rchatley
Created June 10, 2020 16:25
Show Gist options
  • Save rchatley/1e407ed1ba96c64d74d5e34f1477e95d to your computer and use it in GitHub Desktop.
Save rchatley/1e407ed1ba96c64d74d5e34f1477e95d to your computer and use it in GitHub Desktop.
object PigLatin {
fun translate(phrase: String): String = phrase.split(" ").joinToString(" ", transform = ::translateWord)
private fun translateWord(word: String): String =
when {
word.startsWith(vowel) -> word + "ay"
word.startsWith("xr") -> word + "ay"
word.startsWith("yt") -> word + "ay"
word.startsWith("ch") -> word.drop(2) + "chay"
word.startsWith("qu") -> word.drop(2) + "quay"
word.startsWith("thr") -> word.drop(3) + "thray"
word.startsWith("th") -> word.drop(2) + "thay"
word.startsWith("sch") -> word.drop(3) + "schay"
word.startsWith(anything, "qu") -> word.drop(3) + word[0] + "quay"
word.startsWith(consonant, "y") && word.length == 2 -> "y" + word[0] + "ay"
word.startsWith(consonant, consonant, "y") -> word.drop(2) + word.substring(0, 2) + "ay"
word.startsWith(consonant) -> word.drop(1) + word[0] + "ay"
else -> word
}
private val vowel = setOf('a', 'e', 'i', 'o', 'u')
private val anything = ('a'..'z').toSet()
private val consonant = anything - vowel
private fun String.startsWith(firstLetter: Set<Char>, followedBy: String = ""): Boolean =
this[0] in firstLetter && drop(1).startsWith(followedBy)
private fun String.startsWith(firstLetter: Set<Char>, secondLetter: Set<Char>, followedBy: String = ""): Boolean =
this[0] in firstLetter && this[1] in secondLetter && drop(2).startsWith(followedBy)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment