From 505b57369fb7d3d2eafd7d67f3366f83ac640f70 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Fri, 8 Jan 2021 00:07:46 -0300 Subject: [PATCH 01/10] [Chunked] Implementing chunked collection by a given count --- Sources/Algorithms/Chunked.swift | 174 +++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift index 1dc35bb..93296dd 100644 --- a/Sources/Algorithms/Chunked.swift +++ b/Sources/Algorithms/Chunked.swift @@ -246,3 +246,177 @@ extension Collection { try chunked(on: projection, by: ==) } } + +//===----------------------------------------------------------------------===// +// chunks(ofCount:) +//===----------------------------------------------------------------------===// + +/// A collection that presents the elements of its base collection +/// in `SubSequence` chunks of any given count. +/// +/// A `ChunkedByCount` is a lazy view on the base Collection, but it does not implicitly confer +/// laziness on algorithms applied to its result. In other words, for ordinary collections `c`: +/// +/// * `c.chunks(ofCount: 3)` does not create new storage +/// * `c.chunks(ofCount: 3).map(f)` maps eagerly and returns a new array +/// * `c.lazy.chunks(ofCount: 3).map(f)` maps lazily and returns a `LazyMapCollection` +public struct ChunkedByCount { + + public typealias Element = Base.SubSequence + + @usableFromInline + internal let base: Base + + @usableFromInline + internal let chunkCount: Int + + @usableFromInline + internal var computedStartIndex: Index + + /// Creates a view instance that presents the elements of `base` + /// in `SubSequence` chunks of the given count. + /// + /// - Complexity: O(n) + @inlinable + internal init(_base: Base, _chunkCount: Int) { + self.base = _base + self.chunkCount = _chunkCount + + // Compute the start index upfront in order to make + // start index a O(1) lookup. + let baseEnd = _base.index( + _base.startIndex, offsetBy: _chunkCount, + limitedBy: _base.endIndex + ) ?? _base.endIndex + + self.computedStartIndex = + Index(_baseRange: _base.startIndex.. + + @usableFromInline + internal init(_baseRange: Range) { + self.baseRange = _baseRange + } + } + + /// - Complexity: O(n) + public var startIndex: Index { computedStartIndex } + public var endIndex: Index { + Index(_baseRange: base.endIndex.. Element { + base[i.baseRange] + } + + @inlinable + public func index(after i: Index) -> Index { + let baseIdx = base.index( + i.baseRange.upperBound, offsetBy: chunkCount, + limitedBy: base.endIndex + ) ?? base.endIndex + return Index(_baseRange: i.baseRange.upperBound.. Bool { + lhs.baseRange.lowerBound < rhs.baseRange.lowerBound + } +} + +extension ChunkedByCount: + BidirectionalCollection, RandomAccessCollection +where Base: RandomAccessCollection { + @inlinable + public func index(before i: Index) -> Index { + var offset = chunkCount + if i.baseRange.lowerBound == base.endIndex { + let remainder = base.count%chunkCount + if remainder != 0 { + offset = remainder + } + } + + let baseIdx = base.index( + i.baseRange.lowerBound, offsetBy: -offset, + limitedBy: base.startIndex + ) ?? base.startIndex + return Index(_baseRange: baseIdx.. Int { + let distance = + base.distance(from: start.baseRange.lowerBound, + to: end.baseRange.lowerBound) + let (quotient, remainder) = + distance.quotientAndRemainder(dividingBy: chunkCount) + // Increment should account for negative distances. + if remainder < 0 { + return quotient - 1 + } + return quotient + (remainder == 0 ? 0 : 1) + } + + @inlinable + public var count: Int { + let (quotient, remainder) = + base.count.quotientAndRemainder(dividingBy: chunkCount) + return quotient + (remainder == 0 ? 0 : 1) + } +} + +extension Collection { + /// Returns a `ChunkedCollection` view presenting the elements + /// in chunks with count of the given count parameter. + /// + /// - Parameter size: The size of the chunks. If the count parameter + /// is evenly divided by the count of the base `Collection` all the + /// chunks will have the count equals to size. + /// Otherwise, the last chunk will contain the remaining elements. + /// + /// let c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + /// print(c.chunks(ofCount: 5).map(Array.init)) + /// // [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] + /// + /// print(c.chunks(ofCount: 3).map(Array.init)) + /// // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] + /// + /// - Complexity: O(1) + @inlinable + public func chunks(ofCount count: Int) -> ChunkedByCount { + precondition(count > 0, " Cannot chunk with count <= 0!") + return ChunkedByCount(_base: self, _chunkCount: count) + } +} + +// Conditional conformances. +extension ChunkedByCount: Equatable where Base: Equatable {} + +// Since we have another stored property of type `Index` on the +// collection, synthetization of hashble conformace would require +// a `Base.Index: Hashable` constraint, so we implement the hasher +// only in terms of base. Since the computed index is based on it, +// it should make a difference here. +extension ChunkedByCount: Hashable where Base: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(base) + } +} +extension ChunkedByCount.Index: Hashable where Base.Index: Hashable {} + +// Lazy conditional conformance. +extension ChunkedByCount: LazySequenceProtocol + where Base: LazySequenceProtocol {} +extension ChunkedByCount: LazyCollectionProtocol + where Base: LazyCollectionProtocol {} From e0fed414191cb7a1b4e514d799796f5d48991b98 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Fri, 8 Jan 2021 00:08:21 -0300 Subject: [PATCH 02/10] [Chunked] Adding tests for chunks of count collection implementation --- Tests/SwiftAlgorithmsTests/ChunkedTests.swift | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift index c50af57..ea02aad 100644 --- a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift +++ b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift @@ -76,4 +76,67 @@ final class ChunkedTests: XCTestCase { XCTAssertLazySequence(fruits.lazy.chunked(by: { $0.first == $1.first })) XCTAssertLazySequence(fruits.lazy.chunked(on: { $0.first })) } + + + //===----------------------------------------------------------------------===// + // Tests for `chunks(ofCount:)` + //===----------------------------------------------------------------------===// + func testChunksOfCount() { + XCTAssertEqualSequences([Int]().chunks(ofCount: 1), []) + XCTAssertEqualSequences([Int]().chunks(ofCount: 5), []) + + let collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + XCTAssertEqualSequences(collection.chunks(ofCount: 1), + [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]) + XCTAssertEqualSequences(collection.chunks(ofCount: 3), + [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]) + XCTAssertEqualSequences(collection.chunks(ofCount: 5), + [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) + XCTAssertEqualSequences(collection.chunks(ofCount: 11), + [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) + } + + func testChunksOfCountBidirectional() { + let collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + XCTAssertEqualSequences(collection.chunks(ofCount: 1).reversed(), + [[10], [9], [8], [7], [6], [5], [4], [3], [2], [1]]) + XCTAssertEqualSequences(collection.chunks(ofCount: 3).reversed(), + [[10], [7, 8, 9], [4, 5, 6], [1, 2, 3]]) + XCTAssertEqualSequences(collection.chunks(ofCount: 5).reversed(), + [[6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]) + XCTAssertEqualSequences(collection.chunks(ofCount: 11).reversed(), + [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) + } + + func testChunksOfCountCount() { + XCTAssertEqual([Int]().chunks(ofCount: 1).count, 0) + XCTAssertEqual([Int]().chunks(ofCount: 5).count, 0) + + let collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + XCTAssertEqual(collection.chunks(ofCount: 1).count, 10) + XCTAssertEqual(collection.chunks(ofCount: 3).count, 4) + XCTAssertEqual(collection.chunks(ofCount: 5).count, 2) + XCTAssertEqual(collection.chunks(ofCount: 11).count, 1) + } + + func testEmptyChunksTraversal() { + let emptyChunks = [Int]().chunks(ofCount: 1) + + validateIndexTraversals(emptyChunks) + } + + func testChunksOfCountTraversal() { + let collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + let chunks = collection.chunks(ofCount: 2) + + validateIndexTraversals(chunks) + } + + func testChunksOfCountWithRemainderTraversal() { + let collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + let chunks = collection.chunks(ofCount: 3) + + validateIndexTraversals(chunks) + } } From 3092eb1304513cdfcafef0fc6d69678da9b7c9fe Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Fri, 8 Jan 2021 00:09:07 -0300 Subject: [PATCH 03/10] [Chucked] Add chunks(ofCount:) information on the Chunked guides --- Guides/Chunked.md | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/Guides/Chunked.md b/Guides/Chunked.md index d5b7af9..72f8dd0 100644 --- a/Guides/Chunked.md +++ b/Guides/Chunked.md @@ -4,7 +4,10 @@ [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ChunkedTests.swift)] Break a collection into subsequences where consecutive elements pass a binary -predicate, or where all elements in each chunk project to the same value. +predicate, or where all elements in each chunk project to the same value. + +Also, includes a `chunks(ofCount:)` that breaks a collection into subsequences +of a given `count`. There are two variations of the `chunked` method: `chunked(by:)` and `chunked(on:)`. `chunked(by:)` uses a binary predicate to test consecutive @@ -26,17 +29,32 @@ let chunks = names.chunked(on: \.first!) // [["David"], ["Kyle", "Karoy"], ["Nate"]] ``` -These methods are related to the [existing SE proposal][proposal] for chunking a -collection into subsequences of a particular size, potentially named something -like `chunked(length:)`. Unlike the `split` family of methods, the entire -collection is included in the chunked result — joining the resulting chunks -recreates the original collection. +The `chunks(ofCount:)` takes a `count` parameter (required to be > 0) and separates +the collection into `n` chunks of this given count. If the `count` parameter is +evenly divided by the count of the base `Collection` all the chunks will have +the count equals to the parameter. Otherwise, the last chunk will contain the +remaining elements. + +```swift +let names = ["David", "Kyle", "Karoy", "Nate"] +let evenly = names.chunks(ofCount: 2) +// equivalent to [["David", "Kyle"], ["Karoy", "Nate"]] + +let remaining = names.chunks(ofCount: 3) +// equivalent to [["David", "Kyle", "Karoy"], ["Nate"]] +``` + +The `chunks(ofCount:)` is the method of the [existing SE proposal][proposal]. +Unlike the `split` family of methods, the entire collection is included in the +chunked result — joining the resulting chunks recreates the original collection. ```swift c.elementsEqual(c.chunked(...).joined()) // true ``` +Check the [proposal][proposal] detailed design section for more info. + [proposal]: https://github.com/apple/swift-evolution/pull/935 ## Detailed Design From 79aeb24e9d875b70ebe1d5e896493bcdecb107a7 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Fri, 8 Jan 2021 07:12:17 -0300 Subject: [PATCH 04/10] Fixing review comments --- Sources/Algorithms/Chunked.swift | 24 +++++++++++-------- Tests/SwiftAlgorithmsTests/ChunkedTests.swift | 13 ++++++---- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift index 93296dd..73fc2c7 100644 --- a/Sources/Algorithms/Chunked.swift +++ b/Sources/Algorithms/Chunked.swift @@ -313,11 +313,13 @@ extension ChunkedByCount: Collection { /// - Complexity: O(n) public subscript(i: Index) -> Element { - base[i.baseRange] + precondition(i < endIndex, "Index out of range") + return base[i.baseRange] } @inlinable public func index(after i: Index) -> Index { + precondition(i < endIndex, "Advancing past end index") let baseIdx = base.index( i.baseRange.upperBound, offsetBy: chunkCount, limitedBy: base.endIndex @@ -339,6 +341,8 @@ extension ChunkedByCount: where Base: RandomAccessCollection { @inlinable public func index(before i: Index) -> Index { + precondition(i > startIndex, "Advancing past start index") + var offset = chunkCount if i.baseRange.lowerBound == base.endIndex { let remainder = base.count%chunkCount @@ -354,6 +358,10 @@ where Base: RandomAccessCollection { return Index(_baseRange: baseIdx.. Int { let distance = @@ -361,18 +369,14 @@ where Base: RandomAccessCollection { to: end.baseRange.lowerBound) let (quotient, remainder) = distance.quotientAndRemainder(dividingBy: chunkCount) - // Increment should account for negative distances. - if remainder < 0 { - return quotient - 1 - } - return quotient + (remainder == 0 ? 0 : 1) + return quotient + remainder.signum() } @inlinable public var count: Int { let (quotient, remainder) = base.count.quotientAndRemainder(dividingBy: chunkCount) - return quotient + (remainder == 0 ? 0 : 1) + return quotient + remainder.signum() } } @@ -404,10 +408,10 @@ extension Collection { extension ChunkedByCount: Equatable where Base: Equatable {} // Since we have another stored property of type `Index` on the -// collection, synthetization of hashble conformace would require +// collection, synthesis of `Hashble` conformace would require // a `Base.Index: Hashable` constraint, so we implement the hasher -// only in terms of base. Since the computed index is based on it, -// it should make a difference here. +// only in terms of `base`. Since the computed index is based on it, +// it should not make a difference here. extension ChunkedByCount: Hashable where Base: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(base) diff --git a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift index ea02aad..20dcdfa 100644 --- a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift +++ b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift @@ -113,11 +113,14 @@ final class ChunkedTests: XCTestCase { XCTAssertEqual([Int]().chunks(ofCount: 1).count, 0) XCTAssertEqual([Int]().chunks(ofCount: 5).count, 0) - let collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - XCTAssertEqual(collection.chunks(ofCount: 1).count, 10) - XCTAssertEqual(collection.chunks(ofCount: 3).count, 4) - XCTAssertEqual(collection.chunks(ofCount: 5).count, 2) - XCTAssertEqual(collection.chunks(ofCount: 11).count, 1) + let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + XCTAssertEqual(collection1.chunks(ofCount: 1).count, 10) + XCTAssertEqual(collection1.chunks(ofCount: 3).count, 4) + XCTAssertEqual(collection1.chunks(ofCount: 5).count, 2) + XCTAssertEqual(collection1.chunks(ofCount: 11).count, 1) + + let collection2 = (1...50).map { $0 } + XCTAssertEqual(collection2.chunks(ofCount: 9).count, 6) } func testEmptyChunksTraversal() { From afac704540a71abc2b087234b056e029c342db61 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Sat, 9 Jan 2021 00:09:48 -0300 Subject: [PATCH 05/10] [Chunked] Implemeting of ChunkedByCount index(offsetBy:) --- Sources/Algorithms/Chunked.swift | 84 ++++++++++++++++++++++++++++++-- 1 file changed, 80 insertions(+), 4 deletions(-) diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift index 73fc2c7..209aff7 100644 --- a/Sources/Algorithms/Chunked.swift +++ b/Sources/Algorithms/Chunked.swift @@ -305,13 +305,15 @@ extension ChunkedByCount: Collection { } } - /// - Complexity: O(n) + /// - Complexity: O(1) + @inlinable public var startIndex: Index { computedStartIndex } + @inlinable public var endIndex: Index { Index(_baseRange: base.endIndex.. Element { precondition(i < endIndex, "Index out of range") return base[i.baseRange] @@ -358,7 +360,81 @@ where Base: RandomAccessCollection { return Index(_baseRange: baseIdx.. Index? { + guard offset != 0 else { return i } + guard limit != i else { return nil } + + if offset > 0 { + guard limit <= i || distance(from: i, to: limit) >= offset else { + return nil + } + return offsetForward(i, offsetBy: offset) + } else { + guard limit >= i || distance(from: i, to: limit) <= offset else { + return nil + } + return offsetBackward(i, offsetBy: offset) + } + } + + @inlinable + public func index(_ i: Index, offsetBy distance: Int) -> Index { + guard distance != 0 else { return i } + + return distance > 0 + ? offsetForward(i, offsetBy: distance) + : offsetBackward(i, offsetBy: distance) + } + + @usableFromInline + internal func offsetForward(_ i: Index, offsetBy distance: Int) -> Index { + return makeOffsetIndex( + from: i, baseBound: base.endIndex, distance: distance + ) + } + + @usableFromInline + internal func offsetBackward(_ i: Index, offsetBy n: Int) -> Index { + var idx = i + var distance = n + // If we know that the last chunk is the only one that can possible + // have a variadic count. So in order to simplify and avoid another + // calculation of offsets(that is already done at `index(before:)`) + // we just move one position already so the index can be calculated + // assuming all chunks have the same size. + if i.baseRange.lowerBound == base.endIndex { + formIndex(before: &idx) + distance += 1 + // If the offset was simply one, we are done. + guard distance != 0 else { + return idx + } + } + + return makeOffsetIndex( + from: idx, baseBound: base.startIndex, distance: distance + ) + } + + // Helper to compute index(offsetBy:) index. + internal func makeOffsetIndex( + from i: Index, baseBound: Base.Index, distance: Int + ) -> Index { + let baseStartIdx = base.index( + i.baseRange.lowerBound, offsetBy: distance * chunkCount, + limitedBy: baseBound + ) ?? baseBound + + let baseEndIdx = base.index( + i.baseRange.lowerBound, offsetBy: (distance + 1) * chunkCount, + limitedBy: base.endIndex + ) ?? base.endIndex + + return Index(_baseRange: baseStartIdx.. ChunkedByCount { - precondition(count > 0, " Cannot chunk with count <= 0!") + precondition(count > 0, "Cannot chunk with count <= 0!") return ChunkedByCount(_base: self, _chunkCount: count) } } From 05df988369bfaaaaf1eba2fe614213debf237b17 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Sat, 9 Jan 2021 13:45:44 -0300 Subject: [PATCH 06/10] [Chunked] Minor adjustments on tests --- Sources/Algorithms/Chunked.swift | 13 ++++--- Tests/SwiftAlgorithmsTests/ChunkedTests.swift | 39 +++++++++++++------ 2 files changed, 34 insertions(+), 18 deletions(-) diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift index 209aff7..8a53408 100644 --- a/Sources/Algorithms/Chunked.swift +++ b/Sources/Algorithms/Chunked.swift @@ -368,12 +368,12 @@ where Base: RandomAccessCollection { guard limit != i else { return nil } if offset > 0 { - guard limit <= i || distance(from: i, to: limit) >= offset else { + guard limit < i || distance(from: i, to: limit) >= offset else { return nil } return offsetForward(i, offsetBy: offset) } else { - guard limit >= i || distance(from: i, to: limit) <= offset else { + guard limit > i || distance(from: i, to: limit) <= offset else { return nil } return offsetBackward(i, offsetBy: offset) @@ -397,14 +397,14 @@ where Base: RandomAccessCollection { } @usableFromInline - internal func offsetBackward(_ i: Index, offsetBy n: Int) -> Index { + internal func offsetBackward(_ i: Index, offsetBy distance: Int) -> Index { var idx = i - var distance = n + var distance = distance // If we know that the last chunk is the only one that can possible // have a variadic count. So in order to simplify and avoid another // calculation of offsets(that is already done at `index(before:)`) // we just move one position already so the index can be calculated - // assuming all chunks have the same size. + // since all remaining chunks have the same size. if i.baseRange.lowerBound == base.endIndex { formIndex(before: &idx) distance += 1 @@ -420,7 +420,8 @@ where Base: RandomAccessCollection { } // Helper to compute index(offsetBy:) index. - internal func makeOffsetIndex( + @inline(__always) + private func makeOffsetIndex( from i: Index, baseBound: Base.Index, distance: Int ) -> Index { let baseStartIdx = base.index( diff --git a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift index 20dcdfa..33de0df 100644 --- a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift +++ b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift @@ -85,28 +85,36 @@ final class ChunkedTests: XCTestCase { XCTAssertEqualSequences([Int]().chunks(ofCount: 1), []) XCTAssertEqualSequences([Int]().chunks(ofCount: 5), []) - let collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - XCTAssertEqualSequences(collection.chunks(ofCount: 1), + let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + XCTAssertEqualSequences(collection1.chunks(ofCount: 1), [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]) - XCTAssertEqualSequences(collection.chunks(ofCount: 3), + XCTAssertEqualSequences(collection1.chunks(ofCount: 3), [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]) - XCTAssertEqualSequences(collection.chunks(ofCount: 5), + XCTAssertEqualSequences(collection1.chunks(ofCount: 5), [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) - XCTAssertEqualSequences(collection.chunks(ofCount: 11), + XCTAssertEqualSequences(collection1.chunks(ofCount: 11), [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) + + let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + XCTAssertEqualSequences(collection2.chunks(ofCount: 3), + [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]) } func testChunksOfCountBidirectional() { - let collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - XCTAssertEqualSequences(collection.chunks(ofCount: 1).reversed(), + XCTAssertEqualSequences(collection1.chunks(ofCount: 1).reversed(), [[10], [9], [8], [7], [6], [5], [4], [3], [2], [1]]) - XCTAssertEqualSequences(collection.chunks(ofCount: 3).reversed(), + XCTAssertEqualSequences(collection1.chunks(ofCount: 3).reversed(), [[10], [7, 8, 9], [4, 5, 6], [1, 2, 3]]) - XCTAssertEqualSequences(collection.chunks(ofCount: 5).reversed(), + XCTAssertEqualSequences(collection1.chunks(ofCount: 5).reversed(), [[6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]) - XCTAssertEqualSequences(collection.chunks(ofCount: 11).reversed(), + XCTAssertEqualSequences(collection1.chunks(ofCount: 11).reversed(), [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) + + let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + XCTAssertEqualSequences(collection2.chunks(ofCount: 3).reversed(), + [[10, 11], [7, 8, 9], [4, 5, 6], [1, 2, 3]]) } func testChunksOfCountCount() { @@ -123,7 +131,7 @@ final class ChunkedTests: XCTestCase { XCTAssertEqual(collection2.chunks(ofCount: 9).count, 6) } - func testEmptyChunksTraversal() { + func testEmptyChunksOfCountTraversal() { let emptyChunks = [Int]().chunks(ofCount: 1) validateIndexTraversals(emptyChunks) @@ -136,10 +144,17 @@ final class ChunkedTests: XCTestCase { validateIndexTraversals(chunks) } - func testChunksOfCountWithRemainderTraversal() { + func testChunksOfCountWithSingleRemainderTraversal() { let collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let chunks = collection.chunks(ofCount: 3) validateIndexTraversals(chunks) } + + func testChunksOfCountWithRemainder() { + let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + let chunks = collection2.chunks(ofCount: 3) + + validateIndexTraversals(chunks) + } } From f89fe8fad18c74f0f605a62f40c9d6f191a1a3d7 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Wed, 13 Jan 2021 21:36:00 -0300 Subject: [PATCH 07/10] [Chunked] Code review adjustments --- Sources/Algorithms/Chunked.swift | 91 +++++++++++++++++--------------- 1 file changed, 47 insertions(+), 44 deletions(-) diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift index 8a53408..d93bf8f 100644 --- a/Sources/Algorithms/Chunked.swift +++ b/Sources/Algorithms/Chunked.swift @@ -271,7 +271,7 @@ public struct ChunkedByCount { internal let chunkCount: Int @usableFromInline - internal var computedStartIndex: Index + internal var startUpperBound: Base.Index /// Creates a view instance that presents the elements of `base` /// in `SubSequence` chunks of the given count. @@ -284,13 +284,10 @@ public struct ChunkedByCount { // Compute the start index upfront in order to make // start index a O(1) lookup. - let baseEnd = _base.index( + self.startUpperBound = _base.index( _base.startIndex, offsetBy: _chunkCount, limitedBy: _base.endIndex ) ?? _base.endIndex - - self.computedStartIndex = - Index(_baseRange: _base.startIndex.. Bool { + lhs.baseRange.lowerBound == rhs.baseRange.lowerBound + } + @inlinable public static func < (lhs: ChunkedByCount.Index, rhs: ChunkedByCount.Index) -> Bool { @@ -359,6 +364,25 @@ where Base: RandomAccessCollection { ) ?? base.startIndex return Index(_baseRange: baseIdx.. Int { + let distance = + base.distance(from: start.baseRange.lowerBound, + to: end.baseRange.lowerBound) + let (quotient, remainder) = + distance.quotientAndRemainder(dividingBy: chunkCount) + return quotient + remainder.signum() + } + + @inlinable + public var count: Int { + let (quotient, remainder) = + base.count.quotientAndRemainder(dividingBy: chunkCount) + return quotient + remainder.signum() + } @inlinable public func index( @@ -391,72 +415,51 @@ where Base: RandomAccessCollection { @usableFromInline internal func offsetForward(_ i: Index, offsetBy distance: Int) -> Index { + assert(distance > 0) return makeOffsetIndex( - from: i, baseBound: base.endIndex, distance: distance + from: i, baseBound: base.endIndex, baseDistance: distance * chunkCount ) } @usableFromInline internal func offsetBackward(_ i: Index, offsetBy distance: Int) -> Index { - var idx = i - var distance = distance - // If we know that the last chunk is the only one that can possible - // have a variadic count. So in order to simplify and avoid another - // calculation of offsets(that is already done at `index(before:)`) - // we just move one position already so the index can be calculated - // since all remaining chunks have the same size. + assert(distance < 0) if i.baseRange.lowerBound == base.endIndex { - formIndex(before: &idx) - distance += 1 - // If the offset was simply one, we are done. - guard distance != 0 else { - return idx + let remainder = base.count%chunkCount + // We have to take it into account when calculating offsets. + if remainder != 0 { + // Distance "minus" one(at this point distance is negative) because we + // need to adjust for the last position that have a variadic(remainder) + // number of elements. + let baseDistance = ((distance + 1) * chunkCount) - remainder + return makeOffsetIndex( + from: i, baseBound: base.startIndex, baseDistance: baseDistance + ) } } - return makeOffsetIndex( - from: idx, baseBound: base.startIndex, distance: distance + from: i, baseBound: base.startIndex, baseDistance: distance * chunkCount ) } // Helper to compute index(offsetBy:) index. @inline(__always) private func makeOffsetIndex( - from i: Index, baseBound: Base.Index, distance: Int + from i: Index, baseBound: Base.Index, baseDistance: Int ) -> Index { let baseStartIdx = base.index( - i.baseRange.lowerBound, offsetBy: distance * chunkCount, + i.baseRange.lowerBound, offsetBy: baseDistance, limitedBy: baseBound ) ?? baseBound let baseEndIdx = base.index( - i.baseRange.lowerBound, offsetBy: (distance + 1) * chunkCount, - limitedBy: base.endIndex + baseStartIdx, offsetBy: chunkCount, limitedBy: base.endIndex ) ?? base.endIndex return Index(_baseRange: baseStartIdx.. Int { - let distance = - base.distance(from: start.baseRange.lowerBound, - to: end.baseRange.lowerBound) - let (quotient, remainder) = - distance.quotientAndRemainder(dividingBy: chunkCount) - return quotient + remainder.signum() - } - - @inlinable - public var count: Int { - let (quotient, remainder) = - base.count.quotientAndRemainder(dividingBy: chunkCount) - return quotient + remainder.signum() - } -} - extension Collection { /// Returns a `ChunkedCollection` view presenting the elements /// in chunks with count of the given count parameter. From 622703b97f57e68398af2ee62caa3e6e39a920ab Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Thu, 14 Jan 2021 22:56:28 -0300 Subject: [PATCH 08/10] [Chunked] Improve tests for ChunksOfCount traversal --- Tests/SwiftAlgorithmsTests/ChunkedTests.swift | 24 +++++-------------- 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift index 33de0df..10fcc13 100644 --- a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift +++ b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift @@ -138,23 +138,11 @@ final class ChunkedTests: XCTestCase { } func testChunksOfCountTraversal() { - let collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - let chunks = collection.chunks(ofCount: 2) - - validateIndexTraversals(chunks) - } - - func testChunksOfCountWithSingleRemainderTraversal() { - let collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - let chunks = collection.chunks(ofCount: 3) - - validateIndexTraversals(chunks) - } - - func testChunksOfCountWithRemainder() { - let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] - let chunks = collection2.chunks(ofCount: 3) - - validateIndexTraversals(chunks) + for i in 1..<10 { + let collection = (1...50).map { $0 } + let chunks = collection.chunks(ofCount: i) + + validateIndexTraversals(chunks) + } } } From 14f09e422801427659aa1b7818c91af68939b152 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Thu, 14 Jan 2021 22:57:16 -0300 Subject: [PATCH 09/10] [Chunked] Improving index(offset:limit:) to avoid distance call --- Sources/Algorithms/Chunked.swift | 100 ++++++++++++++++++++++--------- 1 file changed, 73 insertions(+), 27 deletions(-) diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift index d93bf8f..e3cd6c5 100644 --- a/Sources/Algorithms/Chunked.swift +++ b/Sources/Algorithms/Chunked.swift @@ -392,15 +392,13 @@ extension ChunkedByCount { guard limit != i else { return nil } if offset > 0 { - guard limit < i || distance(from: i, to: limit) >= offset else { - return nil - } - return offsetForward(i, offsetBy: offset) + return limit > i + ? offsetForward(i, offsetBy: offset, limit: limit) + : offsetForward(i, offsetBy: offset) } else { - guard limit > i || distance(from: i, to: limit) <= offset else { - return nil - } - return offsetBackward(i, offsetBy: offset) + return limit < i + ? offsetBackward(i, offsetBy: offset, limit: limit) + : offsetBackward(i, offsetBy: offset) } } @@ -408,50 +406,98 @@ extension ChunkedByCount { public func index(_ i: Index, offsetBy distance: Int) -> Index { guard distance != 0 else { return i } - return distance > 0 + let idx = distance > 0 ? offsetForward(i, offsetBy: distance) : offsetBackward(i, offsetBy: distance) + guard let index = idx else { + fatalError("Out of bounds") + } + return index } @usableFromInline - internal func offsetForward(_ i: Index, offsetBy distance: Int) -> Index { + internal func offsetForward( + _ i: Index, offsetBy distance: Int, limit: Index? = nil + ) -> Index? { assert(distance > 0) + return makeOffsetIndex( - from: i, baseBound: base.endIndex, baseDistance: distance * chunkCount + from: i, baseBound: base.endIndex, + distance: distance, baseDistance: distance * chunkCount, + limit: limit, by: > ) } - @usableFromInline - internal func offsetBackward(_ i: Index, offsetBy distance: Int) -> Index { - assert(distance < 0) - if i.baseRange.lowerBound == base.endIndex { + // Convenience to compute offset backward base distance. + @inline(__always) + private func computeOffsetBackwardBaseDistance( + _ i: Index, _ distance: Int + ) -> Int { + if i == endIndex { let remainder = base.count%chunkCount // We have to take it into account when calculating offsets. if remainder != 0 { - // Distance "minus" one(at this point distance is negative) because we - // need to adjust for the last position that have a variadic(remainder) - // number of elements. - let baseDistance = ((distance + 1) * chunkCount) - remainder - return makeOffsetIndex( - from: i, baseBound: base.startIndex, baseDistance: baseDistance - ) + // Distance "minus" one(at this point distance is negative) + // because we need to adjust for the last position that have + // a variadic(remainder) number of elements. + return ((distance + 1) * chunkCount) - remainder } } + return distance * chunkCount + } + + @usableFromInline + internal func offsetBackward( + _ i: Index, offsetBy distance: Int, limit: Index? = nil + ) -> Index? { + assert(distance < 0) + let baseDistance = + computeOffsetBackwardBaseDistance(i, distance) return makeOffsetIndex( - from: i, baseBound: base.startIndex, baseDistance: distance * chunkCount + from: i, baseBound: base.startIndex, + distance: distance, baseDistance: baseDistance, + limit: limit, by: < ) } // Helper to compute index(offsetBy:) index. @inline(__always) private func makeOffsetIndex( - from i: Index, baseBound: Base.Index, baseDistance: Int - ) -> Index { - let baseStartIdx = base.index( + from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int, + limit: Index?, by limitFn: (Base.Index, Base.Index) -> Bool + ) -> Index? { + let baseIdx = base.index( i.baseRange.lowerBound, offsetBy: baseDistance, limitedBy: baseBound - ) ?? baseBound + ) + if let limit = limit { + if baseIdx == nil { + // If we past the bounds while advancing forward and the + // limit is the `endIndex`, since the computation on base + // don't take into account the remainder, we have to make + // sure that passing the bound was because of the distance + // not just because of a remainder. Special casing is less + // expensive than always use count(which could be O(n) for + // non-random access collection base) to compute the base + // distance taking remainder into account. + if baseDistance > 0 && limit == endIndex { + if self.distance(from: i, to: limit) < distance { + return nil + } + } else { + return nil + } + } + + // Checks for the limit. + let baseStartIdx = baseIdx ?? baseBound + if limitFn(baseStartIdx, limit.baseRange.lowerBound) { + return nil + } + } + + let baseStartIdx = baseIdx ?? baseBound let baseEndIdx = base.index( baseStartIdx, offsetBy: chunkCount, limitedBy: base.endIndex ) ?? base.endIndex From ad8d6ed7a172d0fe543b34e8429e337ac681d978 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Fri, 15 Jan 2021 07:53:21 -0300 Subject: [PATCH 10/10] [Chunks] Add chunks(ofCount:) in the readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9f07d3d..4e79007 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Read more about the package, and the intent behind it, in the [announcement on s #### Other useful operations -- [`chunked(by:)`, `chunked(on:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chunked.md): Eager and lazy operations that break a collection into chunks based on either a binary predicate or when the result of a projection changes. +- [`chunked(by:)`, `chunked(on:)`, `chunks(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chunked.md): Eager and lazy operations that break a collection into chunks based on either a binary predicate or when the result of a projection changes or chunks of a given count. - [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements. - [`trimming(where:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start and end.