Skip to content

Commit 6fa3ca7

Browse files
authored
Add Duplicate Character Counter in Kotlin (#5050)
* Implemented duplicate character counter * Added missing output message
1 parent 9fef382 commit 6fa3ca7

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import kotlin.system.exitProcess
2+
3+
fun main(args: Array<String>) {
4+
val phrase: String = errorChecking(args)
5+
val counts = duplicateCharacterCount(phrase)
6+
outputMap(counts)
7+
}
8+
9+
fun usageError() {
10+
println("Usage: please provide a string")
11+
}
12+
13+
fun errorChecking(args: Array<String>): String {
14+
if (args.size == 0 || args[0] == "") {
15+
usageError()
16+
exitProcess(1)
17+
}
18+
return args[0]
19+
}
20+
21+
fun duplicateCharacterCount(phrase: String): Map<Char, Int> {
22+
val counts: Map<Char, Int> = phrase.groupingBy { it }.eachCount()
23+
return counts.filter { it.value > 1 }
24+
}
25+
26+
fun outputMap(counts: Map<Char, Int>) {
27+
if (counts.size > 0) {
28+
for (pair in counts) {
29+
println("${pair.key}: ${pair.value}")
30+
}
31+
} else {
32+
println("No duplicate characters")
33+
}
34+
}

0 commit comments

Comments
 (0)