-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroger_federer.kt
More file actions
49 lines (34 loc) · 1.3 KB
/
Copy pathroger_federer.kt
File metadata and controls
49 lines (34 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package w34_roger_federer
data class Group(val token: String, val occurrences: Int)
private fun findGroupsAndCounts(input: String, size: Int): List<Group> {
val groups = mutableListOf<Group>()
for (i in 2..size) {
val counts = input
.windowed(i, 1) // Sliding window of size i
.groupingBy { it } // Group by the token
.eachCount() // And count the tokens
groups.addAll(counts.map { Group(it.key, it.value) })
}
return groups
}
private fun findMostOccurringGroup(input: String): Group? {
val groupsCounts = findGroupsAndCounts(input, input.length / 2)
return groupsCounts.maxWithOrNull(
compareBy<Group> { it.occurrences }
.thenBy { it.token }
)
}
private fun String.trimmed() = this
.filter { it.isLetterOrDigit() }
.lowercase()
fun main() {
val string = "Roger Federer"
val mostOccurring = findMostOccurringGroup(string.trimmed())
if (mostOccurring != null && mostOccurring.occurrences > 1) {
val percentage =
(mostOccurring.occurrences.toDouble() * mostOccurring.token.length / string.trimmed().length * 100).toInt()
println("$percentage% of $string is \"${mostOccurring.token}\"")
} else {
println("$string doesn't have any repeating groups.")
}
}