본문 바로가기
코딩테스트

[프로그래머스] 암호 해독

by liz_devel 2025. 12. 21.

🗒 문제


📝 나의 문제풀이

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

📝 다른 사람의 문제 풀이

다른 사람의 문제 풀이는 좋아요 수가 높거나 많은 사람들이 푼 방법 기준으로 첨부하였습니다.

class Solution {
    fun solution(cipher: String, code: Int) = cipher.indices.filter { index -> index % code == code - 1 }.map { cipher[it] }.joinToString("")
}

🖊 문제 풀이 시 알면 좋을 것

 

filterIndexed — “인덱스 기준 필터링”

fun <T> Iterable<T>.filterIndexed(
    predicate: (index: Int, T) -> Boolean
): List<T>


filterIndexed { index, value -> Boolean }

 

  • index : 0부터 시작하는 위치
  • value : 해당 위치의 값
  • 조건이 true인 요소만 남김

예시

"abcdef".filterIndexed { i, _ -> i % 2 == 0 }

 

결과: "ace"

 

 

indices — 인덱스만 필요할 때

val s = "abc"
println(s.indices)

즉, 0..2 // 0부터 2까지 전부 포함하는 범위

 

  • 0..length-1 범위
  • 값 말고 위치만 필요할 때

 

반응형