Skip to content

Instantly share code, notes, and snippets.

@atonamy
Last active October 29, 2017 04:12
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 atonamy/97652c3da6427b1b7d2eaf1be04c79b0 to your computer and use it in GitHub Desktop.
Save atonamy/97652c3da6427b1b7d2eaf1be04c79b0 to your computer and use it in GitHub Desktop.
package NearbyWords
import kotlin.collections.HashSet
fun main(args : Array<String>) {
println(nearbyWords("gi"))
}
fun nearbyWords(word: String): Set<String> {
val permutations = getAllWordPermutations(word, 0)
return permutations.filter { isWord(it) }.toSet()
}
fun getAllWordPermutations(word: String, index: Int): Set<String> {
if(index >= word.length)
return setOf("")
val sub_words = getAllWordPermutations(word, index+1)
val nearby_letters = getNearbyChar(word[index])
val permutations = HashSet<String>()
sub_words.forEach { sub_word ->
nearby_letters.forEach {
permutations.add("$it$sub_word")
}
}
return permutations
}
//simulating helper function
fun getNearbyChar(char: Char): Set<Char> {
return HashSet<Char>().apply {
when(char) {
'g' -> addAll(arrayListOf('g', 'h', 'f'))
'i' -> addAll(arrayListOf('i', 'o', 'k'))
}
}
}
//simulating helper function
fun isWord(word: String) : Boolean {
return (word == "go" || word == "hi")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment