Skip to content

Instantly share code, notes, and snippets.

@patxibocos
Last active June 19, 2023 22:55
Show Gist options
  • Select an option

  • Save patxibocos/8e3402ef8f00b6655e3c54a2e2866a95 to your computer and use it in GitHub Desktop.

Select an option

Save patxibocos/8e3402ef8f00b6655e3c54a2e2866a95 to your computer and use it in GitHub Desktop.
AnagramCalculator.kt
class AnagramCalculator(private val wordsDictionary: Collection<String>) {
private fun findAnagrams(
word: String,
dictionary: Collection<String>,
acc: String = "",
): Collection<String> {
if (word.isEmpty() || dictionary.isEmpty()) {
return dictionary
}
val wordsByLetter = dictionary.groupBy { it[acc.length] }
return word.toSet().flatMap { c ->
val filteredDict = wordsByLetter[c] ?: return@flatMap emptyList()
val index = word.indexOf(c)
findAnagrams(word.removeRange(index, index + 1), filteredDict, acc + c)
}
}
fun listAnagrams(word: String): Collection<String> {
val sameLengthWords = wordsDictionary.filter { it.length == word.length }
if (sameLengthWords.isEmpty()) {
return emptyList()
}
return findAnagrams(word.lowercase(), sameLengthWords) - word
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment