Last active
October 29, 2017 04:12
-
-
Save atonamy/97652c3da6427b1b7d2eaf1be04c79b0 to your computer and use it in GitHub Desktop.
Solution on Kotlin for https://www.facebook.com/Engineering/videos/10152735777427200/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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