Kotlin/Kotlin 알고리즘

백준 20920번 영단어 암기는 괴로워 Kotlin 구현해보기

kimc 2023. 3. 12. 00:36

```

백준 20920번 영단어 암기는 괴로워  Kotlin 구현해 보기

```

Kimc Kotlin Study

이번 글을 통해 배워갈 내용

  1. 백준 20920번 영단어 암기는 괴로워  Kotlin 구현해 보기

https://www.acmicpc.net/problem/20920

 

20920번: 영단어 암기는 괴로워

첫째 줄에는 영어 지문에 나오는 단어의 개수 $N$과 외울 단어의 길이 기준이 되는 $M$이 공백으로 구분되어 주어진다. ($1 \leq N \leq 100\,000$, $1 \leq M \leq 10$) 둘째 줄부터 $N+1$번째 줄까지 외울 단

www.acmicpc.net

 

 

백준 20920번 영단어 암기는 괴로워은

난이도 실버 등급의 문제로서

 

주어진 영어단어들을 정렬해서

자주 나오는 단어일수록 앞에 배치한고.
해당 단어의 길이가 길수록 앞에 배치한고.
알파벳 사전 순으로 앞에 있는 단어일수록 앞에 배치하며

특정 길이 미만은 버리는 문제입니다.

 

 


30분 정도 위에 링크를 방문하셔서 풀어보시고

안 풀리시는 경우에만 아래 해답을 봐주시면 감사하겠습니다.


맵을 가지고 카운팅을 한 다음

커스텀 비교연산을 하게 해 주고

순서에 맞게 출력하였습니다.

 

 

import java.util.stream.Collectors

fun main() {
    val inputDto = getInput()
    print(solution(inputDto))
}

fun getInput(): InputDto {
    val inputLine1 = readln().split(" ").map { it.toInt() }
    val wordCnt = inputLine1[0]
    val wordMinLen = inputLine1[1]

    val words = emptyList<String>().toMutableList()
    for (i in 1..wordCnt) {
        words.add(readln())
    }
    return InputDto(words, wordMinLen)
}

data class InputDto(
    val words: List<String>,
    val minLength: Int
)

fun solution(dto: InputDto): String {
    return findCustomSort(dto.words, dto.minLength)
}

//자주 나오는 단어일수록 앞에 배치한다.
//해당 단어의 길이가 길수록 앞에 배치한다.
//알파벳 사전 순으로 앞에 있는 단어일수록 앞에 배치한다
private val customComparator = Comparator<MutableMap.MutableEntry<String, Int>> { a, b ->
    when {
        (a.value > b.value) -> -1
        (a.value < b.value) -> 1
        else -> when {
            (a.key.length > b.key.length) -> -1
            (a.key.length < b.key.length) -> 1
            else -> when {
                (a.key > b.key) -> 1
                (a.key < b.key) -> -1
                else -> 0
            }
        }
    }
}

fun findCustomSort(words: List<String>, minLength: Int): String {
    val map = emptyMap<String, Int>().toMutableMap()
    words.forEach { word ->
        run {
            if (word.length >= minLength) {
                if (map[word] == null) {
                    map[word] = 1
                } else {
                    map[word] = map[word]!! + 1
                }
            }
        }
    }
    return map.entries.stream()
        .sorted(customComparator)
        .map { m -> m.key }.collect(Collectors.joining("\n"))

}

// https://codemasterkimc.tistory.com/

 

테스트

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test

internal class MainKtTest {

    @Test
    fun test() {
        assertEquals(
            "sand\n" +
                    "apple\n" +
                    "append",
            solution(
                InputDto(
                    listOf(
                        "apple",
                        "ant",
                        "sand",
                        "apple",
                        "append",
                        "sand",
                        "sand",
                    ), 4
                )
            )
        )
        assertEquals(
            "a\n" +
                    "b\n" +
                    "c",
            solution(
                InputDto(
                    listOf(
                        "a",
                        "a",
                        "a",
                        "b",
                        "b",
                        "b",
                        "c",
                    ), 1
                )
            )
        )
        assertEquals(
            "bb\n" +
                    "a\n" +
                    "c",
            solution(
                InputDto(
                    listOf(
                        "a",
                        "a",
                        "a",
                        "bb",
                        "bb",
                        "bb",
                        "c",
                    ), 1
                )
            )
        )
    }
}

 

 

 

읽어주셔서 감사합니다

 

무엇인가 얻어가셨기를 바라며

 

오늘도 즐거운 코딩 하시길 바랍니다 ~ :)

 


 

728x90