포스트

56. 리스트 자르기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import Foundation

func solution(_ n:Int, _ slicer:[Int], _ num_list:[Int]) -> [Int] {
    
    var answer : [Int] = []
    
    switch n {
        case 1 :
            answer = Array(num_list[0...slicer[1]])
        case 2 :
            answer = Array(num_list[slicer[0]...])
        case 3 :
            answer = Array(num_list[slicer[0]...slicer[1]])
        case 4 :
            answer = stride(from:slicer[0], to:slicer[1]+1, by:slicer[2]).map{num_list[$0]}
    
        default : answer = []
    }

    return answer
}

이렇게 한 이유

switch case를 이용해 1,2,3,4 일때의 조건을 나누었다.

Array로 감싼이유는 array를 감싸지 않도 돌리니 type 에러가 났다.

[]를 통해 슬라이싱을 할경우 슬라이싱을 한 배열은 ArrySlice<>으로 되면서 데이터 타입 에러가 났다.

그래서 Array로 감싸서 데이텨형을 맞추었다.

n=4일때 간격을 두고 슬라이싱을 해야해서 검색을 해야했다. stride를 통해서 할수 있다는 것을 알았고, 그다음 map을 써서 배열로 만들어야하는것을 알게 되었다.

출력결과 4번에서 2,4,6이 정답인데 6이 안나와서 +1을 하여 슬라이싱 범위를 한칸 더 주었다.

from: to from: through 의 표현에 차이가 있었다.

to를 하게되면 해당 인덱스를 포함하지 않는다.

through를 하게되면 해다 인덱스를 포함하게된다.

다른 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import Foundation

func solution(_ n:Int, _ slicer:[Int], _ num_list:[Int]) -> [Int] {
    
    var answer : [Int] = []
    
    switch n {
        case 1 :
            answer = Array(num_list[0...slicer[1]])
        case 2 :
            answer = Array(num_list[slicer[0]...])
        case 3 :
            answer = Array(num_list[slicer[0]...slicer[1]])
        case 4 :
            answer = stride(from:slicer[0], through:slicer[1], by:slicer[2]).map{num_list[$0]}
    
        default : answer = []
    }
    
    print(answer)
    
    return answer
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.