관리 메뉴

나만을 위한 블로그

[Algorithm] 프로그래머스 - 암호 해독 (Kotlin) 본문

알고리즘 문제 풀이/프로그래머스

[Algorithm] 프로그래머스 - 암호 해독 (Kotlin)

참깨빵위에참깨빵_ 2023. 1. 4. 18:40
728x90
반응형
전쟁 중 적군이 아래와 같은 암호 체계를 쓴다는 걸 알아냈다
- 암호화된 문자열 cipher를 주고받는다

- 그 문자열에서 code의 배수 번째 글자만 진짜 암호다

문자열 cipher, 정수 code가 매개변수로 주어질 때 해독된 암호 문자열을 리턴하는 solution()을 완성하라

 

 

아래는 주먹구구식으로 푼 코드다.

 

class Solution {
    fun solution(cipher: String, code: Int): String {
        val s = StringBuilder()
        val list = cipher.split("")
        for (i in 1 until list.size) {
            if (i % code == 0) {
                s.append(list[i])
            }
        }
        
        return s.toString()
    }
}

 

아래는 위 코드를 좀 더 간략하게 줄여보려고 시도한 결과다.

 

class Solution {
    fun solution(cipher: String, code: Int): String = cipher.split("").toList()
        .mapIndexed { index, s -> if (index % code == 0) s else "" }
        .joinToString("")
}

 

다른 사람의 풀이를 참고하니 filterIndexed {}를 써서 풀 수도 있었다.

 

class Solution {
    fun solution(cipher: String, code: Int): String = cipher.filterIndexed{ i, _ -> (i + 1) % code == 0}
}

 

반응형
Comments