From df51f1780b95aebbb3cdad0ef14f436cff507145 Mon Sep 17 00:00:00 2001 From: Gwynne Raskind Date: Mon, 3 Jul 2023 15:15:33 -0500 Subject: [PATCH 01/23] Specify dependency URL in consistent fashion (#194) --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 5993f0a..c007b52 100644 --- a/Package.swift +++ b/Package.swift @@ -20,7 +20,7 @@ let package = Package( targets: ["Algorithms"]), ], dependencies: [ - .package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"), + .package(url: "https://github.com/apple/swift-numerics.git", from: "1.0.0"), ], targets: [ .target( From de3efbc567dbaad19c123f165bccc9c0a4a93d84 Mon Sep 17 00:00:00 2001 From: Tim Vermeulen Date: Wed, 26 Jul 2023 18:17:25 +0200 Subject: [PATCH 02/23] Evenly divide a collection into chunks (#96) Adds `evenlyChunked(in:)` as a `Collection` method that divides a collection into a specific number of chunks as evenly as possible. Co-authored-by: Tim Vermeulen --- Guides/Chunked.md | 89 ++++--- Sources/Algorithms/Chunked.swift | 241 +++++++++++++++++- Tests/SwiftAlgorithmsTests/ChunkedTests.swift | 36 ++- 3 files changed, 325 insertions(+), 41 deletions(-) diff --git a/Guides/Chunked.md b/Guides/Chunked.md index 4b230c0..c839457 100644 --- a/Guides/Chunked.md +++ b/Guides/Chunked.md @@ -3,16 +3,16 @@ [[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Chunked.swift) | [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. +Break a collection into nonoverlapping subsequences: -Also includes a `chunks(ofCount:)` that breaks a collection into subsequences -of a given `count`. +* `chunked(by:)` forms chunks of consecutive elements that pass a binary predicate, +* `chunked(on:)` forms chunks of consecutive elements that project to equal values, +* `chunks(ofCount:)` forms chunks of a given size, and +* `evenlyChunked(in:)` forms a given number of equally-sized chunks. -There are two variations of the `chunked` method: `chunked(by:)` and -`chunked(on:)`. `chunked(by:)` uses a binary predicate to test consecutive -elements, separating chunks where the predicate returns `false`. For example, -you can chunk a collection into ascending sequences using this method: +`chunked(by:)` uses a binary predicate to test consecutive elements, separating +chunks where the predicate returns `false`. For example, you can chunk a +collection into ascending sequences using this method: ```swift let numbers = [10, 20, 30, 10, 40, 40, 10, 20] @@ -31,11 +31,10 @@ let chunks = names.chunked(on: \.first!) // [("D", ["David"]), ("K", ["Kyle", "Karoy"]), ("N", ["Nate"])] ``` -The `chunks(ofCount:)` method takes a `count` parameter (greater than zero) -and separates the collection into chunks of this given count. If the `count` -parameter is evenly divided by the count of the base `Collection`, all the -chunks will have a count equal to the parameter. Otherwise, the last chunk will -contain the remaining elements. +The `chunks(ofCount:)` method takes a `count` parameter (required to be > 0) and +separates the collection into chunks of this given count. If the length of the +collection is a multiple of the `count` parameter, all chunks will have the +a count equal to the parameter. Otherwise, the last chunk will contain the remaining elements. ```swift let names = ["David", "Kyle", "Karoy", "Nate"] @@ -46,7 +45,21 @@ let remaining = names.chunks(ofCount: 3) // equivalent to [["David", "Kyle", "Karoy"], ["Nate"]] ``` -The `chunks(ofCount:)` is the subject of an [existing SE proposal][proposal]. +The `chunks(ofCount:)` method was previously [proposed](proposal) for inclusion +in the standard library. + +The `evenlyChunked(in:)` method takes a `count` parameter and divides the +collection into `count` number of equally-sized chunks. If the length of the +collection is not a multiple of the `count` parameter, the chunks at the start +will be longer than the chunks at the end. + +```swift +let evenChunks = (0..<15).evenlyChunked(in: 3) +// equivalent to [0..<5, 5..<10, 10..<15] + +let nearlyEvenChunks = (0..<15).evenlyChunked(in: 4) +// equivalent to [0..<4, 4..<8, 8..<12, 12..<15] +``` When "chunking" a collection, the entire collection is included in the result, unlike the `split` family of methods, where separators are dropped. @@ -61,38 +74,40 @@ c.elementsEqual(c.chunked(...).joined()) ## Detailed Design -The three methods are added as extension to `Collection`. `chunked(by:)` and -`chunked(on:)` are eager by default, both with a matching version that return a -lazy wrapper added to `LazySequenceProtocol`. +The four methods are added to `Collection`, with matching versions of +`chunked(by:)` and `chunked(on:)` that return a lazy wrapper added to +`LazyCollectionProtocol`. ```swift extension Collection { - public func chunked( - by belongInSameGroup: (Element, Element) -> Bool - ) -> [SubSequence] + public func chunked( + by belongInSameGroup: (Element, Element) -> Bool + ) -> [SubSequence] - public func chunked( + public func chunked( on projection: (Element) -> Subject - ) -> [(Subject, SubSequence)] - - public func chunks(ofCount count: Int) -> ChunksOfCountCollection + ) -> [SubSequence] + + public func chunks(ofCount count: Int) -> ChunkedByCount + + public func evenlyChunked(in count: Int) -> EvenChunks } -extension LazySequenceProtocol where Self: Collection, Elements: Collection { - public func chunked( - by belongInSameGroup: @escaping (Element, Element) -> Bool - ) -> ChunkedByCollection +extension LazyCollectionProtocol { + public func chunked( + by belongInSameGroup: @escaping (Element, Element) -> Bool + ) -> ChunkedByCollection - public func chunked( - on projection: @escaping (Element) -> Subject - ) -> ChunkedOnCollection + public func chunked( + on projection: @escaping (Element) -> Subject + ) -> ChunkedOnCollection } ``` -The `ChunkedByCollection`, `ChunkedOnCollection`, and `ChunksOfCountCollection` -types are bidirectional when the wrapped collection is bidirectional. -`ChunksOfCountCollection` also conforms to `LazySequenceProtocol` when the base -collection conforms. +Each of the "chunked" collection types are bidirectional when the wrapped +collection is bidirectional. `ChunksOfCountCollection` and +`EvenChunksCollection` also conform to `RandomAccessCollection` and +`LazySequenceProtocol` when their base collections conform. ### Complexity @@ -120,5 +135,5 @@ into potentially overlapping subsequences. **Ruby:** Ruby’s `Enumerable` class defines `chunk_while` and `chunk`, which map to the proposed `chunked(by:)` and `chunked(on:)` methods. -**Rust:** Rust defines a variety of size-based `chunks` methods, but doesn’t -include any with the functionality described here. +**Rust:** Rust defines a variety of size-based `chunks` methods, of which the +standard version corresponds to the `chunks(ofCount:)` method defined here. diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift index c149ce3..ad4e9c7 100644 --- a/Sources/Algorithms/Chunked.swift +++ b/Sources/Algorithms/Chunked.swift @@ -198,6 +198,210 @@ extension ChunkedOnCollection: BidirectionalCollection extension ChunkedOnCollection: LazyCollectionProtocol {} +/// A collection wrapper that evenly breaks a collection into a given number of +/// chunks. +public struct EvenChunksCollection { + /// The base collection. + @usableFromInline + internal let base: Base + + /// The number of equal chunks the base collection is divided into. + @usableFromInline + internal let numberOfChunks: Int + + /// The count of the base collection. + @usableFromInline + internal let baseCount: Int + + /// The upper bound of the first chunk. + @usableFromInline + internal var firstUpperBound: Base.Index + + @inlinable + internal init(base: Base, numberOfChunks: Int) { + self.base = base + self.numberOfChunks = numberOfChunks + self.baseCount = base.count + self.firstUpperBound = base.startIndex + + if numberOfChunks > 0 { + firstUpperBound = endOfChunk(startingAt: base.startIndex, offset: 0) + } + } +} + +extension EvenChunksCollection { + /// Returns the number of chunks with size `smallChunkSize + 1` at the start + /// of this collection. + @inlinable + internal var numberOfLargeChunks: Int { + baseCount % numberOfChunks + } + + /// Returns the size of a chunk at a given offset. + @inlinable + internal func sizeOfChunk(offset: Int) -> Int { + let isLargeChunk = offset < numberOfLargeChunks + return baseCount / numberOfChunks + (isLargeChunk ? 1 : 0) + } + + /// Returns the index in the base collection of the end of the chunk starting + /// at the given index. + @inlinable + internal func endOfChunk(startingAt start: Base.Index, offset: Int) -> Base.Index { + base.index(start, offsetBy: sizeOfChunk(offset: offset)) + } + + /// Returns the index in the base collection of the start of the chunk ending + /// at the given index. + @inlinable + internal func startOfChunk(endingAt end: Base.Index, offset: Int) -> Base.Index { + base.index(end, offsetBy: -sizeOfChunk(offset: offset)) + } + + /// Returns the index that corresponds to the chunk that starts at the given + /// base index. + @inlinable + internal func indexOfChunk(startingAt start: Base.Index, offset: Int) -> Index { + guard offset != numberOfChunks else { return endIndex } + let end = endOfChunk(startingAt: start, offset: offset) + return Index(start.. Index { + let start = startOfChunk(endingAt: end, offset: offset) + return Index(start.. + + /// The offset corresponding to the chunk at this position. The first chunk + /// has offset `0` and all other chunks have an offset `1` greater than the + /// previous. + @usableFromInline + internal var offset: Int + + @inlinable + internal init(_ baseRange: Range, offset: Int) { + self.baseRange = baseRange + self.offset = offset + } + + @inlinable + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.offset == rhs.offset + } + + @inlinable + public static func < (lhs: Self, rhs: Self) -> Bool { + lhs.offset < rhs.offset + } + } + + public typealias Element = Base.SubSequence + + @inlinable + public var startIndex: Index { + Index(base.startIndex.. Index { + precondition(i != endIndex, "Can't advance past endIndex") + let start = i.baseRange.upperBound + return indexOfChunk(startingAt: start, offset: i.offset + 1) + } + + @inlinable + public subscript(position: Index) -> Element { + precondition(position != endIndex) + return base[position.baseRange] + } + + @inlinable + public func index(_ i: Index, offsetBy distance: Int) -> Index { + /// Returns the base distance between two `EvenChunksCollection` indices + /// from the end of one to the start of the other, when given their offsets. + func baseDistance(from offsetA: Int, to offsetB: Int) -> Int { + let smallChunkSize = baseCount / numberOfChunks + let numberOfChunks = (offsetB - offsetA) - 1 + + let largeChunksEnd = Swift.min(self.numberOfLargeChunks, offsetB) + let largeChunksStart = Swift.min(self.numberOfLargeChunks, offsetA + 1) + let numberOfLargeChunks = largeChunksEnd - largeChunksStart + + return smallChunkSize * numberOfChunks + numberOfLargeChunks + } + + if distance == 0 { + return i + } else if distance > 0 { + let offset = i.offset + distance + let baseOffset = baseDistance(from: i.offset, to: offset) + let start = base.index(i.baseRange.upperBound, offsetBy: baseOffset) + return indexOfChunk(startingAt: start, offset: offset) + } else { + let offset = i.offset + distance + let baseOffset = baseDistance(from: offset, to: i.offset) + let end = base.index(i.baseRange.lowerBound, offsetBy: -baseOffset) + return indexOfChunk(endingAt: end, offset: offset) + } + } + + @inlinable + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + if distance >= 0 { + if (0.. Int { + end.offset - start.offset + } +} + +extension EvenChunksCollection.Index: Hashable where Base.Index: Hashable {} + +extension EvenChunksCollection: BidirectionalCollection + where Base: BidirectionalCollection +{ + @inlinable + public func index(before i: Index) -> Index { + precondition(i != startIndex, "Can't advance before startIndex") + return indexOfChunk(endingAt: i.baseRange.lowerBound, offset: i.offset - 1) + } +} + +extension EvenChunksCollection: RandomAccessCollection + where Base: RandomAccessCollection {} + +extension EvenChunksCollection: LazySequenceProtocol + where Base: LazySequenceProtocol {} + +extension EvenChunksCollection: LazyCollectionProtocol + where Base: LazyCollectionProtocol {} + //===----------------------------------------------------------------------===// // lazy.chunked(by:) / lazy.chunked(on:) //===----------------------------------------------------------------------===// @@ -583,5 +787,40 @@ extension Collection { extension ChunksOfCountCollection.Index: Hashable where Base.Index: Hashable {} -extension ChunksOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol +extension ChunksOfCountCollection: LazySequenceProtocol where Base: LazySequenceProtocol {} + +extension ChunksOfCountCollection: LazyCollectionProtocol + where Base: LazyCollectionProtocol {} + +//===----------------------------------------------------------------------===// +// evenlyChunked(in:) +//===----------------------------------------------------------------------===// + +extension Collection { + /// Returns a collection of `count` evenly divided subsequences of this + /// collection. + /// + /// This method divides the collection into a given number of equally sized + /// chunks. If the length of the collection is not divisible by `count`, the + /// chunks at the start will be longer than the chunks at the end, like in + /// this example: + /// + /// for chunk in "Hello, world!".evenlyChunked(in: 5) { + /// print(chunk) + /// } + /// // "Hel" + /// // "lo," + /// // " wo" + /// // "rl" + /// // "d!" + /// + /// - Complexity: O(1) if the collection conforms to `RandomAccessCollection`, + /// otherwise O(*n*), where *n* is the length of the collection. + @inlinable + public func evenlyChunked(in count: Int) -> EvenChunksCollection { + precondition(count >= 0, "Can't divide into a negative number of chunks") + precondition(count > 0 || isEmpty, "Can't divide a non-empty collection into 0 chunks") + return EvenChunksCollection(base: self, numberOfChunks: count) + } +} diff --git a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift index 811f787..7f5b10b 100644 --- a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift +++ b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift @@ -87,9 +87,6 @@ final class ChunkedTests: XCTestCase { [1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }), [[1, 2, 3, 4], [6, 7, 8, 9]]) - print(Array([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 }))) - print(Array([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 }).reversed())) - XCTAssertEqualSequences( [1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }).reversed(), [[6, 7, 8, 9], [1, 2, 3, 4]]) @@ -173,4 +170,37 @@ final class ChunkedTests: XCTestCase { expectedCount: range.count / i + (range.count % i).signum()) } } + + func testEvenChunks() { + XCTAssertEqualSequences( + (0..<10).evenlyChunked(in: 4), + [0..<3, 3..<6, 6..<8, 8..<10]) + + XCTAssertEqualSequences( + (0..<3).evenlyChunked(in: 5), + [0..<1, 1..<2, 2..<3, 3..<3, 3..<3]) + + XCTAssertEqualSequences( + "".evenlyChunked(in: 0), + []) + + XCTAssertEqualSequences( + "".evenlyChunked(in: 1), + [""]) + } + + func testEvenChunksIndexTraversals() { + let validator = IndexValidator>>() + + [ + (0..<10).evenlyChunked(in: 1), + (0..<10).evenlyChunked(in: 2), + (0..<10).evenlyChunked(in: 3), + (0..<10).evenlyChunked(in: 10), + (0..<10).evenlyChunked(in: 20), + (0..<0).evenlyChunked(in: 0), + (0..<0).evenlyChunked(in: 1), + (0..<0).evenlyChunked(in: 10), + ].forEach { validator.validate($0) } + } } From 0f81ef4a709979b323cedb3c1e8b7d3d312315df Mon Sep 17 00:00:00 2001 From: Nate Cook Date: Wed, 26 Jul 2023 13:15:35 -0500 Subject: [PATCH 03/23] Chunked type / documentation cleanup (#200) This change improves the documentation for `evenlyChunked(in:)` and `chunks(ofCount:)` and renames `EvenChunksCollection` to `EvenlyChunkedCollection` to follow the pattern of wrapper type names matching their producing functions. --- Guides/Chunked.md | 7 +- Sources/Algorithms/Chunked.swift | 84 +++++++++++++------ Tests/SwiftAlgorithmsTests/ChunkedTests.swift | 2 +- 3 files changed, 63 insertions(+), 30 deletions(-) diff --git a/Guides/Chunked.md b/Guides/Chunked.md index c839457..a2f6703 100644 --- a/Guides/Chunked.md +++ b/Guides/Chunked.md @@ -63,7 +63,8 @@ let nearlyEvenChunks = (0..<15).evenlyChunked(in: 4) When "chunking" a collection, the entire collection is included in the result, unlike the `split` family of methods, where separators are dropped. -Joining the result of a chunking method call recreates the original collection. +Joining the result of a chunking method call results in a collection equivalent +to the original. ```swift c.elementsEqual(c.chunked(...).joined()) @@ -90,7 +91,7 @@ extension Collection { public func chunks(ofCount count: Int) -> ChunkedByCount - public func evenlyChunked(in count: Int) -> EvenChunks + public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection } extension LazyCollectionProtocol { @@ -106,7 +107,7 @@ extension LazyCollectionProtocol { Each of the "chunked" collection types are bidirectional when the wrapped collection is bidirectional. `ChunksOfCountCollection` and -`EvenChunksCollection` also conform to `RandomAccessCollection` and +`EvenlyChunkedCollection` also conform to `RandomAccessCollection` and `LazySequenceProtocol` when their base collections conform. ### Complexity diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift index ad4e9c7..48839a2 100644 --- a/Sources/Algorithms/Chunked.swift +++ b/Sources/Algorithms/Chunked.swift @@ -200,7 +200,7 @@ extension ChunkedOnCollection: LazyCollectionProtocol {} /// A collection wrapper that evenly breaks a collection into a given number of /// chunks. -public struct EvenChunksCollection { +public struct EvenlyChunkedCollection { /// The base collection. @usableFromInline internal let base: Base @@ -230,7 +230,7 @@ public struct EvenChunksCollection { } } -extension EvenChunksCollection { +extension EvenlyChunkedCollection { /// Returns the number of chunks with size `smallChunkSize + 1` at the start /// of this collection. @inlinable @@ -277,7 +277,7 @@ extension EvenChunksCollection { } } -extension EvenChunksCollection: Collection { +extension EvenlyChunkedCollection: Collection { public struct Index: Comparable { /// The range corresponding to the chunk at this position. @usableFromInline @@ -381,9 +381,9 @@ extension EvenChunksCollection: Collection { } } -extension EvenChunksCollection.Index: Hashable where Base.Index: Hashable {} +extension EvenlyChunkedCollection.Index: Hashable where Base.Index: Hashable {} -extension EvenChunksCollection: BidirectionalCollection +extension EvenlyChunkedCollection: BidirectionalCollection where Base: BidirectionalCollection { @inlinable @@ -393,13 +393,13 @@ extension EvenChunksCollection: BidirectionalCollection } } -extension EvenChunksCollection: RandomAccessCollection +extension EvenlyChunkedCollection: RandomAccessCollection where Base: RandomAccessCollection {} -extension EvenChunksCollection: LazySequenceProtocol +extension EvenlyChunkedCollection: LazySequenceProtocol where Base: LazySequenceProtocol {} -extension EvenChunksCollection: LazyCollectionProtocol +extension EvenlyChunkedCollection: LazyCollectionProtocol where Base: LazyCollectionProtocol {} //===----------------------------------------------------------------------===// @@ -762,22 +762,37 @@ extension ChunksOfCountCollection { } extension Collection { - /// Returns a `ChunksOfCountCollection` view presenting the elements in - /// chunks with count of the given count parameter. + /// Returns a collection of subsequences of this collection, each with the + /// specified length. /// - /// - Parameter count: 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. + /// If the number of elements in the collection is evenly divided by `count`, + /// then every chunk will have a length equal to `count`. Otherwise, every + /// chunk but the last will have a length equal to `count`, with the + /// remaining elements in the last chunk. /// - /// 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]] + /// let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + /// for chunk in numbers.chunks(ofCount: 5) { + /// print(chunk) + /// } + /// // [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]] + /// for chunk in numbers.chunks(ofCount: 5) { + /// print(chunk) + /// } + /// // [1, 2, 3] + /// // [4, 5, 5] + /// // [7, 8, 9] + /// // [10] /// - /// - Complexity: O(*n*), because the start index is pre-computed. + /// - Parameter count: The desired size of each chunk. + /// - Returns: A collection of consescutive, non-overlapping subseqeunces of + /// this collection, where each subsequence (except possibly the last) has + /// the length `count`. + /// + /// - Complexity: O(1) if the collection conforms to `RandomAccessCollection`; + /// otherwise, O(*k*), where *k* is equal to `count`. @inlinable public func chunks(ofCount count: Int) -> ChunksOfCountCollection { precondition(count > 0, "Cannot chunk with count <= 0!") @@ -798,10 +813,9 @@ extension ChunksOfCountCollection: LazyCollectionProtocol //===----------------------------------------------------------------------===// extension Collection { - /// Returns a collection of `count` evenly divided subsequences of this - /// collection. + /// Returns a collection of evenly divided subsequences of this collection. /// - /// This method divides the collection into a given number of equally sized + /// This method divides the collection into a given number of evenly sized /// chunks. If the length of the collection is not divisible by `count`, the /// chunks at the start will be longer than the chunks at the end, like in /// this example: @@ -815,12 +829,30 @@ extension Collection { /// // "rl" /// // "d!" /// - /// - Complexity: O(1) if the collection conforms to `RandomAccessCollection`, - /// otherwise O(*n*), where *n* is the length of the collection. + /// If the number passed as `count` is greater than the number of elements in + /// the collection, the result will include one or more empty subsequences. + /// + /// for chunk in "Hi!".evenlyChunked(in: 5) { + /// print(chunk) + /// } + /// // "H" + /// // "i" + /// // "!" + /// // "" + /// // "" + /// + /// - Parameter count: The number of chunks to evenly divide this collection + /// into. If this collection is non-empty, `count` must be greater than + /// zero; otherwise, `count` may be zero or greater. + /// - Returns: A collection of `count` subsequences of this collection, + /// divided as evenly as possible. + /// + /// - Complexity: O(1) if the collection conforms to `RandomAccessCollection`; + /// otherwise, O(*n*), where *n* is the length of the collection. @inlinable - public func evenlyChunked(in count: Int) -> EvenChunksCollection { + public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection { precondition(count >= 0, "Can't divide into a negative number of chunks") precondition(count > 0 || isEmpty, "Can't divide a non-empty collection into 0 chunks") - return EvenChunksCollection(base: self, numberOfChunks: count) + return EvenlyChunkedCollection(base: self, numberOfChunks: count) } } diff --git a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift index 7f5b10b..b8567ea 100644 --- a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift +++ b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift @@ -190,7 +190,7 @@ final class ChunkedTests: XCTestCase { } func testEvenChunksIndexTraversals() { - let validator = IndexValidator>>() + let validator = IndexValidator>>() [ (0..<10).evenlyChunked(in: 1), From bfcaaa8758d6d5d4ea44486365c79b5271e0b0a6 Mon Sep 17 00:00:00 2001 From: Matt Zanchelli Date: Wed, 2 Aug 2023 08:18:17 -0700 Subject: [PATCH 04/23] Correct Chunked documentation (#182) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Clarify that the determining factor for being grouped is equality (`Equatable`), which doesn’t necessarily mean the _same_ value (identity) * Correct algorithmic complexity documentation on the lazy Chunked functions * Document `belongInSameGroup` and `projection` --- Guides/Chunked.md | 3 ++- Sources/Algorithms/Chunked.swift | 19 +++++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Guides/Chunked.md b/Guides/Chunked.md index a2f6703..583f781 100644 --- a/Guides/Chunked.md +++ b/Guides/Chunked.md @@ -112,7 +112,8 @@ collection is bidirectional. `ChunksOfCountCollection` and ### Complexity -The eager methods are O(_n_), the lazy methods are O(_1_). +The eager methods are O(_n_) where _n_ is the number of elements in the +collection. The lazy methods are O(_n_) because the start index is pre-computed. ### Naming diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift index 48839a2..52efbd0 100644 --- a/Sources/Algorithms/Chunked.swift +++ b/Sources/Algorithms/Chunked.swift @@ -410,6 +410,9 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection { /// Returns a lazy collection of subsequences of this collection, chunked by /// the given predicate. /// + /// - Parameter belongInSameGroup: A closure that takes two adjacent elements + /// of the sequence and returns whether or not they belong in the same group. + /// /// - Complexity: O(*n*), because the start index is pre-computed. @inlinable public func chunked( @@ -422,7 +425,11 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection { } /// Returns a lazy collection of subsequences of this collection, chunked by - /// grouping elements that project to the same value. + /// grouping elements that project to equal values. + /// + /// - Parameter projection: A closure that takes an element in the sequence + /// and returns an `Equatable` value that can be used to determine if adjacent + /// elements belong in the same group. /// /// - Complexity: O(*n*), because the start index is pre-computed. @inlinable @@ -443,6 +450,10 @@ extension Collection { /// Returns a collection of subsequences of this collection, chunked by the /// given predicate. /// + /// - Parameter belongInSameGroup: A closure that takes two adjacent elements + /// of the collection and returns whether or not they belong in the same + /// group. + /// /// - Complexity: O(*n*), where *n* is the length of this collection. @inlinable public func chunked( @@ -470,7 +481,11 @@ extension Collection { } /// Returns a collection of subsequences of this collection, chunked by - /// grouping elements that project to the same value. + /// grouping elements that project to equal values. + /// + /// - Parameter projection: A closure that takes an element in the collection + /// and returns an `Equatable` value that can be used to determine if adjacent + /// elements belong in the same group. /// /// - Complexity: O(*n*), where *n* is the length of this collection. @inlinable From fc8fdfd4dcc6d05f9d603c581fcbba643cb676df Mon Sep 17 00:00:00 2001 From: Nate Cook Date: Thu, 24 Aug 2023 14:17:38 -0500 Subject: [PATCH 05/23] Curate documentation for Algorithms module (#201) --- Sources/Algorithms/AdjacentPairs.swift | 15 ++++++-- Sources/Algorithms/Combinations.swift | 4 +-- .../Documentation.docc/Algorithms.md | 24 +++++++++++++ .../Algorithms/Documentation.docc/Chunking.md | 27 ++++++++++++++ .../CombinationsPermutations.md | 32 +++++++++++++++++ .../Documentation.docc/DeprecatedScan.md | 14 ++++++++ .../Documentation.docc/Extending.md | 21 +++++++++++ .../Documentation.docc/Filtering.md | 26 ++++++++++++++ .../Algorithms/Documentation.docc/Joining.md | 35 +++++++++++++++++++ .../Documentation.docc/MinAndMax.md | 23 ++++++++++++ .../Documentation.docc/Partitioning.md | 34 ++++++++++++++++++ .../Documentation.docc/Reductions.md | 21 +++++++++++ .../Algorithms/Documentation.docc/Sampling.md | 17 +++++++++ .../Documentation.docc/Selecting.md | 25 +++++++++++++ .../Documentation.docc/SlicingSplitting.md | 31 ++++++++++++++++ .../Algorithms/Documentation.docc/Trimming.md | 27 ++++++++++++++ Sources/Algorithms/Indexed.swift | 6 +++- 17 files changed, 377 insertions(+), 5 deletions(-) create mode 100644 Sources/Algorithms/Documentation.docc/Algorithms.md create mode 100644 Sources/Algorithms/Documentation.docc/Chunking.md create mode 100644 Sources/Algorithms/Documentation.docc/CombinationsPermutations.md create mode 100644 Sources/Algorithms/Documentation.docc/DeprecatedScan.md create mode 100644 Sources/Algorithms/Documentation.docc/Extending.md create mode 100644 Sources/Algorithms/Documentation.docc/Filtering.md create mode 100644 Sources/Algorithms/Documentation.docc/Joining.md create mode 100644 Sources/Algorithms/Documentation.docc/MinAndMax.md create mode 100644 Sources/Algorithms/Documentation.docc/Partitioning.md create mode 100644 Sources/Algorithms/Documentation.docc/Reductions.md create mode 100644 Sources/Algorithms/Documentation.docc/Sampling.md create mode 100644 Sources/Algorithms/Documentation.docc/Selecting.md create mode 100644 Sources/Algorithms/Documentation.docc/SlicingSplitting.md create mode 100644 Sources/Algorithms/Documentation.docc/Trimming.md diff --git a/Sources/Algorithms/AdjacentPairs.swift b/Sources/Algorithms/AdjacentPairs.swift index 1c1fd71..dd8473d 100644 --- a/Sources/Algorithms/AdjacentPairs.swift +++ b/Sources/Algorithms/AdjacentPairs.swift @@ -10,7 +10,8 @@ //===----------------------------------------------------------------------===// extension Sequence { - /// Creates a sequence of adjacent pairs of elements from this sequence. + /// Returns a sequence of overlapping adjacent pairs of the elements of this + /// sequence. /// /// In the `AdjacentPairsSequence` returned by this method, the elements of /// the *i*th pair are the *i*th and *(i+1)*th elements of the underlying @@ -24,6 +25,11 @@ extension Sequence { /// // Prints "(2, 3)" /// // Prints "(3, 4)" /// // Prints "(4, 5)" + /// + /// The resulting sequence is empty when called on an empty or single-element + /// sequence. + /// + /// - Complexity: O(1) @inlinable public func adjacentPairs() -> AdjacentPairsSequence { AdjacentPairsSequence(base: self) @@ -31,7 +37,7 @@ extension Sequence { } extension Collection { - /// A collection of adjacent pairs of elements built from an underlying + /// Returns a collection of overlapping adjacent pairs of the elements of this /// collection. /// /// In an `AdjacentPairsCollection`, the elements of the *i*th pair are the @@ -46,6 +52,11 @@ extension Collection { /// // Prints "(2, 3)" /// // Prints "(3, 4)" /// // Prints "(4, 5)" + /// + /// The resulting collection is empty when called on an empty or + /// single-element collection. + /// + /// - Complexity: O(1) @inlinable public func adjacentPairs() -> AdjacentPairsCollection { AdjacentPairsCollection(base: self) diff --git a/Sources/Algorithms/Combinations.swift b/Sources/Algorithms/Combinations.swift index 2f26e9c..95c9c5e 100644 --- a/Sources/Algorithms/Combinations.swift +++ b/Sources/Algorithms/Combinations.swift @@ -289,8 +289,8 @@ extension Collection { /// - Parameter k: The number of elements to include in each combination. /// /// - Complexity: O(1) for random-access base collections. O(*n*) where *n* - /// is the number of elements in the base collection, since - /// `CombinationsSequence` accesses the `count` of the base collection. + /// is the number of elements in the base collection, since + /// `CombinationsSequence` accesses the `count` of the base collection. @inlinable public func combinations(ofCount k: Int) -> CombinationsSequence { precondition(k >= 0, "Can't have combinations with a negative number of elements.") diff --git a/Sources/Algorithms/Documentation.docc/Algorithms.md b/Sources/Algorithms/Documentation.docc/Algorithms.md new file mode 100644 index 0000000..4626905 --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/Algorithms.md @@ -0,0 +1,24 @@ +# ``Algorithms`` + +**Swift Algorithms** is an open-source package of sequence and collection algorithms, +along with their related types. + +## Overview + +This library adds a variety of extended operations to the Swift standard library's +`Sequence` and `Collection` protocols, via extension methods and global functions. + +## Topics + +- +- +- +- +- +- +- +- +- +- +- +- diff --git a/Sources/Algorithms/Documentation.docc/Chunking.md b/Sources/Algorithms/Documentation.docc/Chunking.md new file mode 100644 index 0000000..3c0699a --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/Chunking.md @@ -0,0 +1,27 @@ +# Chunking + +Break collections into consecutive chunks by length, count, or based on closure-based logic. + +## Overview + +## Topics + +### Chunking a Collection by Count + +- ``Swift/Collection/chunks(ofCount:)`` +- ``Swift/Collection/evenlyChunked(in:)`` + +### Chunking a Collection by Predicate + +- ``Swift/Collection/chunked(on:)`` +- ``Swift/Collection/chunked(by:)`` +- ``Swift/LazySequenceProtocol/chunked(by:)`` +- ``Swift/LazySequenceProtocol/chunked(by:)`` +- ``Swift/LazySequenceProtocol/chunked(on:)`` + +### Supporting Types + +- ``ChunkedByCollection`` +- ``ChunkedOnCollection`` +- ``ChunksOfCountCollection`` +- ``EvenlyChunkedCollection`` diff --git a/Sources/Algorithms/Documentation.docc/CombinationsPermutations.md b/Sources/Algorithms/Documentation.docc/CombinationsPermutations.md new file mode 100644 index 0000000..54199fa --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/CombinationsPermutations.md @@ -0,0 +1,32 @@ +# Combinations and Permutations + +Find the combinations and permutations of any collection's elements, +or the product of two different collections. + +## Topics + +### Combinations + +- ``Swift/Collection/combinations(ofCount:)-26o4x`` +- ``Swift/Collection/combinations(ofCount:)-53jql`` + +### Permutations + +- ``Swift/Collection/permutations(ofCount:)-7rc99`` +- ``Swift/Collection/permutations(ofCount:)-5zvhn`` + +### Unique Permutations + +- ``Swift/Collection/uniquePermutations(ofCount:)-2extq`` +- ``Swift/Collection/uniquePermutations(ofCount:)-48r1k`` + +### Product + +- ``product(_:_:)`` + +### Supporting Types + +- ``CombinationsSequence`` +- ``PermutationsSequence`` +- ``UniquePermutationsSequence`` +- ``Product2Sequence`` diff --git a/Sources/Algorithms/Documentation.docc/DeprecatedScan.md b/Sources/Algorithms/Documentation.docc/DeprecatedScan.md new file mode 100644 index 0000000..c122730 --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/DeprecatedScan.md @@ -0,0 +1,14 @@ +# DeprecatedScan + +These methods are deprecated, use the `reductions` family of methods instead. + +## Overview + +## Topics + +- ``Swift/Sequence/scan(_:)`` +- ``Swift/Sequence/scan(_:_:)`` +- ``Swift/Sequence/scan(into:_:)`` +- ``Swift/LazySequenceProtocol/scan(_:)`` +- ``Swift/LazySequenceProtocol/scan(_:_:)`` +- ``Swift/LazySequenceProtocol/scan(into:_:)`` diff --git a/Sources/Algorithms/Documentation.docc/Extending.md b/Sources/Algorithms/Documentation.docc/Extending.md new file mode 100644 index 0000000..5d45a15 --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/Extending.md @@ -0,0 +1,21 @@ +# Extending + +Chain two collections end-to-end, +or repeat a collection forever or a specific number of times. + +## Topics + +### Chaining Two Collections + +- ``chain(_:_:)`` + +### Cycling a Collection + +- ``Swift/Collection/cycled()`` +- ``Swift/Collection/cycled(times:)`` + +### Supporting Types + +- ``Chain2Sequence`` +- ``CycledSequence`` +- ``CycledTimesCollection`` diff --git a/Sources/Algorithms/Documentation.docc/Filtering.md b/Sources/Algorithms/Documentation.docc/Filtering.md new file mode 100644 index 0000000..46b7255 --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/Filtering.md @@ -0,0 +1,26 @@ +# Filtering + +Remove duplicated elements or strip the `nil` values from a sequence or collection. + +## Overview + +Text + +## Topics + +### Uniqueing Elements + +- ``Swift/Sequence/uniqued()`` +- ``Swift/Sequence/uniqued(on:)`` +- ``Swift/LazySequenceProtocol/uniqued(on:)`` + +### Filtering out nil Elements + +- ``Swift/Collection/compacted()`` +- ``Swift/Sequence/compacted()`` + +### Supporting Types + +- ``UniquedSequence`` +- ``CompactedSequence`` +- ``CompactedCollection`` diff --git a/Sources/Algorithms/Documentation.docc/Joining.md b/Sources/Algorithms/Documentation.docc/Joining.md new file mode 100644 index 0000000..2c567c2 --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/Joining.md @@ -0,0 +1,35 @@ +# Joining + +Join the parts of a collection of collections, +providing a connecting element or collection, +or a closure that produces the connector. + +## Topics + +### Joining by an Element + +- ``Swift/Sequence/joined(by:)-6mrf9`` +- ``Swift/Sequence/joined(by:)-9hyaf`` +- ``Swift/Collection/joined(by:)-430ue`` +- ``Swift/LazySequenceProtocol/joined(by:)-3yjw0`` +- ``Swift/LazySequenceProtocol/joined(by:)-47xvy`` + +### Joining by a Collection + +- ``Swift/Sequence/joined(by:)-62j1h`` +- ``Swift/Sequence/joined(by:)-9b108`` +- ``Swift/Collection/joined(by:)-28n3b`` +- ``Swift/LazySequenceProtocol/joined(by:)-4neii`` +- ``Swift/LazySequenceProtocol/joined(by:)-49xws`` + +### Interspersing Elements + +- ``Swift/Sequence/interspersed(with:)`` + +### Supporting Types + +- ``JoinedBySequence`` +- ``JoinedByCollection`` +- ``JoinedByClosureSequence`` +- ``JoinedByClosureCollection`` +- ``InterspersedSequence`` diff --git a/Sources/Algorithms/Documentation.docc/MinAndMax.md b/Sources/Algorithms/Documentation.docc/MinAndMax.md new file mode 100644 index 0000000..56e2cc8 --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/MinAndMax.md @@ -0,0 +1,23 @@ +# Finding the Minimum and Maximum + +Find the minimum and maximum elements simultaneously, +or a specific number of elements at the minimum and maximum. + +## Topics + +### Finding Minimum or Maximum Elements + +- ``Swift/Sequence/min(count:)`` +- ``Swift/Collection/min(count:)`` +- ``Swift/Sequence/min(count:sortedBy:)`` +- ``Swift/Collection/min(count:sortedBy:)`` +- ``Swift/Sequence/max(count:)`` +- ``Swift/Collection/max(count:)`` +- ``Swift/Sequence/max(count:sortedBy:)`` +- ``Swift/Collection/max(count:sortedBy:)`` + +### Finding the Minimum and Maximum Elements Simulataneously + +- ``Swift/Sequence/minAndMax()`` +- ``Swift/Sequence/minAndMax(by:)`` + diff --git a/Sources/Algorithms/Documentation.docc/Partitioning.md b/Sources/Algorithms/Documentation.docc/Partitioning.md new file mode 100644 index 0000000..d1b1fdc --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/Partitioning.md @@ -0,0 +1,34 @@ +# Partitioning and Rotating + +Partition a collection according to a unary predicate, +rotate a collection around a particular index, +or find the index where a collection is already partitioned. + +## Topics + +### Stable Partition + +- ``Swift/MutableCollection/stablePartition(by:)`` +- ``Swift/MutableCollection/stablePartition(subrange:by:)`` +- ``Swift/Sequence/partitioned(by:)`` +- ``Swift/Collection/partitioned(by:)`` + +### Partition of Subranges + +- ``Swift/MutableCollection/partition(subrange:by:)-5vdh7`` +- ``Swift/MutableCollection/partition(subrange:by:)-4gpqz`` + +### Finding a Partition Index + +- ``Swift/Collection/partitioningIndex(where:)`` + +### Rotation + +- ``Swift/MutableCollection/rotate(toStartAt:)-9fp48`` +- ``Swift/MutableCollection/rotate(toStartAt:)-2r55j`` +- ``Swift/MutableCollection/rotate(subrange:toStartAt:)-ov6a`` +- ``Swift/MutableCollection/rotate(subrange:toStartAt:)-5teoq`` + +### Reversing + +- ``Swift/MutableCollection/reverse(subrange:)`` diff --git a/Sources/Algorithms/Documentation.docc/Reductions.md b/Sources/Algorithms/Documentation.docc/Reductions.md new file mode 100644 index 0000000..81d7ea2 --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/Reductions.md @@ -0,0 +1,21 @@ +# Reductions + +Find the incremental values of a sequence "reduce" operation. + +## Topics + +- ``Swift/Sequence/reductions(_:)`` +- ``Swift/Sequence/reductions(_:_:)`` +- ``Swift/Sequence/reductions(into:_:)`` +- ``Swift/LazySequenceProtocol/reductions(_:)`` +- ``Swift/LazySequenceProtocol/reductions(_:_:)`` +- ``Swift/LazySequenceProtocol/reductions(into:_:)`` + +### Supporting Types + +- ``InclusiveReductionsSequence`` +- ``ExclusiveReductionsSequence`` + +### Deprecated Methods + +- diff --git a/Sources/Algorithms/Documentation.docc/Sampling.md b/Sources/Algorithms/Documentation.docc/Sampling.md new file mode 100644 index 0000000..b94f662 --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/Sampling.md @@ -0,0 +1,17 @@ +# Random Sampling + +Choose a specified number of random elements from a sequence or collection. + +## Topics + +### Random Sampling + +- ``Swift/Sequence/randomSample(count:)`` +- ``Swift/Collection/randomSample(count:)`` +- ``Swift/Collection/randomStableSample(count:)`` + +### Random Sampling with a Generator + +- ``Swift/Sequence/randomSample(count:using:)`` +- ``Swift/Collection/randomSample(count:using:)`` +- ``Swift/Collection/randomStableSample(count:using:)`` diff --git a/Sources/Algorithms/Documentation.docc/Selecting.md b/Sources/Algorithms/Documentation.docc/Selecting.md new file mode 100644 index 0000000..e5bed60 --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/Selecting.md @@ -0,0 +1,25 @@ +# Selecting Elements + +Select elements at a particular interval, the first mapped value, +or iterate of elements with their indices. + +## Topics + +### Selecting Elements at an Interval + +- ``Swift/Sequence/striding(by:)`` +- ``Swift/Collection/striding(by:)`` + +### Conditionally Finding the First Mapped Value + +- ``Swift/Sequence/firstNonNil(_:)`` + +### Iterating Over Elements with Their Indices + +- ``Swift/Collection/indexed()`` + +### Supporting Types + +- ``IndexedCollection`` +- ``StridingSequence`` +- ``StridingCollection`` diff --git a/Sources/Algorithms/Documentation.docc/SlicingSplitting.md b/Sources/Algorithms/Documentation.docc/SlicingSplitting.md new file mode 100644 index 0000000..78db68a --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/SlicingSplitting.md @@ -0,0 +1,31 @@ +# Slicing and Splitting + +Iterate over tuple pairs of adjacent elements, overlapping windows of a specified size, or lazily-calculated splits. + +## Topics + +### Adjacent Pairs + +- ``Swift/Sequence/adjacentPairs()`` +- ``Swift/Collection/adjacentPairs()`` + +### Windows + +- ``Swift/Collection/windows(ofCount:)`` + +### Lazily Splitting a Collection + +These methods… + +- ``Swift/LazySequenceProtocol/split(separator:maxSplits:omittingEmptySubsequences:)-4q4x8`` +- ``Swift/LazySequenceProtocol/split(maxSplits:omittingEmptySubsequences:whereSeparator:)-68oqf`` +- ``Swift/LazySequenceProtocol/split(separator:maxSplits:omittingEmptySubsequences:)-a46s`` +- ``Swift/LazySequenceProtocol/split(maxSplits:omittingEmptySubsequences:whereSeparator:)-3rwee`` + +### Supporting Types + +- ``AdjacentPairsSequence`` +- ``AdjacentPairsCollection`` +- ``WindowsOfCountCollection`` +- ``SplitSequence`` +- ``SplitCollection`` diff --git a/Sources/Algorithms/Documentation.docc/Trimming.md b/Sources/Algorithms/Documentation.docc/Trimming.md new file mode 100644 index 0000000..8052a22 --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/Trimming.md @@ -0,0 +1,27 @@ +# Trimming + +Remove unwanted elements from the start, the end, or both ends of a collection. + +## Topics + +### Trimming Both Ends of a Collection + +- ``Swift/BidirectionalCollection/trimming(while:)`` +- ``Swift/BidirectionalCollection/trim(while:)-781az`` +- ``Swift/BidirectionalCollection/trim(while:)-6cbz3`` + +### Trimming from the Start + +- ``Swift/Collection/trimmingPrefix(while:)`` +- ``Swift/Collection/trimPrefix(while:)-2r8n8`` +- ``Swift/Collection/trimPrefix(while:)-93obt`` + +### Trimming from the End + +- ``Swift/BidirectionalCollection/trimmingSuffix(while:)`` +- ``Swift/BidirectionalCollection/trimSuffix(while:)-33ubj`` +- ``Swift/BidirectionalCollection/trimSuffix(while:)-3o6x9`` + +### Finding the Suffix of a Collection + +- ``Swift/BidirectionalCollection/suffix(while:)`` diff --git a/Sources/Algorithms/Indexed.swift b/Sources/Algorithms/Indexed.swift index ea5598a..6298b6d 100644 --- a/Sources/Algorithms/Indexed.swift +++ b/Sources/Algorithms/Indexed.swift @@ -94,6 +94,10 @@ extension Collection { /// Returns a collection of pairs *(i, x)*, where *i* represents an index of /// the collection, and *x* represents an element. /// + /// The `indexed()` method is similar to the standard library's `enumerated()` + /// method, but provides the index with each element instead of a zero-based + /// counter. + /// /// This example iterates over the indices and elements of a set, building an /// array consisting of indices of names with five or fewer letters. /// @@ -105,7 +109,7 @@ extension Collection { /// } /// } /// - /// Returns: A collection of paired indices and elements of this collection. + /// - Returns: A collection of paired indices and elements of this collection. @inlinable public func indexed() -> IndexedCollection { IndexedCollection(base: self) From 0d6f943832d2afe1eccf6a4fd034fe207c970cc6 Mon Sep 17 00:00:00 2001 From: Nate Cook Date: Thu, 5 Oct 2023 13:03:25 -0500 Subject: [PATCH 06/23] Increase the package version to 5.4 (#205) The latest Swift versions appear to have a problem with the LinuxMain.swift again, which we haven't needed for quite some time. Linux test autodiscovery has been enabled since 5.4, so we can update to that version and drop the file. --- Package.swift | 2 +- Tests/LinuxMain.swift | 19 ------------------- 2 files changed, 1 insertion(+), 20 deletions(-) delete mode 100644 Tests/LinuxMain.swift diff --git a/Package.swift b/Package.swift index c007b52..30684ba 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.1 +// swift-tools-version:5.4 //===----------------------------------------------------------------------===// // // This source file is part of the Swift Algorithms open source project diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift deleted file mode 100644 index 917e331..0000000 --- a/Tests/LinuxMain.swift +++ /dev/null @@ -1,19 +0,0 @@ -//===----------------------------------------------------------*- swift -*-===// -// -// This source file is part of the Swift Argument Parser open source project -// -// Copyright (c) 2020 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -#error(""" - - ----------------------------------------------------- - - Please test with `swift test --enable-test-discovery` - - ----------------------------------------------------- - """) From 4f53c9cf409f5dce5cec07d0a73498cd5ba8ce6b Mon Sep 17 00:00:00 2001 From: Nate Cook Date: Thu, 5 Oct 2023 13:10:03 -0500 Subject: [PATCH 07/23] Finish sub-page documentation updates (#204) * Finish sub-page documentation updates Some of these pages could use introductions, but the current state is ready for publication. * Add SPI yaml file for building docs --- .spi.yml | 5 ++++ Sources/Algorithms/Chunked.swift | 11 +++---- .../Documentation.docc/Algorithms.md | 21 ++++++++++++-- .../Algorithms/Documentation.docc/Chunking.md | 17 +++++++++-- .../Documentation.docc/DeprecatedScan.md | 4 +-- .../Documentation.docc/Extending.md | 21 ++++++++++++++ .../Documentation.docc/Filtering.md | 21 ++++++++++++-- .../Documentation.docc/Partitioning.md | 29 +++++++++++++++++++ .../Documentation.docc/Reductions.md | 14 +++++++++ .../Documentation.docc/SlicingSplitting.md | 2 -- 10 files changed, 129 insertions(+), 16 deletions(-) create mode 100644 .spi.yml diff --git a/.spi.yml b/.spi.yml new file mode 100644 index 0000000..c75c9ab --- /dev/null +++ b/.spi.yml @@ -0,0 +1,5 @@ +version: 1 +builder: + configs: + - documentation_targets: [Algorithms] + diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift index 52efbd0..74f774b 100644 --- a/Sources/Algorithms/Chunked.swift +++ b/Sources/Algorithms/Chunked.swift @@ -777,8 +777,8 @@ extension ChunksOfCountCollection { } extension Collection { - /// Returns a collection of subsequences of this collection, each with the - /// specified length. + /// Returns a collection of subsequences, each with up to the specified + /// length. /// /// If the number of elements in the collection is evenly divided by `count`, /// then every chunk will have a length equal to `count`. Otherwise, every @@ -792,8 +792,7 @@ extension Collection { /// // [1, 2, 3, 4, 5] /// // [6, 7, 8, 9, 10] /// - /// print(c.chunks(ofCount: 3).map(Array.init)) - /// for chunk in numbers.chunks(ofCount: 5) { + /// for chunk in numbers.chunks(ofCount: 3) { /// print(chunk) /// } /// // [1, 2, 3] @@ -808,6 +807,7 @@ extension Collection { /// /// - Complexity: O(1) if the collection conforms to `RandomAccessCollection`; /// otherwise, O(*k*), where *k* is equal to `count`. + /// @inlinable public func chunks(ofCount count: Int) -> ChunksOfCountCollection { precondition(count > 0, "Cannot chunk with count <= 0!") @@ -828,7 +828,8 @@ extension ChunksOfCountCollection: LazyCollectionProtocol //===----------------------------------------------------------------------===// extension Collection { - /// Returns a collection of evenly divided subsequences of this collection. + /// Returns a collection of evenly divided consecutive subsequences of this + /// collection. /// /// This method divides the collection into a given number of evenly sized /// chunks. If the length of the collection is not divisible by `count`, the diff --git a/Sources/Algorithms/Documentation.docc/Algorithms.md b/Sources/Algorithms/Documentation.docc/Algorithms.md index 4626905..edd880a 100644 --- a/Sources/Algorithms/Documentation.docc/Algorithms.md +++ b/Sources/Algorithms/Documentation.docc/Algorithms.md @@ -5,8 +5,25 @@ along with their related types. ## Overview -This library adds a variety of extended operations to the Swift standard library's -`Sequence` and `Collection` protocols, via extension methods and global functions. +The Algorithms package provides a variety of sequence and collection operations, letting you cycle over a collection's elements, find combinations and permutations, create a random sample, and more. + +For example, the package includes a group of "chunking" methods, each of which breaks a collection into consecutive subsequences. One version tests adjacent elements to find the breaking point between chunks — you can use it to quickly separate an array into ascending runs: + +```swift +let numbers = [10, 20, 30, 10, 40, 40, 10, 20] +let chunks = numbers.chunked(by: { $0 <= $1 }) +// [[10, 20, 30], [10, 40, 40], [10, 20]] +``` + +Another version looks for a change in the transformation of each successive value. You can use that to separate a list of names into groups by the first character: + +```swift +let names = ["Cassie", "Chloe", "Jasmine", "Jordan", "Taylor"] +let chunks = names.chunked(on: \.first) +// [["Cassie", "Chloe"], ["Jasmine", "Jordan"], ["Taylor"]] +``` + +Explore more chunking methods and the remainder of the Algorithms package, grouped in the following topics. ## Topics diff --git a/Sources/Algorithms/Documentation.docc/Chunking.md b/Sources/Algorithms/Documentation.docc/Chunking.md index 3c0699a..c6f1448 100644 --- a/Sources/Algorithms/Documentation.docc/Chunking.md +++ b/Sources/Algorithms/Documentation.docc/Chunking.md @@ -4,6 +4,17 @@ Break collections into consecutive chunks by length, count, or based on closure- ## Overview +_Chunking_ is the process of breaking a collection into consecutive subsequences, without dropping or duplicating any of the collection's elements. After chunking a collection, joining the resulting subsequences produces the original collection of elements, unlike _splitting_, which consumes the separator element(s). + +```swift +let names = ["Ji-sun", "Jin-su", "Min-jae", "Young-ho"] +let evenlyChunked = names.chunks(ofCount: 2) +// ~ [["Ji-sun", "Jin-su"], ["Min-jae", "Young-ho"]] + +let chunkedByFirstLetter = names.chunked(on: \.first) +// equivalent to [("J", ["Ji-sun", "Jin-su"]), ("M", ["Min-jae"]), ("Y", ["Young-ho"])] +``` + ## Topics ### Chunking a Collection by Count @@ -13,10 +24,12 @@ Break collections into consecutive chunks by length, count, or based on closure- ### Chunking a Collection by Predicate -- ``Swift/Collection/chunked(on:)`` - ``Swift/Collection/chunked(by:)`` - ``Swift/LazySequenceProtocol/chunked(by:)`` -- ``Swift/LazySequenceProtocol/chunked(by:)`` + +### Chunking a Collection by Subject + +- ``Swift/Collection/chunked(on:)`` - ``Swift/LazySequenceProtocol/chunked(on:)`` ### Supporting Types diff --git a/Sources/Algorithms/Documentation.docc/DeprecatedScan.md b/Sources/Algorithms/Documentation.docc/DeprecatedScan.md index c122730..38a82a9 100644 --- a/Sources/Algorithms/Documentation.docc/DeprecatedScan.md +++ b/Sources/Algorithms/Documentation.docc/DeprecatedScan.md @@ -1,8 +1,8 @@ # DeprecatedScan -These methods are deprecated, use the `reductions` family of methods instead. +These methods are deprecated; use the `reductions` family of methods instead. -## Overview +See: ## Topics diff --git a/Sources/Algorithms/Documentation.docc/Extending.md b/Sources/Algorithms/Documentation.docc/Extending.md index 5d45a15..f3d9bce 100644 --- a/Sources/Algorithms/Documentation.docc/Extending.md +++ b/Sources/Algorithms/Documentation.docc/Extending.md @@ -3,6 +3,27 @@ Chain two collections end-to-end, or repeat a collection forever or a specific number of times. +## Overview + +_Chaining_ two collections + +```swift +let letters = chain("abcd", "EFGH") +// String(letters) == "abcdEFGH" + +for (num, letter) in zip((1...3).cycled(), letters) { + print(num, letter) +} +// 1 a +// 2 b +// 3 c +// 1 d +// 2 E +// 3 F +// 1 G +// 2 H +``` + ## Topics ### Chaining Two Collections diff --git a/Sources/Algorithms/Documentation.docc/Filtering.md b/Sources/Algorithms/Documentation.docc/Filtering.md index 46b7255..85073ab 100644 --- a/Sources/Algorithms/Documentation.docc/Filtering.md +++ b/Sources/Algorithms/Documentation.docc/Filtering.md @@ -4,17 +4,32 @@ Remove duplicated elements or strip the `nil` values from a sequence or collecti ## Overview -Text +Use the _uniquing_ methods to remove duplicates from a sequence or collection, or to remove elements that have a duplicated property. + +```swift +let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1] + +let unique = numbers.uniqued() +// Array(unique) == [1, 2, 3] +``` + +The `compacted()` method removes all `nil` values from a sequence or collection of optionals: + +```swift +let array: [Int?] = [10, nil, 30, nil, 2, 3, nil, 5] +let withNoNils = array.compacted() +// Array(withNoNils) == [10, 30, 2, 3, 5] +``` ## Topics -### Uniqueing Elements +### Uniquing Elements - ``Swift/Sequence/uniqued()`` - ``Swift/Sequence/uniqued(on:)`` - ``Swift/LazySequenceProtocol/uniqued(on:)`` -### Filtering out nil Elements +### Filtering out `nil` Elements - ``Swift/Collection/compacted()`` - ``Swift/Sequence/compacted()`` diff --git a/Sources/Algorithms/Documentation.docc/Partitioning.md b/Sources/Algorithms/Documentation.docc/Partitioning.md index d1b1fdc..091985d 100644 --- a/Sources/Algorithms/Documentation.docc/Partitioning.md +++ b/Sources/Algorithms/Documentation.docc/Partitioning.md @@ -4,6 +4,35 @@ Partition a collection according to a unary predicate, rotate a collection around a particular index, or find the index where a collection is already partitioned. +## Overview + +A _stable partition_ maintains the relative order of elements within both partitions. + +```swift +// partition(by:) - unstable ordering +var numbers = [10, 20, 30, 40, 50, 60, 70, 80] +let p1 = numbers.partition(by: { $0.isMultiple(of: 20) }) +// p1 == 4 +// numbers == [10, 70, 30, 50, 40, 60, 20, 80] +// ^ start of second partition + +// stablePartition(by:) - maintains relative ordering +numbers = [10, 20, 30, 40, 50, 60, 70, 80] +let p2 = numbers.stablePartition(by: { $0.isMultiple(of: 20) }) +// p2 == 4 +// numbers == [10, 30, 50, 70, 20, 40, 60, 80] +// ^ start of second partition +``` + +Use the `rotate` method to shift the elements of a collection to start at a new position, moving the displaced elements to the end: + +```swift +var numbers = [10, 20, 30, 40, 50, 60, 70, 80] +let p = numbers.rotate(toStartAt: 2) +// numbers == [30, 40, 50, 60, 70, 80, 10, 20] +// p == 6 -- numbers[p] == 10 +``` + ## Topics ### Stable Partition diff --git a/Sources/Algorithms/Documentation.docc/Reductions.md b/Sources/Algorithms/Documentation.docc/Reductions.md index 81d7ea2..5006821 100644 --- a/Sources/Algorithms/Documentation.docc/Reductions.md +++ b/Sources/Algorithms/Documentation.docc/Reductions.md @@ -2,6 +2,20 @@ Find the incremental values of a sequence "reduce" operation. +## Overview + +Call one of the `reductions` methods when you want the result of a `reduce` operation along with all of its intermediate values: + +```swift +let exclusiveRunningTotal = (1...5).reductions(0, +) +print(exclusiveRunningTotal) +// prints [0, 1, 3, 6, 10, 15] + +let inclusiveRunningTotal = (1...5).reductions(+) +print(inclusiveRunningTotal) +// prints [1, 3, 6, 10, 15] +``` + ## Topics - ``Swift/Sequence/reductions(_:)`` diff --git a/Sources/Algorithms/Documentation.docc/SlicingSplitting.md b/Sources/Algorithms/Documentation.docc/SlicingSplitting.md index 78db68a..388422c 100644 --- a/Sources/Algorithms/Documentation.docc/SlicingSplitting.md +++ b/Sources/Algorithms/Documentation.docc/SlicingSplitting.md @@ -15,8 +15,6 @@ Iterate over tuple pairs of adjacent elements, overlapping windows of a specifie ### Lazily Splitting a Collection -These methods… - - ``Swift/LazySequenceProtocol/split(separator:maxSplits:omittingEmptySubsequences:)-4q4x8`` - ``Swift/LazySequenceProtocol/split(maxSplits:omittingEmptySubsequences:whereSeparator:)-68oqf`` - ``Swift/LazySequenceProtocol/split(separator:maxSplits:omittingEmptySubsequences:)-a46s`` From bcd4f369ac962bc3e5244c9df778739f8f5bdbf1 Mon Sep 17 00:00:00 2001 From: Nate Cook Date: Thu, 5 Oct 2023 14:45:17 -0500 Subject: [PATCH 08/23] Update changelog for 1.1.0 release (#206) --- CHANGELOG.md | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b070cf5..df0317f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,49 @@ This project follows semantic versioning. --- +## [1.1.0] - 2023-08-24 + +### Additions + +- New nonmutating `partitioned(by:)` methods that return both the failing and passing elements of a sequence or collection in separate arrays. ([#152]) + + ```swift + let cast = ["Vivien", "Marlon", "Kim", "Karl"] + let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 }) + + print(longNames) + // Prints "["Vivien", "Marlon"]" + print(shortNames) + // Prints "["Kim", "Karl"]" + ``` + +- A new `evenlyChunked(in:)` method that chunks a sequence or collection into the specified number of evenly-sized subsequences. ([#96]) + + ```swift + let numbers = Array(0..<10) + for chunk in numbers.evenlyChunked(in: 4) { + print(chunk) + } + // Prints: + // [0, 1, 2] + // [3, 4, 5] + // [6, 7] + // [8, 9] + ``` + +### Changes + +- The package now has a minimum Swift version of Swift 5.4. + +### Fixes + +- Improvements to documentation, including a new DocC-based documentation structure. + +The 1.1.0 release includes contributions from [dickoff], [gwynne], [mdznr], [natecook1000], [ole], [stephentyrone], and [timvermeulen]. +Thank you! + +--- + ## [1.0.0] - 2021-09-08 ### Changes @@ -269,7 +312,8 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co -[Unreleased]: https://github.com/apple/swift-algorithms/compare/1.0.0...HEAD +[Unreleased]: https://github.com/apple/swift-algorithms/compare/1.1.0...HEAD +[1.1.0]: https://github.com/apple/swift-algorithms/compare/1.0.0...1.1.0 [1.0.0]: https://github.com/apple/swift-algorithms/compare/0.2.1...1.0.0 [0.2.1]: https://github.com/apple/swift-algorithms/compare/0.2.0...0.2.1 [0.2.0]: https://github.com/apple/swift-algorithms/compare/0.1.1...0.2.0 @@ -299,6 +343,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co [#85]: https://github.com/apple/swift-algorithms/pull/85 [#90]: https://github.com/apple/swift-algorithms/pull/90 [#91]: https://github.com/apple/swift-algorithms/pull/91 +[#96]: https://github.com/apple/swift-algorithms/pull/96 [#104]: https://github.com/apple/swift-algorithms/pull/104 [#106]: https://github.com/apple/swift-algorithms/pull/106 [#112]: https://github.com/apple/swift-algorithms/pull/112 @@ -307,6 +352,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co [#125]: https://github.com/apple/swift-algorithms/pull/125 [#130]: https://github.com/apple/swift-algorithms/pull/130 [#138]: https://github.com/apple/swift-algorithms/pull/138 +[#152]: https://github.com/apple/swift-algorithms/pull/152 [#162]: https://github.com/apple/swift-algorithms/pull/162 @@ -317,11 +363,13 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co [CTMacUser]: https://github.com/apple/swift-algorithms/commits?author=CTMacUser [danielctull]: https://github.com/apple/swift-algorithms/commits?author=danielctull [dhruvshah8]: https://github.com/apple/swift-algorithms/commits?author=dhruvshah8 +[dickoff]: https://github.com/apple/swift-algorithms/commits?author=dickoff [egorzhdan]: https://github.com/apple/swift-algorithms/commits?author=egorzhdan [fedeci]: https://github.com/apple/swift-algorithms/commits?author=fedeci +[gwynne]: https://github.com/apple/swift-algorithms/commits?author=gwynne [hashemi]: https://github.com/apple/swift-algorithms/commits?author=hashemi -[IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen [iainsmith]: https://github.com/apple/swift-algorithms/commits?author=iainsmith +[IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen [iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7 [karwa]: https://github.com/apple/swift-algorithms/commits?author=karwa [kylemacomber]: https://github.com/apple/swift-algorithms/commits?author=kylemacomber @@ -333,6 +381,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co [mpangburn]: https://github.com/apple/swift-algorithms/commits?author=mpangburn [natecook1000]: https://github.com/apple/swift-algorithms/commits?author=natecook1000 [nordicio]: https://github.com/apple/swift-algorithms/commits?author=nordicio +[ole]: https://github.com/apple/swift-algorithms/commits?author=ole [ollieatkinson]: https://github.com/apple/swift-algorithms/commits?author=ollieatkinson [pmtao]: https://github.com/apple/swift-algorithms/commits?author=pmtao [Qata]: https://github.com/apple/swift-algorithms/commits?author=Qata From dd4e0e70ff9e648f780444f437ef4c1380a27b01 Mon Sep 17 00:00:00 2001 From: Taras Tsugrii Date: Tue, 31 Oct 2023 09:03:19 -0700 Subject: [PATCH 09/23] [minmax] Do nothing for empty suffix/prefix. (#202) It's a semantical noop but slightly more efficient for the case when max/min is requested for an empty Collection. --- Sources/Algorithms/MinMax.swift | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Sources/Algorithms/MinMax.swift b/Sources/Algorithms/MinMax.swift index 3bce4af..ea6b5a7 100644 --- a/Sources/Algorithms/MinMax.swift +++ b/Sources/Algorithms/MinMax.swift @@ -256,13 +256,13 @@ extension Collection { """ ) - // Do nothing if we're prefixing nothing. - guard count > 0 else { - return [] - } - // Make sure we are within bounds. let prefixCount = Swift.min(count, self.count) + + // Do nothing if we're prefixing nothing. + guard prefixCount > 0 else { + return [] + } // If we're attempting to prefix more than 10% of the collection, it's // faster to sort everything. @@ -310,13 +310,13 @@ extension Collection { """ ) - // Do nothing if we're suffixing nothing. - guard count > 0 else { - return [] - } - // Make sure we are within bounds. let suffixCount = Swift.min(count, self.count) + + // Do nothing if we're suffixing nothing. + guard suffixCount > 0 else { + return [] + } // If we're attempting to prefix more than 10% of the collection, it's // faster to sort everything. From c8ae549e42aed5d5940a8b83250aa85e9d8d1dc6 Mon Sep 17 00:00:00 2001 From: Alexander Momchilov Date: Tue, 31 Oct 2023 20:25:50 -0400 Subject: [PATCH 10/23] [Docs] Add link and remove redundant doc line --- Guides/AdjacentPairs.md | 3 --- Guides/Combinations.md | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/Guides/AdjacentPairs.md b/Guides/AdjacentPairs.md index 32a6652..0924476 100644 --- a/Guides/AdjacentPairs.md +++ b/Guides/AdjacentPairs.md @@ -5,9 +5,6 @@ Lazily iterates over tuples of adjacent elements. -This operation is available for any sequence by calling the `adjacentPairs()` -method. - ```swift let numbers = (1...5) let pairs = numbers.adjacentPairs() diff --git a/Guides/Combinations.md b/Guides/Combinations.md index 2428ae9..ef78c1d 100644 --- a/Guides/Combinations.md +++ b/Guides/Combinations.md @@ -86,7 +86,7 @@ call to `CombinationsSequence.Iterator.next()` is an O(_n_) operation. ### Naming The parameter label in `combination(ofCount:)` is the best match for the -Swift API guidelines. A few other options were considered: +[Swift's API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/). A few other options were considered: - When the standard library uses `of` as a label, the parameter is generally the object of the operation, as in `type(of:)` and `firstIndex(of:)`, and From 328631d60c72528a9842adf6f854eaa31ec6ca10 Mon Sep 17 00:00:00 2001 From: Alexander Momchilov Date: Tue, 7 Nov 2023 15:29:10 -0500 Subject: [PATCH 11/23] Add `grouped(by:)` and `keyed(by:)` (#197) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add Grouped and Keyed * Add `Key` to `combine` closure * Split `keyed(by:)` into two overloads * Rename uniquingKeysWith → resolvingConflictsWith * Keep latest instead of throwing on collision --- Guides/Grouped.md | 68 ++++++++++++++ Guides/Keyed.md | 78 ++++++++++++++++ README.md | 2 + Sources/Algorithms/Grouped.swift | 25 ++++++ Sources/Algorithms/Keyed.swift | 65 ++++++++++++++ Tests/SwiftAlgorithmsTests/GroupedTests.swift | 46 ++++++++++ Tests/SwiftAlgorithmsTests/KeyedTests.swift | 88 +++++++++++++++++++ 7 files changed, 372 insertions(+) create mode 100644 Guides/Grouped.md create mode 100644 Guides/Keyed.md create mode 100644 Sources/Algorithms/Grouped.swift create mode 100755 Sources/Algorithms/Keyed.swift create mode 100644 Tests/SwiftAlgorithmsTests/GroupedTests.swift create mode 100644 Tests/SwiftAlgorithmsTests/KeyedTests.swift diff --git a/Guides/Grouped.md b/Guides/Grouped.md new file mode 100644 index 0000000..3df5443 --- /dev/null +++ b/Guides/Grouped.md @@ -0,0 +1,68 @@ +# Grouped + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Grouped.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/GroupedTests.swift)] + +Groups up elements of a sequence into a new Dictionary, whose values are Arrays of grouped elements, each keyed by the result of the given closure. + +```swift +let fruits = ["Apricot", "Banana", "Apple", "Cherry", "Avocado", "Coconut"] +let fruitsByLetter = fruits.grouped(by: { $0.first! }) +// Results in: +// [ +// "B": ["Banana"], +// "A": ["Apricot", "Apple", "Avocado"], +// "C": ["Cherry", "Coconut"], +// ] +``` + +If you wish to achieve a similar effect but for single values (instead of Arrays of grouped values), see [`keyed(by:)`](Keyed.md). + +## Detailed Design + +The `grouped(by:)` method is declared as a `Sequence` extension returning +`[GroupKey: [Element]]`. + +```swift +extension Sequence { + public func grouped( + by keyForValue: (Element) throws -> GroupKey + ) rethrows -> [GroupKey: [Element]] +} +``` + +### Complexity + +Calling `grouped(by:)` is an O(_n_) operation. + +### Comparison with other languages + +| Language | Grouping API | +|---------------|--------------| +| Java | [`groupingBy`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/stream/Collectors.html#groupingBy(java.util.function.Function)) | +| Kotlin | [`groupBy`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/group-by.html) | +| C# | [`GroupBy`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupby?view=net-7.0#system-linq-enumerable-groupby) | +| Rust | [`group_by`](https://doc.rust-lang.org/std/primitive.slice.html#method.group_by) | +| Ruby | [`group_by`](https://ruby-doc.org/3.2.2/Enumerable.html#method-i-group_by) | +| Python | [`groupby`](https://docs.python.org/3/library/itertools.html#itertools.groupby) | +| PHP (Laravel) | [`groupBy`](https://laravel.com/docs/10.x/collections#method-groupby) | + +#### Naming + +All the surveyed languages name this operation with a variant of "grouped" or "grouping". The past tense `grouped(by:)` best fits [Swift's API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/). + +#### Customization points + +Java and C# are interesting in that they provide multiple overloads with several points of customization: + +1. Changing the type of the groups. + 1. E.g. the groups can be Sets instead of Arrays. + 1. Akin to calling `.transformValues { group in Set(group) }` on the resultant dictionary, but avoiding the intermediate allocation of Arrays of each group. +2. Picking which elements end up in the groupings. + 1. The default is the elements of the input sequence, but can be changed. + 2. Akin to calling `.transformValues { group in group.map(someTransform) }` on the resultant dictionary, but avoiding the intermediate allocation of Arrays of each group. +3. Changing the type of the outermost collection. + 1. E.g using an `OrderedDictionary`, `SortedDictionary` or `TreeDictionary` instead of the default (hashed, unordered) `Dictionary`. + 2. There's no great way to achieve this with the `grouped(by:)`. One could wrap the resultant dictionary in an initializer to one of the other dictionary types, but that isn't sufficient: Once the `Dictionary` loses the ordering, there's no way to get it back when constructing one of the ordered dictionary variants. + +It is not clear which of these points of customization are worth supporting, or what the best way to express them might be. diff --git a/Guides/Keyed.md b/Guides/Keyed.md new file mode 100644 index 0000000..b2b72b4 --- /dev/null +++ b/Guides/Keyed.md @@ -0,0 +1,78 @@ +# Keyed + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Keyed.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/KeyedTests.swift)] + +Stores the elements of a sequence as the values of a Dictionary, keyed by the result of the given closure. + +```swift +let fruits = ["Apricot", "Banana", "Apple", "Cherry", "Blackberry", "Avocado", "Coconut"] +let fruitByLetter = fruits.keyed(by: { $0.first! }) +// Results in: +// [ +// "A": "Avocado", +// "B": "Blackberry", +// "C": "Coconut", +// ] +``` + +On a key-collision, the latest element is kept by default. Alternatively, you can provide a closure which specifies which value to keep: + +```swift +let fruits = ["Apricot", "Banana", "Apple", "Cherry", "Blackberry", "Avocado", "Coconut"] +let fruitsByLetter = fruits.keyed( + by: { $0.first! }, + resolvingConflictsWith: { key, old, new in old } // Always pick the first fruit +) +// Results in: +// [ +// "A": "Apricot", +// "B": "Banana", +// "C": "Cherry", +// ] +``` + +## Detailed Design + +The `keyed(by:)` and `keyed(by:resolvingConflictsWith:)` methods are declared in an `Sequence` extension, both returning `[Key: Element]`. + +```swift +extension Sequence { + public func keyed( + by keyForValue: (Element) throws -> Key + ) rethrows -> [Key: Element] + + public func keyed( + by keyForValue: (Element) throws -> Key, + resolvingConflictsWith resolve: ((Key, Element, Element) throws -> Element)? = nil + ) rethrows -> [Key: Element] +} +``` + +### Complexity + +Calling `keyed(by:)` is an O(_n_) operation. + +### Comparison with other languages + +| Language | "Keying" API | +|---------------|-------------| +| Java | [`toMap`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/stream/Collectors.html#toMap(java.util.function.Function,java.util.function.Function)) | +| Kotlin | [`associatedBy`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/associate-by.html) | +| C# | [`ToDictionary`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.todictionary?view=net-7.0#system-linq-enumerable-todictionary) | +| Ruby (ActiveSupport) | [`index_by`](https://rubydoc.info/gems/activesupport/7.0.5/Enumerable#index_by-instance_method) | +| PHP (Laravel) | [`keyBy`](https://laravel.com/docs/10.x/collections#method-keyby) | + +#### Rejected alternative names + +1. Java's `toMap` is referring to `Map`/`HashMap`, their naming for Dictionaries and other associative collections. It's easy to confuse with the transformation function, `Sequence.map(_:)`. +2. C#'s `toXXX()` naming doesn't suite Swift well, which tends to prefer `Foo.init` over `toFoo()` methods. +3. Ruby's `index_by` naming doesn't fit Swift well, where "index" is a specific term (e.g. the `associatedtype Index` on `Collection`). There is also a [`index(by:)`](Index.md) method in swift-algorithms, is specifically to do with matching elements up with their indices, and not any arbitrary derived value. + +#### Alternative names + +Kotlin's `associatedBy` naming is a good alterative, and matches the past tense of [Swift's API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/), though perhaps we'd spell it `associated(by:)`. + +#### Customization points + +Java and C# are interesting in that they provide overloads that let you customize the type of the outermost collection. E.g. using an `OrderedDictionary` instead of the default (hashed, unordered) `Dictionary`. diff --git a/README.md b/README.md index 270055f..4218cdf 100644 --- a/README.md +++ b/README.md @@ -45,8 +45,10 @@ Read more about the package, and the intent behind it, in the [announcement on s - [`adjacentPairs()`](https://github.com/apple/swift-algorithms/blob/main/Guides/AdjacentPairs.md): Lazily iterates over tuples of adjacent elements. - [`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. - [`firstNonNil(_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/FirstNonNil.md): Returns the first non-`nil` result from transforming a sequence's elements. +- [`grouped(by:)](https://github.com/apple/swift-algorithms/blob/main/Guides/Grouped.md): Group up elements using the given closure, returning a Dictionary of those groups, keyed by the results of the closure. - [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements. - [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence. +- [`keyed(by:)`, `keyed(by:resolvingConflictsBy:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Keyed.md): Returns a Dictionary that associates elements of a sequence with the keys returned by the given closure. - [`partitioningIndex(where:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the starting index of the partition of a collection that matches a predicate. - [`reductions(_:)`, `reductions(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Reductions.md): Returns all the intermediate states of reducing the elements of a sequence or collection. - [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Split.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element. diff --git a/Sources/Algorithms/Grouped.swift b/Sources/Algorithms/Grouped.swift new file mode 100644 index 0000000..34d284d --- /dev/null +++ b/Sources/Algorithms/Grouped.swift @@ -0,0 +1,25 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension Sequence { + /// Groups up elements of `self` into a new Dictionary, + /// whose values are Arrays of grouped elements, + /// each keyed by the group key returned by the given closure. + /// - Parameters: + /// - keyForValue: A closure that returns a key for each element in + /// `self`. + /// - Returns: A dictionary containing grouped elements of self, keyed by + /// the keys derived by the `keyForValue` closure. + @inlinable + public func grouped(by keyForValue: (Element) throws -> GroupKey) rethrows -> [GroupKey: [Element]] { + try Dictionary(grouping: self, by: keyForValue) + } +} diff --git a/Sources/Algorithms/Keyed.swift b/Sources/Algorithms/Keyed.swift new file mode 100755 index 0000000..0446ef6 --- /dev/null +++ b/Sources/Algorithms/Keyed.swift @@ -0,0 +1,65 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension Sequence { + /// Creates a new Dictionary from the elements of `self`, keyed by the + /// results returned by the given `keyForValue` closure. + /// + /// If the key derived for a new element collides with an existing key from a previous element, + /// the latest value will be kept. + /// + /// - Parameters: + /// - keyForValue: A closure that returns a key for each element in `self`. + @inlinable + public func keyed( + by keyForValue: (Element) throws -> Key + ) rethrows -> [Key: Element] { + return try self.keyed(by: keyForValue, resolvingConflictsWith: { _, old, new in new }) + } + + /// Creates a new Dictionary from the elements of `self`, keyed by the + /// results returned by the given `keyForValue` closure. As the dictionary is + /// built, the initializer calls the `resolve` closure with the current and + /// new values for any duplicate keys. Pass a closure as `resolve` that + /// returns the value to use in the resulting dictionary: The closure can + /// choose between the two values, combine them to produce a new value, or + /// even throw an error. + /// + /// - Parameters: + /// - keyForValue: A closure that returns a key for each element in `self`. + /// - resolve: A closure that is called with the values for any duplicate + /// keys that are encountered. The closure returns the desired value for + /// the final dictionary. + @inlinable + public func keyed( + by keyForValue: (Element) throws -> Key, + resolvingConflictsWith resolve: (Key, Element, Element) throws -> Element + ) rethrows -> [Key: Element] { + var result = [Key: Element]() + + for element in self { + let key = try keyForValue(element) + + if let oldValue = result.updateValue(element, forKey: key) { + let valueToKeep = try resolve(key, oldValue, element) + + // This causes a second look-up for the same key. The standard library can avoid that + // by calling `mutatingFind` to get access to the bucket where the value will end up, + // and updating in place. + // Swift Algorithms doesn't have access to that API, so we make do. + // When this gets merged into the standard library, we should optimize this. + result[key] = valueToKeep + } + } + + return result + } +} diff --git a/Tests/SwiftAlgorithmsTests/GroupedTests.swift b/Tests/SwiftAlgorithmsTests/GroupedTests.swift new file mode 100644 index 0000000..579016c --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/GroupedTests.swift @@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import Algorithms + +final class GroupedTests: XCTestCase { + private class SampleError: Error {} + + // Based on https://github.com/apple/swift/blob/4d1d8a9de5ebc132a17aee9fc267461facf89bf8/validation-test/stdlib/Dictionary.swift#L1974-L1988 + + func testGroupedBy() { + let r = 0..<10 + + let d1 = r.grouped(by: { $0 % 3 }) + XCTAssertEqual(3, d1.count) + XCTAssertEqual(d1[0]!, [0, 3, 6, 9]) + XCTAssertEqual(d1[1]!, [1, 4, 7]) + XCTAssertEqual(d1[2]!, [2, 5, 8]) + + let d2 = r.grouped(by: { $0 }) + XCTAssertEqual(10, d2.count) + + let d3 = (0..<0).grouped(by: { $0 }) + XCTAssertEqual(0, d3.count) + } + + func testThrowingFromKeyFunction() { + let input = ["Apple", "Banana", "Cherry"] + let error = SampleError() + + XCTAssertThrowsError( + try input.grouped(by: { (_: String) -> Character in throw error }) + ) { thrownError in + XCTAssertIdentical(error, thrownError as? SampleError) + } + } +} diff --git a/Tests/SwiftAlgorithmsTests/KeyedTests.swift b/Tests/SwiftAlgorithmsTests/KeyedTests.swift new file mode 100644 index 0000000..53b1c98 --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/KeyedTests.swift @@ -0,0 +1,88 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import Algorithms + +final class KeyedTests: XCTestCase { + private class SampleError: Error {} + + func testUniqueKeys() { + let d = ["Apple", "Banana", "Cherry"].keyed(by: { $0.first! }) + XCTAssertEqual(d.count, 3) + XCTAssertEqual(d["A"]!, "Apple") + XCTAssertEqual(d["B"]!, "Banana") + XCTAssertEqual(d["C"]!, "Cherry") + XCTAssertNil(d["D"]) + } + + func testEmpty() { + let d = EmptyCollection().keyed(by: { $0.first! }) + XCTAssertEqual(d.count, 0) + } + + func testNonUniqueKeys() throws { + let d = ["Apple", "Avocado", "Banana", "Cherry"].keyed(by: { $0.first! }) + XCTAssertEqual(d.count, 3) + XCTAssertEqual(d["A"]!, "Avocado", "On a key-collision, keyed(by:) should take the latest value.") + XCTAssertEqual(d["B"]!, "Banana") + XCTAssertEqual(d["C"]!, "Cherry") + } + + func testNonUniqueKeysWithMergeFunction() { + var resolveCallHistory = [(key: Character, current: String, new: String)]() + let expectedCallHistory = [ + (key: "A", current: "Apple", new: "Avocado"), + (key: "C", current: "Cherry", new: "Coconut"), + ] + + let d = ["Apple", "Avocado", "Banana", "Cherry", "Coconut"].keyed( + by: { $0.first! }, + resolvingConflictsWith: { key, older, newer in + resolveCallHistory.append((key, older, newer)) + return "\(older)-\(newer)" + } + ) + + XCTAssertEqual(d.count, 3) + XCTAssertEqual(d["A"]!, "Apple-Avocado") + XCTAssertEqual(d["B"]!, "Banana") + XCTAssertEqual(d["C"]!, "Cherry-Coconut") + XCTAssertNil(d["D"]) + + XCTAssertEqual( + resolveCallHistory.map(String.init(describing:)), // quick/dirty workaround: tuples aren't Equatable + expectedCallHistory.map(String.init(describing:)) + ) + } + + func testThrowingFromKeyFunction() { + let input = ["Apple", "Banana", "Cherry"] + let error = SampleError() + + XCTAssertThrowsError( + try input.keyed(by: { (_: String) -> Character in throw error }) + ) { thrownError in + XCTAssertIdentical(error, thrownError as? SampleError) + } + } + + func testThrowingFromCombineFunction() { + let input = ["Apple", "Avocado", "Banana", "Cherry"] + let error = SampleError() + + XCTAssertThrowsError( + try input.keyed(by: { $0.first! }, resolvingConflictsWith: { _, _, _ in throw error }) + ) { thrownError in + XCTAssertIdentical(error, thrownError as? SampleError) + } + } +} From 2e71e228c00dc38ea8f23a82563818beb0a8509f Mon Sep 17 00:00:00 2001 From: Matthew Young Date: Tue, 14 Nov 2023 11:04:54 -0600 Subject: [PATCH 12/23] Update Suffix.swift Change `endOfPrefix(while:)` and `startOfSuffix(while:)` from internal to public --- Sources/Algorithms/Suffix.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/Algorithms/Suffix.swift b/Sources/Algorithms/Suffix.swift index c091b82..c942adf 100644 --- a/Sources/Algorithms/Suffix.swift +++ b/Sources/Algorithms/Suffix.swift @@ -46,7 +46,7 @@ extension Collection { /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable - internal func endOfPrefix( + public func endOfPrefix( while predicate: (Element) throws -> Bool ) rethrows -> Index { var index = startIndex @@ -72,7 +72,7 @@ extension BidirectionalCollection { /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable - internal func startOfSuffix( + public func startOfSuffix( while predicate: (Element) throws -> Bool ) rethrows -> Index { var index = endIndex From 5c54f200e7f559aadf961b1fc3910706d66b17a1 Mon Sep 17 00:00:00 2001 From: Nate Cook Date: Tue, 14 Nov 2023 11:51:57 -0600 Subject: [PATCH 13/23] Update guide/docs/tests. --- Guides/Trim.md | 79 ++++++++++++------- .../Algorithms/Documentation.docc/Trimming.md | 5 ++ Sources/Algorithms/Trim.swift | 12 +-- Tests/SwiftAlgorithmsTests/SuffixTests.swift | 2 +- 4 files changed, 62 insertions(+), 36 deletions(-) diff --git a/Guides/Trim.md b/Guides/Trim.md index 4eef4e5..3f16882 100644 --- a/Guides/Trim.md +++ b/Guides/Trim.md @@ -3,8 +3,8 @@ [[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Trim.swift) | [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/TrimTests.swift)] -Returns a `SubSequence` formed by discarding all elements at the start and end -of the collection which satisfy the given predicate. +A group of methods that return the `SubSequence` formed by discarding elements +at the start and/or end of the collection which satisfy the given predicate. This example uses `trimming(while:)` to get a substring without the white space at the beginning and end of the string. @@ -17,24 +17,44 @@ let results = [2, 10, 11, 15, 20, 21, 100].trimming(while: { $0.isMultiple(of: 2 print(results) // [11, 15, 20, 21] ``` +The `Algorithms` library also includes methods that trim from each end, +as well as mutating versions of all three methods. + ## Detailed Design -A new method is added to `BidirectionalCollection`: +New methods are added to `Collection` and `BidirectionalCollection`: ```swift +extension Collection { + func trimmingPrefix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence +} + extension BidirectionalCollection { - public func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence + func trimmingSuffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence + + func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence +} + +extension Collection where Self: RangeReplaceableCollection { + mutating func trimPrefix(while predicate: (Element) throws -> Bool) rethrows +} + +extension BidirectionalCollection where Self: RangeReplaceableCollection { + mutating func trimSuffix(while predicate: (Element) throws -> Bool) rethrows + + mutating func trim(while predicate: (Element) throws -> Bool) rethrows } ``` -This method requires `BidirectionalCollection` for an efficient implementation -which visits as few elements as possible. +There are also overloads of the mutating methods when `Self == Self.SubSequence`, +for non-range-replaceable self-slicing types. -A less-efficient implementation is _possible_ for any `Collection`, which would -involve always traversing the entire collection. This implementation is not -provided, as it would mean developers of generic algorithms who forget to add -the `BidirectionalCollection` constraint will receive that inefficient -implementation: +Though the `trimming` and `trimmingSuffix` methods are declared on +`BidirectionalCollection`, a less-efficient implementation is _possible_ for +any `Collection`, which would involve always traversing the entire collection. +This implementation is not provided, as it would mean developers of generic +algorithms who forget to add the `BidirectionalCollection` constraint will +receive that inefficient implementation: ```swift func myAlgorithm(input: Input) where Input: Collection { @@ -50,28 +70,29 @@ Swift provides the `BidirectionalCollection` protocol for marking types which support reverse traversal, and generic types and algorithms which want to make use of that should add it to their constraints. -### >= 0.3.0 +#### Supporting Methods -In `v0.3.0` new methods are added to allow discarding all the elements matching -the predicate at the beginning (prefix) or at the ending (suffix) of the -collection. -- `trimmingSuffix(while:)` can only be run on collections conforming to the -`BidirectionalCollection` protocol. -- `trimmingPrefix(while:)` can be run also on collections conforming to the -`Collection` protocol. +The `endOfPrefix(while:)` and `startOfSuffix(while:)` methods are used +in the implementation of the trimming methods described above. As these +supporting methods are independently useful, they are included in the library +as well. ```swift -let myString = " hello, world " -print(myString.trimmingPrefix(while: \.isWhitespace)) // "hello, world " +extension Collection { + /// Returns the exclusive upper bound of the prefix of elements that satisfy + /// the predicate. + func endOfPrefix( + while predicate: (Element) throws -> Bool + ) rethrows -> Index +} -print(myString.trimmingSuffix(while: \.isWhitespace)) // " hello, world" -``` -Also mutating variants for all the methods already existing and the new ones are -added. -```swift -var myString = " hello, world " -myString.trim(while: \.isWhitespace) -print(myString) // "hello, world" +extension BidirectionalCollection { + /// Returns the inclusive lower bound of the suffix of elements that satisfy + /// the predicate. + func startOfSuffix( + while predicate: (Element) throws -> Bool + ) rethrows -> Index +} ``` ### Complexity diff --git a/Sources/Algorithms/Documentation.docc/Trimming.md b/Sources/Algorithms/Documentation.docc/Trimming.md index 8052a22..66d39de 100644 --- a/Sources/Algorithms/Documentation.docc/Trimming.md +++ b/Sources/Algorithms/Documentation.docc/Trimming.md @@ -25,3 +25,8 @@ Remove unwanted elements from the start, the end, or both ends of a collection. ### Finding the Suffix of a Collection - ``Swift/BidirectionalCollection/suffix(while:)`` + +### Finding Boundaries within a Collection + +- ``Swift/Collection/endOfPrefix(while:)`` +- ``Swift/BidirectionalCollection/startOfSuffix(while:)`` diff --git a/Sources/Algorithms/Trim.swift b/Sources/Algorithms/Trim.swift index 832216b..c3318c3 100644 --- a/Sources/Algorithms/Trim.swift +++ b/Sources/Algorithms/Trim.swift @@ -32,7 +32,7 @@ extension Collection { while predicate: (Element) throws -> Bool ) rethrows -> SubSequence { let start = try endOfPrefix(while: predicate) - return self[start...] + return self[start.. Bool ) rethrows { - let end = try endOfPrefix(while: predicate) - removeSubrange(startIndex.. Bool ) rethrows -> SubSequence { let end = try startOfSuffix(while: predicate) - return self[.. Bool ) rethrows { - let start = try startOfSuffix(while: predicate) - removeSubrange(start.. Date: Tue, 14 Nov 2023 12:34:56 -0600 Subject: [PATCH 14/23] Update changelog for 1.2.0 release --- CHANGELOG.md | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df0317f..98caefc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,11 +8,33 @@ This project follows semantic versioning. ## [Unreleased] -*No new changes.* +## [1.2.0] - 2023-11-14 + +### Additions + +- Sequences have new `grouped(by:)` and `keyed(by:)` methods, which simplify + building dictionaries based on sequence elements: ([#197]) + + ```swift + let evensOdds = (1...10).grouped(by: { $0.isMultiple(of: 2) ? "even" : "odd" }) + // ["even": [2, 4, 6, 8, 10], "odd": [1, 3, 5, 7, 9]] + + let animals = ["Aardvark", "Alpaca", "Armadillo", "Barracuda", "Buffalo", ...] + let alphaAnimals = animals.keyed(by: \.first!, resolvingConflictsWith: { _, first, _ in first }) + // ["A": "Aardvark", "B": "Barracuda", ...] + ``` +- The `endOfPrefix(while:)` and `startOfSuffix(while)` methods are now public. + These methods were previously implementation details of the `trimming` group + of methods. ([#211]) + +### Fixes + +- Documentation and performance improvements. ([#202], [#210]) + --- -## [1.1.0] - 2023-08-24 +## [1.1.0] - 2023-10-05 ### Additions @@ -354,6 +376,10 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co [#138]: https://github.com/apple/swift-algorithms/pull/138 [#152]: https://github.com/apple/swift-algorithms/pull/152 [#162]: https://github.com/apple/swift-algorithms/pull/162 +[#197]: https://github.com/apple/swift-algorithms/pull/197 +[#202]: https://github.com/apple/swift-algorithms/pull/202 +[#210]: https://github.com/apple/swift-algorithms/pull/210 +[#211]: https://github.com/apple/swift-algorithms/pull/211 @@ -376,6 +402,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co [LemonSpike]: https://github.com/apple/swift-algorithms/commits?author=LemonSpike [LucianoPAlmeida]: https://github.com/apple/swift-algorithms/commits?author=LucianoPAlmeida [markuswntr]: https://github.com/apple/swift-algorithms/commits?author=markuswntr +[mattyoung]: https://github.com/apple/swift-algorithms/commits?author=mattyoung [mdznr]: https://github.com/apple/swift-algorithms/commits?author=mdznr [michiboo]: https://github.com/apple/swift-algorithms/commits?author=michiboo [mpangburn]: https://github.com/apple/swift-algorithms/commits?author=mpangburn From f6919dfc309e7f1b56224378b11e28bab5bccc42 Mon Sep 17 00:00:00 2001 From: Nate Cook Date: Tue, 14 Nov 2023 13:22:01 -0600 Subject: [PATCH 15/23] Documentation improvements - Restructure the project README, moving the list of guides into a README in the `Guides` directory - Curate the `keyed(by:)` and `grouped(by:)` methods --- CHANGELOG.md | 9 ++- Guides/README.md | 53 ++++++++++++++ README.md | 70 +++++++------------ .../Documentation.docc/Algorithms.md | 1 + .../Algorithms/Documentation.docc/Keying.md | 14 ++++ 5 files changed, 102 insertions(+), 45 deletions(-) create mode 100644 Guides/README.md create mode 100644 Sources/Algorithms/Documentation.docc/Keying.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 98caefc..56f5fd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ This project follows semantic versioning. ## [Unreleased] +*No new changes.* + ## [1.2.0] - 2023-11-14 ### Additions @@ -31,6 +33,8 @@ This project follows semantic versioning. - Documentation and performance improvements. ([#202], [#210]) +The 1.2.0 release includes contributions from [amomchilov], [mattyoung], [natecook1000], [stephentyrone], and [ttsugriy]. +Thank you! --- @@ -334,7 +338,8 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co -[Unreleased]: https://github.com/apple/swift-algorithms/compare/1.1.0...HEAD +[Unreleased]: https://github.com/apple/swift-algorithms/compare/1.2.0...HEAD +[1.2.0]: https://github.com/apple/swift-algorithms/compare/1.1.0...1.2.0 [1.1.0]: https://github.com/apple/swift-algorithms/compare/1.0.0...1.1.0 [1.0.0]: https://github.com/apple/swift-algorithms/compare/0.2.1...1.0.0 [0.2.1]: https://github.com/apple/swift-algorithms/compare/0.2.0...0.2.1 @@ -383,6 +388,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co +[amomchilov]: https://github.com/apple/swift-algorithms/commits?author=amomchilov [AustinConlon]: https://github.com/apple/swift-algorithms/commits?author=AustinConlon [benrimmington]: https://github.com/apple/swift-algorithms/commits?author=benrimmington [bjhomer]: https://github.com/apple/swift-algorithms/commits?author=bjhomer @@ -420,3 +426,4 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co [stephentyrone]: https://github.com/apple/swift-algorithms/commits?author=stephentyrone [timvermeulen]: https://github.com/apple/swift-algorithms/commits?author=timvermeulen [toddthomas]: https://github.com/apple/swift-algorithms/commits?author=toddthomas +[ttsugriy]: https://github.com/apple/swift-algorithms/commits?author=ttsugriy diff --git a/Guides/README.md b/Guides/README.md new file mode 100644 index 0000000..d489488 --- /dev/null +++ b/Guides/README.md @@ -0,0 +1,53 @@ +# Guides + +These guides describe the design and intention behind the APIs included in the `Algorithms` library. For further reading, see the [announcement on swift.org](https://swift.org/blog/swift-algorithms/) and the [official documentation](https://swiftpackageindex.com/apple/swift-algorithms/documentation/algorithms). + +## Contents + +#### Combinations / permutations + +- [`combinations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Combinations.md): Combinations of particular sizes of the elements in a collection. +- [`permutations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md): Permutations of a particular size of the elements in a collection, or of the full collection. +- [`uniquePermutations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md): Permutations of a collection's elements, skipping any duplicate permutations. + +#### Mutating algorithms + +- [`rotate(toStartAt:)`, `rotate(subrange:toStartAt:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Rotate.md): In-place rotation of elements. +- [`stablePartition(by:)`, `stablePartition(subrange:by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): A partition that preserves the relative order of the resulting prefix and suffix. + +#### Combining collections + +- [`chain(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chain.md): Concatenates two collections with the same element type. +- [`cycled()`, `cycled(times:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Cycle.md): Repeats the elements of a collection forever or a set number of times. +- [`joined(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Joined.md): Concatenate sequences of sequences, using an element or sequence as a separator, or using a closure to generate each separator. +- [`product(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Product.md): Iterates over all the pairs of two collections; equivalent to nested `for`-`in` loops. + +#### Subsetting operations + +- [`compacted()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Compacted.md): Drops the `nil`s from a sequence or collection, unwrapping the remaining elements. +- [`partitioned(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the elements in a sequence or collection that do and do not match a given predicate. +- [`randomSample(count:)`, `randomSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection. +- [`randomStableSample(count:)`, `randomStableSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection, preserving their original relative order. +- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection. +- [`suffix(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Suffix.md): Returns the suffix of a collection where all element pass a given predicate. +- [`trimmingPrefix(while:)`, `trimmingSuffix(while)`, `trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start, end, or both. The mutating `trim...` methods trim a collection in place. +- [`uniqued()`, `uniqued(on:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Unique.md): The unique elements of a collection, preserving their order. +- [`minAndMax()`, `minAndMax(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest and largest elements of a sequence. + +#### Partial sorting + +- [`min(count:)`, `max(count:)`, `min(count:sortedBy:)`, `max(count:sortedBy:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest or largest elements of a collection, sorted by a predicate. + +#### Other useful operations + +- [`adjacentPairs()`](https://github.com/apple/swift-algorithms/blob/main/Guides/AdjacentPairs.md): Lazily iterates over tuples of adjacent elements. +- [`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. +- [`firstNonNil(_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/FirstNonNil.md): Returns the first non-`nil` result from transforming a sequence's elements. +- [`grouped(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Grouped.md): Group up elements using the given closure, returning a Dictionary of those groups, keyed by the results of the closure. +- [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements. +- [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence. +- [`keyed(by:)`, `keyed(by:resolvingConflictsBy:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Keyed.md): Returns a Dictionary that associates elements of a sequence with the keys returned by the given closure. +- [`partitioningIndex(where:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the starting index of the partition of a collection that matches a predicate. +- [`reductions(_:)`, `reductions(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Reductions.md): Returns all the intermediate states of reducing the elements of a sequence or collection. +- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Split.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element. +- [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection. diff --git a/README.md b/README.md index 4218cdf..e64b4d1 100644 --- a/README.md +++ b/README.md @@ -2,57 +2,35 @@ **Swift Algorithms** is an open-source package of sequence and collection algorithms, along with their related types. -Read more about the package, and the intent behind it, in the [announcement on swift.org](https://swift.org/blog/swift-algorithms/). +## Overview -## Contents +The Algorithms package provides a variety of sequence and collection operations, letting you cycle over a collection's elements, find combinations and permutations, create a random sample, and more. -#### Combinations / permutations +For example, the package includes a group of "chunking" methods, each of which breaks a collection into consecutive subsequences. One version tests adjacent elements to find the breaking point between chunks — you can use it to quickly separate an array into ascending runs: -- [`combinations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Combinations.md): Combinations of particular sizes of the elements in a collection. -- [`permutations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md): Permutations of a particular size of the elements in a collection, or of the full collection. -- [`uniquePermutations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md): Permutations of a collection's elements, skipping any duplicate permutations. +```swift +let numbers = [10, 20, 30, 10, 40, 40, 10, 20] +let chunks = numbers.chunked(by: { $0 <= $1 }) +// [[10, 20, 30], [10, 40, 40], [10, 20]] +``` -#### Mutating algorithms +Another version looks for a change in the transformation of each successive value. You can use that to separate a list of names into groups by the first character: -- [`rotate(toStartAt:)`, `rotate(subrange:toStartAt:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Rotate.md): In-place rotation of elements. -- [`stablePartition(by:)`, `stablePartition(subrange:by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): A partition that preserves the relative order of the resulting prefix and suffix. +```swift +let names = ["Cassie", "Chloe", "Jasmine", "Jordan", "Taylor"] +let chunks = names.chunked(on: \.first) +// [["Cassie", "Chloe"], ["Jasmine", "Jordan"], ["Taylor"]] +``` -#### Combining collections +Explore more chunking methods and the remainder of the `Algorithms` package in the links below. -- [`chain(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chain.md): Concatenates two collections with the same element type. -- [`cycled()`, `cycled(times:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Cycle.md): Repeats the elements of a collection forever or a set number of times. -- [`joined(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Joined.md): Concatenate sequences of sequences, using an element or sequence as a separator, or using a closure to generate each separator. -- [`product(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Product.md): Iterates over all the pairs of two collections; equivalent to nested `for`-`in` loops. +## Documentation -#### Subsetting operations +For API documentation, see the library's official documentation in Xocde or on the Web. -- [`compacted()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Compacted.md): Drops the `nil`s from a sequence or collection, unwrapping the remaining elements. -- [`partitioned(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the elements in a sequence or collection that do and do not match a given predicate. -- [`randomSample(count:)`, `randomSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection. -- [`randomStableSample(count:)`, `randomStableSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection, preserving their original relative order. -- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection. -- [`suffix(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Suffix.md): Returns the suffix of a collection where all element pass a given predicate. -- [`trimmingPrefix(while:)`, `trimmingSuffix(while)`, `trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start, end, or both. The mutating `trim...` methods trim a collection in place. -- [`uniqued()`, `uniqued(on:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Unique.md): The unique elements of a collection, preserving their order. -- [`minAndMax()`, `minAndMax(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest and largest elements of a sequence. - -#### Partial sorting - -- [`min(count:)`, `max(count:)`, `min(count:sortedBy:)`, `max(count:sortedBy:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest or largest elements of a collection, sorted by a predicate. - -#### Other useful operations - -- [`adjacentPairs()`](https://github.com/apple/swift-algorithms/blob/main/Guides/AdjacentPairs.md): Lazily iterates over tuples of adjacent elements. -- [`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. -- [`firstNonNil(_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/FirstNonNil.md): Returns the first non-`nil` result from transforming a sequence's elements. -- [`grouped(by:)](https://github.com/apple/swift-algorithms/blob/main/Guides/Grouped.md): Group up elements using the given closure, returning a Dictionary of those groups, keyed by the results of the closure. -- [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements. -- [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence. -- [`keyed(by:)`, `keyed(by:resolvingConflictsBy:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Keyed.md): Returns a Dictionary that associates elements of a sequence with the keys returned by the given closure. -- [`partitioningIndex(where:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the starting index of the partition of a collection that matches a predicate. -- [`reductions(_:)`, `reductions(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Reductions.md): Returns all the intermediate states of reducing the elements of a sequence or collection. -- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Split.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element. -- [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection. +- [API documentation][docs] +- [Swift.org announcement][announcement] +- [API Proposals/Guides][guides] ## Adding Swift Algorithms as a Dependency @@ -60,7 +38,7 @@ To use the `Algorithms` library in a SwiftPM project, add the following line to the dependencies in your `Package.swift` file: ```swift -.package(url: "https://github.com/apple/swift-algorithms", from: "1.0.0"), +.package(url: "https://github.com/apple/swift-algorithms", from: "1.2.0"), ``` Include `"Algorithms"` as a dependency for your executable target: @@ -77,8 +55,12 @@ Finally, add `import Algorithms` to your source code. The Swift Algorithms package is source stable; version numbers follow [Semantic Versioning](https://semver.org/). Source breaking changes to public API can only land in a new major version. -The public API of version 1.0 of the `swift-algorithms` package consists of non-underscored declarations that are marked `public` in the `Algorithms` module. Interfaces that aren't part of the public API may continue to change in any release, including patch releases. +The public API of the `swift-algorithms` package consists of non-underscored declarations that are marked `public` in the `Algorithms` module. Interfaces that aren't part of the public API may continue to change in any release, including patch releases. Future minor versions of the package may introduce changes to these rules as needed. We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release. Requiring a new Swift release will only require a minor version bump. + +[docs]: https://swiftpackageindex.com/apple/swift-algorithms/documentation/algorithms +[announcement]: https://swift.org/blog/swift-algorithms/ +[guides]: https://github.com/apple/swift-algorithms/tree/main/Guides diff --git a/Sources/Algorithms/Documentation.docc/Algorithms.md b/Sources/Algorithms/Documentation.docc/Algorithms.md index edd880a..3cfb269 100644 --- a/Sources/Algorithms/Documentation.docc/Algorithms.md +++ b/Sources/Algorithms/Documentation.docc/Algorithms.md @@ -33,6 +33,7 @@ Explore more chunking methods and the remainder of the Algorithms package, group - - - +- - - - diff --git a/Sources/Algorithms/Documentation.docc/Keying.md b/Sources/Algorithms/Documentation.docc/Keying.md new file mode 100644 index 0000000..aa29616 --- /dev/null +++ b/Sources/Algorithms/Documentation.docc/Keying.md @@ -0,0 +1,14 @@ +# Keying and Grouping + +Convert a sequence to a dictionary, providing keys to individual elements or to use as grouping values. + +## Topics + +### Creating a Keyed Dictionary + +- ``Swift/Sequence/keyed(by:)`` +- ``Swift/Sequence/keyed(by:resolvingConflictsWith:)`` + +### Grouping Elements by Key + +- ``Swift/Sequence/grouped(by:)`` From c3b3acbca3aa70adbd30756fe137b14e25140c0d Mon Sep 17 00:00:00 2001 From: Kenny <11343005+schlagelk@users.noreply.github.com> Date: Thu, 16 Nov 2023 13:46:54 -0700 Subject: [PATCH 16/23] Fix Typo in README Xocde -> Xcode --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e64b4d1..c648234 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Explore more chunking methods and the remainder of the `Algorithms` package in t ## Documentation -For API documentation, see the library's official documentation in Xocde or on the Web. +For API documentation, see the library's official documentation in Xcode or on the Web. - [API documentation][docs] - [Swift.org announcement][announcement] From 9dd88e5eafbd8dbdf3c2d1fd4b2016152fa0f0ac Mon Sep 17 00:00:00 2001 From: Dave Abrahams Date: Sat, 20 Jan 2024 08:04:45 -0800 Subject: [PATCH 17/23] CombinationsSequence: underestimatedCount == count (#220) Not doing this makes it needlessly costly to create an Array of the results. --- Sources/Algorithms/Combinations.swift | 4 + .../CombinationsTests.swift | 98 ++++++++++--------- 2 files changed, 56 insertions(+), 46 deletions(-) diff --git a/Sources/Algorithms/Combinations.swift b/Sources/Algorithms/Combinations.swift index 95c9c5e..0bfcbff 100644 --- a/Sources/Algorithms/Combinations.swift +++ b/Sources/Algorithms/Combinations.swift @@ -78,6 +78,10 @@ public struct CombinationsSequence { binomial(n: n, k: $0) }.reduce(0, +) } + + /// The total number of combinations. + @inlinable + public var underestimatedCount: Int { count } } extension CombinationsSequence: Sequence { diff --git a/Tests/SwiftAlgorithmsTests/CombinationsTests.swift b/Tests/SwiftAlgorithmsTests/CombinationsTests.swift index 4239b7e..45fe587 100644 --- a/Tests/SwiftAlgorithmsTests/CombinationsTests.swift +++ b/Tests/SwiftAlgorithmsTests/CombinationsTests.swift @@ -15,57 +15,63 @@ import Algorithms final class CombinationsTests: XCTestCase { func testCount() { let c = "ABCD" - - let c0 = c.combinations(ofCount: 0).count - XCTAssertEqual(c0, 1) - - let c1 = c.combinations(ofCount: 1).count - XCTAssertEqual(c1, 4) - - let c2 = c.combinations(ofCount: 2).count - XCTAssertEqual(c2, 6) - - let c3 = c.combinations(ofCount: 3).count - XCTAssertEqual(c3, 4) - - let c4 = c.combinations(ofCount: 4).count - XCTAssertEqual(c4, 1) - - let c5 = c.combinations(ofCount: 0...0).count - XCTAssertEqual(c5, 1) - - let c6 = c.combinations(ofCount: 1...1).count - XCTAssertEqual(c6, 4) - - let c7 = c.combinations(ofCount: 1...2).count - XCTAssertEqual(c7, 10) - - let c8 = c.combinations(ofCount: 1...3).count - XCTAssertEqual(c8, 14) - - let c9 = c.combinations(ofCount: 2...4).count - XCTAssertEqual(c9, 11) + + /// XCTAsserts that `x`'s `count` and `underestimatedCount` are both `l` at + /// the given `file` and `line`. + func check( + _ x: CombinationsSequence, countsAre l: Int, + file: StaticString, line: UInt) + { + XCTAssertEqual(x.count, l, "unexpected count", file: file, line: line) + XCTAssertEqual( + x.underestimatedCount, l, "unexpected underestimatedCount", + file: file, line: line) + } + + /// XCTAsserts that the `count` and `underestimatedCount` of + /// `c.combinations(ofCount: l)` are both `n` at the given `file` and + /// `line`. + func check( + cHas n: Int, + combinationsOfLength l: Int, + file: StaticString = #filePath, line: UInt = #line) + { + check(c.combinations(ofCount: l), countsAre: n, file: file, line: line) + } + + /// XCTAsserts that the `count` and `underestimatedCount` of + /// `c.combinations(ofCount: l)` are both `n` at the given `file` and + /// `line`. + func check( + cHas n: Int, + combinationsOfLengths l: R, + file: StaticString = #filePath, line: UInt = #line) where R.Bound == Int + { + check(c.combinations(ofCount: l), countsAre: n, file: file, line: line) + } + + check(cHas: 1, combinationsOfLength: 0) + check(cHas: 4, combinationsOfLength: 1) + check(cHas: 6, combinationsOfLength: 2) + check(cHas: 1, combinationsOfLength: 4) + + check(cHas: 1, combinationsOfLengths: 0...0) + check(cHas: 4, combinationsOfLengths: 1...1) + check(cHas: 10, combinationsOfLengths: 1...2) + check(cHas: 14, combinationsOfLengths: 1...3) + check(cHas: 11, combinationsOfLengths: 2...4) + + // `k` greater than element count results in same number of combinations + check(cHas: 5, combinationsOfLengths: 3...10) // `k` greater than element count results in same number of combinations - let c10 = c.combinations(ofCount: 3...10).count - XCTAssertEqual(c10, 5) - - // `k` greater than element count results in same number of combinations - let c11 = c.combinations(ofCount: 4...10).count - XCTAssertEqual(c11, 1) + check(cHas: 1, combinationsOfLengths: 4...10) // `k` entirely greater than element count results in no combinations - let c12 = c.combinations(ofCount: 5...10).count - XCTAssertEqual(c12, 0) + check(cHas: 0, combinationsOfLengths: 5...10) - let c13 = c.combinations(ofCount: 0...).count - XCTAssertEqual(c13, 16) - - let c14 = c.combinations(ofCount: ...3).count - XCTAssertEqual(c14, 15) - - let c15 = c.combinations(ofCount: 0...).count - XCTAssertEqual(c15, 16) + check(cHas: 16, combinationsOfLengths: 0...) + check(cHas: 15, combinationsOfLengths: ...3) } func testCombinations() { From 9e3900be495400075bbe75a41a92895a60aa03d3 Mon Sep 17 00:00:00 2001 From: Dimitris Apostolou Date: Wed, 7 Feb 2024 08:18:57 +0200 Subject: [PATCH 18/23] Fix typos (#222) --- Guides/Keyed.md | 2 +- Sources/Algorithms/Documentation.docc/MinAndMax.md | 2 +- Sources/Algorithms/Split.swift | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Guides/Keyed.md b/Guides/Keyed.md index b2b72b4..33c5f08 100644 --- a/Guides/Keyed.md +++ b/Guides/Keyed.md @@ -71,7 +71,7 @@ Calling `keyed(by:)` is an O(_n_) operation. #### Alternative names -Kotlin's `associatedBy` naming is a good alterative, and matches the past tense of [Swift's API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/), though perhaps we'd spell it `associated(by:)`. +Kotlin's `associatedBy` naming is a good alternative, and matches the past tense of [Swift's API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/), though perhaps we'd spell it `associated(by:)`. #### Customization points diff --git a/Sources/Algorithms/Documentation.docc/MinAndMax.md b/Sources/Algorithms/Documentation.docc/MinAndMax.md index 56e2cc8..50c7668 100644 --- a/Sources/Algorithms/Documentation.docc/MinAndMax.md +++ b/Sources/Algorithms/Documentation.docc/MinAndMax.md @@ -16,7 +16,7 @@ or a specific number of elements at the minimum and maximum. - ``Swift/Sequence/max(count:sortedBy:)`` - ``Swift/Collection/max(count:sortedBy:)`` -### Finding the Minimum and Maximum Elements Simulataneously +### Finding the Minimum and Maximum Elements Simultaneously - ``Swift/Sequence/minAndMax()`` - ``Swift/Sequence/minAndMax(by:)`` diff --git a/Sources/Algorithms/Split.swift b/Sources/Algorithms/Split.swift index a1e941a..81c8cb0 100644 --- a/Sources/Algorithms/Split.swift +++ b/Sources/Algorithms/Split.swift @@ -512,7 +512,7 @@ extension SplitCollection: Collection { var subsequenceStart = i.baseRange.upperBound if subsequenceStart < base.endIndex { // If we're not already at the end of the base collection, the previous - // susequence ended with a separator. Start searching for the next + // subsequence ended with a separator. Start searching for the next // subsequence at the following element. subsequenceStart = base.index(after: i.baseRange.upperBound) } From 82ee335a4891469d887a8a3dd953afadd6e65ab2 Mon Sep 17 00:00:00 2001 From: Takumi Muraishi Date: Sat, 17 Feb 2024 15:58:00 +0900 Subject: [PATCH 19/23] Fix typo in TestUtilities.swift (#223) --- Tests/SwiftAlgorithmsTests/TestUtilities.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/SwiftAlgorithmsTests/TestUtilities.swift b/Tests/SwiftAlgorithmsTests/TestUtilities.swift index 68870bb..fbd70be 100644 --- a/Tests/SwiftAlgorithmsTests/TestUtilities.swift +++ b/Tests/SwiftAlgorithmsTests/TestUtilities.swift @@ -216,7 +216,7 @@ extension IndexValidator { /// - expectedCount: /// /// - Complexity: O(*n*^3) where *n* is the length of the collection if the - /// collection conforms to `RandomAccesCollection`, otherwise O(*n*^4). + /// collection conforms to `RandomAccessCollection`, otherwise O(*n*^4). func validate( _ collection: C, expectedCount: Int? = nil, From 33abb694280321a84aa7dc9806de284afb8ca226 Mon Sep 17 00:00:00 2001 From: Marcos Griselli <14804033+marcosgriselli@users.noreply.github.com> Date: Sat, 9 Mar 2024 11:35:42 -0800 Subject: [PATCH 20/23] Remove @_implementationOnly annotations (#225) Signed-off-by: Marcos Griselli --- Sources/Algorithms/RandomSample.swift | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Sources/Algorithms/RandomSample.swift b/Sources/Algorithms/RandomSample.swift index 933269d..72a3322 100644 --- a/Sources/Algorithms/RandomSample.swift +++ b/Sources/Algorithms/RandomSample.swift @@ -10,8 +10,14 @@ //===----------------------------------------------------------------------===// // For log(_:) and root(_:_:) +#if swift(>=5.11) +internal import RealModule +#elseif swift(>=5.10) +import RealModule +#else @_implementationOnly import RealModule +#endif //===----------------------------------------------------------------------===// // randomStableSample(count:) From ae92f2b33f5a7bfe1a315c644aedd161ae0ca87e Mon Sep 17 00:00:00 2001 From: jerry Date: Fri, 12 Apr 2024 16:09:42 +0800 Subject: [PATCH 21/23] Update Suffix.md Fix 'Suffix.md' example code --- Guides/Suffix.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Guides/Suffix.md b/Guides/Suffix.md index f772f3c..2f2b5b8 100644 --- a/Guides/Suffix.md +++ b/Guides/Suffix.md @@ -9,7 +9,7 @@ collection until predicate returns `false` and skipping the remaining elements. This example uses `suffix(while: )` to iterate through collection of integers from the end until the predicate returns false, in this case when `$0 <= 5` ```swift -(0...10).suffix(while: { $0 > 5 } // == [6,7,8,9,10] +(0...10).suffix(while: { $0 > 5 }) // == [6,7,8,9,10] ``` ## Detailed Design From 34b1705efd40fa47ace0d02d0ce89872bc53060d Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Tue, 7 May 2024 12:53:17 -0700 Subject: [PATCH 22/23] Clarify the docs for `partitioned(by:)` (#228) --- Sources/Algorithms/Partition.swift | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Sources/Algorithms/Partition.swift b/Sources/Algorithms/Partition.swift index 178bd4c..181547e 100644 --- a/Sources/Algorithms/Partition.swift +++ b/Sources/Algorithms/Partition.swift @@ -210,8 +210,8 @@ extension Collection { //===----------------------------------------------------------------------===// extension Sequence { - /// Returns two arrays containing, in order, the elements of the sequence that - /// do and don’t satisfy the given predicate. + /// Returns two arrays containing the elements of the sequence that + /// don’t and do satisfy the given predicate, respectively. /// /// In this example, `partitioned(by:)` is used to separate the input based on /// whether a name is shorter than five characters: @@ -230,7 +230,9 @@ extension Sequence { /// /// - Returns: Two arrays with all of the elements of the receiver. The /// first array contains all the elements that `predicate` didn’t allow, and - /// the second array contains all the elements that `predicate` allowed. + /// the second array contains all the elements that `predicate` allowed. The + /// order of the elements in the arrays matches the order of the elements in + /// the original sequence. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable @@ -253,8 +255,8 @@ extension Sequence { } extension Collection { - /// Returns two arrays containing, in order, the elements of the collection - /// that do and don’t satisfy the given predicate. + /// Returns two arrays containing the elements of the collection that + /// don’t and do satisfy the given predicate, respectively. /// /// In this example, `partitioned(by:)` is used to separate the input based on /// whether a name is shorter than five characters. @@ -273,7 +275,9 @@ extension Collection { /// /// - Returns: Two arrays with all of the elements of the receiver. The /// first array contains all the elements that `predicate` didn’t allow, and - /// the second array contains all the elements that `predicate` allowed. + /// the second array contains all the elements that `predicate` allowed. The + /// order of the elements in the arrays matches the order of the elements in + /// the original collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable From 34eec0dd27ba4b539fe01e61fac07c9227c65a63 Mon Sep 17 00:00:00 2001 From: Nate Cook Date: Wed, 21 Aug 2024 17:19:30 -0500 Subject: [PATCH 23/23] Update project to depend on Swift 5.7 (#240) --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 30684ba..8dcb18c 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.4 +// swift-tools-version:5.7 //===----------------------------------------------------------------------===// // // This source file is part of the Swift Algorithms open source project