🍏/Swift
[Swift Algorithms] chunks(ofCount:)
eungding
2021. 9. 28. 12:09
728x90
반응형
swift-algorithms 패키지 / swift-collections 패키지 가 등장하면서
(참고: WWDC 2021 Meet the Swift Algorithms and Collections packages)
기존에 extension으로 만들어서 쓰고 있었던 chuck 메소드를 패키지 안의 메소드로 교체할 수 있게 되었습니다!
[ as is ]
import Foundation
extension Array {
// https://www.hackingwithswift.com/example-code/language/how-to-split-an-array-into-chunks
public func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}
[ to be ]
우선 swift-algorithms 패키지 를 SPM으로 추가해주셔야합니다.
import Foundation
import Algorithms
extension Array {
public func chunked(into size: Int) -> [[Element]] {
return self.chunks(ofCount: size).map { Array($0) }
}
}
[ 테스트 ]
let array = [1, 2, 3, 4, 5, 6, 7, 8]
// as is
print(array.chunked(into: 3))
// [[1, 2, 3], [4, 5, 6], [7, 8]]
// to be
print(array.chunks(ofCount: 3))
// ChunksOfCountCollection<Array<Int>>(base: [1, 2, 3, 4, 5, 6, 7, 8], chunkCount: 3, endOfFirstChunk: 3)
print(array.chunks(ofCount: 3).map { Array($0)})
// [[1, 2, 3], [4, 5, 6], [7, 8]]
[ Complexity ]
코드에 Complexity가 저렇게 적혀있는데 어떻게 읽어야할 지 모르겠네요,,,,
주석 때문에 O(*n*) 로 된 것 같고
옵션 키 눌러보면 O(n) 이라고 나옵니다!!
반응형