Created
August 28, 2025 16:00
-
-
Save hikaMaeng/1424cd9b468c09c1ad54be9e812544b4 to your computer and use it in GitHub Desktop.
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
| package week3 | |
| fun checkMK(v:String):Pair<Int, Int>{ | |
| val split = v.split(" ") | |
| if(split.size != 2 || split[0].isEmpty() || split[1].isEmpty()) throw Exception("invalid mk-$v-") | |
| val m = split[0].toIntOrNull() ?: throw IllegalArgumentException("invalid int m") | |
| if(m !in 1.. 1000) throw Throwable("out of range 1..1000 m: $m") | |
| val k = split[1].toIntOrNull() ?: throw IllegalArgumentException("invalid int k") | |
| return m to k | |
| } | |
| fun cco99p2() { | |
| val input = System.`in`.bufferedReader() | |
| val datasets = input.readLine().toIntOrNull() ?: throw IllegalArgumentException("invalid int datasets") | |
| val output = mutableListOf<String>() | |
| var i = 1 | |
| while(i in 1..datasets){ | |
| val mk = input.readLine() | |
| val (m, k) = checkMK(mk) | |
| if(i != 1) output.add("") | |
| when(k){ | |
| 1 -> output.add("1st most common word(s):") | |
| 2 -> output.add("2nd most common word(s):") | |
| 3 -> output.add("3rd most common word(s):") | |
| else -> output.add("${k}th most common word(s):") | |
| } | |
| val words = mutableMapOf<String, Int>() | |
| var j = 0 | |
| while(j < m){ | |
| val word = input.readLine().lowercase() | |
| if(word.length > 20) throw Throwable("out of 20 length: $word") | |
| words[word] = words.getOrPut(word){0} + 1 | |
| j++ | |
| } | |
| val sort = words.entries.sortedByDescending{it.value} | |
| j = 0 | |
| var nth = 1 | |
| var prev = sort[0].value | |
| while(j < sort.size){ | |
| val (key, value) = sort[j] | |
| if(value < prev){ | |
| if(nth == k) break | |
| nth++ | |
| prev = value | |
| } | |
| if(nth == k) output.add(key) | |
| j++ | |
| } | |
| i++ | |
| } | |
| for(o in output) { | |
| println(o) | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment