Last active
June 19, 2023 22:55
-
-
Save patxibocos/8e3402ef8f00b6655e3c54a2e2866a95 to your computer and use it in GitHub Desktop.
AnagramCalculator.kt
This file contains hidden or 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
| 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