Skip to content

Instantly share code, notes, and snippets.

@caroltr
Last active May 4, 2020 02:05
Show Gist options
  • Save caroltr/c4a180e1151aa49c06129ce4d3663918 to your computer and use it in GitHub Desktop.
Save caroltr/c4a180e1151aa49c06129ce4d3663918 to your computer and use it in GitHub Desktop.
Kotlin Word Count Challenge
As the purpose is to provide insights about messages entered by a real person, it was assumed that any symbol that doesn't belong to the alphabet or to the numerical system doesn't give meaningful information. So, this filter was included in the solution.
Full project can be found here: https://github.com/caroltr/word-count-challenge
fun Map<String, Int>.orderDescendingByValue(): Map<String, Int> {
return this.toList().sortedByDescending { it.second }.toMap()
}
fun main() {
val controller = MessageController()
val input = listOf("I love summer.", "My family loves to hike in the summer.")
val frequency = controller.countWords(input)
val frequencyOrdered = frequency?.orderDescendingByValue()
print(frequencyOrdered?.toList())
}
class MessageController {
fun countWords(messages: List<String>): Map<String, Int>? {
return if (messages.isEmpty()) null else {
val allMessages: String = messages.joinToString(" ")
allMessages.split(" ")
.groupingBy { getPlainWord(it) }
.eachCount()
}
}
private fun getPlainWord(word: String): String {
return word.toLowerCase().filter { it.isLetterOrDigit() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment