Skip to content

Instantly share code, notes, and snippets.

@hikaMaeng
Created August 28, 2025 16:00
Show Gist options
  • Select an option

  • Save hikaMaeng/1424cd9b468c09c1ad54be9e812544b4 to your computer and use it in GitHub Desktop.

Select an option

Save hikaMaeng/1424cd9b468c09c1ad54be9e812544b4 to your computer and use it in GitHub Desktop.

Revisions

  1. hikaMaeng created this gist Aug 28, 2025.
    57 changes: 57 additions & 0 deletions cco99p2.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    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)
    }
    }