ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 단어 정렬
    백준 2023. 7. 31. 12:03
    728x90

    다 풀어놓고 어이없는 곳에서 실수가 있었다.

    문제

    알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.

    1. 길이가 짧은 것부터
    2. 길이가 같으면 사전 순으로

    단, 중복된 단어는 하나만 남기고 제거해야 한다.

    입력

    첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.

    출력

    조건에 따라 정렬하여 단어들을 출력한다.

    예제 입력 1

    13
    but
    i
    wont
    hesitate
    no
    more
    no
    more
    it
    cannot
    wait
    im
    yours
    
    

    예제 출력 1

    i
    im
    it
    no
    but
    more
    wait
    wont
    yours
    cannot
    hesitate
    

     

    풀이


    다 풀어놓고 엄한 곳에서 삽질하고있었다.

    정렬과 중복제거를 통해 정렬은 하지만 계속해서 빈 배열 요소 하나가 생기는 문제가 있었다

     

    오답 코드

    import java.io.InputStreamReader
    import java.io.BufferedReader
    fun main(){
        val sb = StringBuilder()
        var i:Int=0
        var count= readln().toInt()
        val emptyArray: Array<String> = Array(count) { "" }
        while (i<count){
            val word = readln().toString()
            if (!emptyArray.contains(word)) {
                emptyArray[i]=word
                i++
            }else{
                i=i
                count--
            }
        }
    
        emptyArray.sortWith(compareBy({it.toString().length},{it.toString()}))
        val distinctArray = emptyArray.distinct().toTypedArray()
    
        for (i in 0 until distinctArray.size) {
            print(distinctArray[i])
            if (i != distinctArray.size - 1) {
                print("\\n")
            }
        }
    
    }
    

    sortWith를 통해 정렬을 하고 val distinctArray = emptyArray.distinct().toTypedArray()를 통해 중복제거하여 새로운 문자열에 할당했는데…

    if (!emptyArray.contains(word)) {
                emptyArray[i]=word
                i++
            }else{
                i=i
                count--
            }
    

    이 코드를 통해 다시 중복제거를 하려다 문제가 생긴 것이다

    if (!emptyArray.contains(word))
    

    위 조건문 때문에 최초 빈배열이 조건문에 진입하지 못한채 공백이나 null이 할당된 그대로 배열의 다음 요소에 접근하는 문제였다.

    애초에 필요없는 조건문이니 해당 조건문을 코드애서 삭제하자 문제가 해결 되었다.

     

    정답코드


    fun main(){
    
        var i:Int=0
        var count= readln().toInt()
        val emptyArray: Array<String> = Array(count) { "" }
        while (i<count){
            val word = readLine().toString()
                emptyArray[i]=word
                i++
        }
    
        emptyArray.sortWith(compareBy({it.toString().length},{it.toString()}))
        val distinctArray = emptyArray.distinct().toTypedArray()
    
        for (i in 0 until distinctArray.size) {
            print(distinctArray[i])
            if (i != distinctArray.size - 1) {
                print("\\n")
            }
        }
    
    }
    

    sortWith를 통해 정렬하고 .distinct()를 통해 중복된 단어를 하나만 남기고 제거하였다.

    출력형식을 맞추기위해 마지막 줄 바꿈은 생략해야했다. 따라서 println()대신

    for (i in 0 until distinctArray.size) {
            print(distinctArray[i])
            if (i != distinctArray.size - 1) {
                print("\\n")
            }
        }
    

    위코드 처럼 반복문안에 조건문을 추가해 배열의 마지막 요소에선 줄 바꿈을 하지않도록 하였다.

    '백준' 카테고리의 다른 글

    막대기  (0) 2023.08.01
    개수 세기  (0) 2023.08.01
    영화감독 숌  (0) 2023.07.31
    2007년  (0) 2023.07.31
    수 정렬하기3  (0) 2023.07.31
Designed by Tistory.