Swift 문법 ;; stride(from:through:by:) / stride(from:to:by:)
오늘 백준 알고리즘 문제 2775: 부녀회장이 될테야
를 풀다가 stride에 대해서 알게 되었다.
https://www.acmicpc.net/problem/2775
2775번: 부녀회장이 될테야
첫 번째 줄에 Test case의 수 T가 주어진다. 그리고 각각의 케이스마다 입력으로 첫 번째 줄에 정수 k, 두 번째 줄에 정수 n이 주어진다
www.acmicpc.net
아파트에는 0층부터 있고 각층에는 1호부터 있으며, 0층의 i호에는 i명이 산다.
1 ≤ 층, 호 ≤ 14 라는 조건이 있어서
0층에 초기값을
var apt = Array(repeating: Array(repeating: 0, count: 14), count: 15) apt[0] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
이렇게 주려고 했다.
범위가 작아서 다행이지 만약에 <= 200 이라도 되었으면
손가락이 나갈 수도 있는 노릇.
찾아보니 특정 숫자만큼 증가시킬 수 있는 stride 함수가 있었다!!
/* 기존 var apt = Array(repeating: Array(repeating: 0, count: 14), count: 15) apt[0] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14] */ //stride -through 사용 var apt = Array(repeating: [Int](stride(from: 1, through: 14, by: 1)), count: 15) //stride -to 사용 var apt = Array(repeating: [Int](stride(from: 1, to: 15, by: 1)), count: 15)
이렇게 바꿀 수 있다.
stride
stride 메서드를 통해서 특정 범위의 숫자를 특정 숫자만큼 증가시킨 값을 반환할 수 있다고 했다.
stride에 대해서 알아보자!
stride 는 보폭(걸음) 등의 의미가 있다.
by에 보폭(증가시킬 값)을 넣으면 해당 보폭만큼 증가시킨 값들을 반환해주는 것이다.
stride 메서드는
stride(from:through:by) / stride(from:to:by) 가 있다.
전자는 from <= n <= through 까지의 범위를 가지고,
후자는 from <= n < to 까지의 범위를 가진다.
단순하다.
stride(from:through:by:)

위에서 언급했듯이
설명을 읽어보면 including, an end value
즉, 끝 값(through)을 포함해서 특정 수(by)만큼 stepping하는 sequence를 반환한다고 한다.
예시>
5부터 시작해서 0까지 -1씩 stepping한 값을 출력하고자 한다.
for i in (stride(from: 5, through: 0, by: -1)) {
print(i)
}
출력)
5
4
3
2
1
0
4부터 10까지 4의 배수를 출력하고자 한다.
for i in (stride(from: 4, through: 10, by: 4)) {
print(i)
}
출력)
4
8
stride(from:to:by:)

stride(from:through:by:)와 달리
not including an end value라고 쓰여져 있다.
예시>
5부터 시작해서 0까지 -1씩 stepping한 값을 출력하고자 한다.
for i in (stride(from: 5, to: 0, by: -1)) {
print(i)
}
출력)
5
4
3
2
1
위의 stride(from :5, through: 0, by:-1) 출력 값과 달리
0을 포함하지 않는다.
5 >= n > 0 까지 -1 씩한 값을 반환한다는 것!
특이 사항 (?)

from, through(to)값 설정을 잘못 해주었을 경우
빈 배열을 반환하고 크래시를 발생시키지 않는다.
>> 알고리즘 문제 풀이 시 유용할 듯 하다.
인덱스 설정을 잘못해주어서 런타임 에러가 나는 상황을 방지할 수 있겠다!! 🍯
예시>
var arr = [Int](stride(from: 0, through: 5, by: -1))
출력)
[] //빈 배열
위 코드는 0부터 5 사이의 값을 0부터 -1씩 감소하도록 하는 값을 반환하라고 했는데,
from, through 값 설정을 잘못 해준 것이다.
그리하여 빈 배열을 반환한다.
var arr = [Int](stride(from: 1, through: 5, by: 6))
출력)
[1]
위 코드는 1부터 5 사이의 값을 1부터 6씩 증가하도록 하는 값을 반환했으니 1이 출력된다.
참고
https://developer.apple.com/documentation/swift/stride(from:through:by:)
stride(from:through:by:) | Apple Developer Documentation
Returns a sequence from a starting value toward, and possibly including, an end value, stepping by the specified amount.
developer.apple.com
https://developer.apple.com/documentation/swift/stride(from:through:by:)
stride(from:through:by:) | Apple Developer Documentation
Returns a sequence from a starting value toward, and possibly including, an end value, stepping by the specified amount.
developer.apple.com