관리 메뉴

나만을 위한 블로그

[Algorithm] 프로그래머스 - n개 간격의 원소들 (Kotlin) 본문

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

[Algorithm] 프로그래머스 - n개 간격의 원소들 (Kotlin)

참깨빵위에참깨빵 2024. 4. 20. 21:06
728x90
반응형
정수 리스트 num_list, 정수 n이 주어질 때, num_list의 첫 번째 원소부터 마지막 원소까지 n개 간격으로 저장된 원소들을 차례로 담은 리스트를 리턴하는 함수를 완성하라

 

 

주먹구구식으로 풀면 아래와 같다.

 

class Solution {
    fun solution(numList: IntArray, n: Int): IntArray {
        val list = mutableListOf<Int>()
        for (i in numList.indices step n) {
            list.add(numList[i])
        }

        return list.toIntArray()
    }
}

 

위 코드는 filterIndexed를 쓰면 더 간결해진다.

 

class Solution {
    fun solution(numList: IntArray, n: Int): IntArray =
        numList.filterIndexed { index, _ -> index % n == 0 }.toIntArray()
}

 

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/filter-indexed.html

 

filterIndexed - Kotlin Programming Language

 

kotlinlang.org

주어진 술어와 일치하는 요소만 포함된 리스트를 리턴한다

 

step n 부분이 filterIndexed 안의 index % n == 0 으로 바뀌었다고 보면 된다.

반응형
Comments