Compare commits

..
10 Commits
29 changed files with 109 additions and 1170 deletions

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
version: 1
builder:
configs:
- documentation_targets: [Algorithms]
+2 -51
View File
@@ -12,49 +12,6 @@ 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 ## [1.0.0] - 2021-09-08
### Changes ### Changes
@@ -312,8 +269,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
<!-- Link references for releases --> <!-- Link references for releases -->
[Unreleased]: https://github.com/apple/swift-algorithms/compare/1.1.0...HEAD [Unreleased]: https://github.com/apple/swift-algorithms/compare/1.0.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 [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.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 [0.2.0]: https://github.com/apple/swift-algorithms/compare/0.1.1...0.2.0
@@ -343,7 +299,6 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
[#85]: https://github.com/apple/swift-algorithms/pull/85 [#85]: https://github.com/apple/swift-algorithms/pull/85
[#90]: https://github.com/apple/swift-algorithms/pull/90 [#90]: https://github.com/apple/swift-algorithms/pull/90
[#91]: https://github.com/apple/swift-algorithms/pull/91 [#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 [#104]: https://github.com/apple/swift-algorithms/pull/104
[#106]: https://github.com/apple/swift-algorithms/pull/106 [#106]: https://github.com/apple/swift-algorithms/pull/106
[#112]: https://github.com/apple/swift-algorithms/pull/112 [#112]: https://github.com/apple/swift-algorithms/pull/112
@@ -352,7 +307,6 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
[#125]: https://github.com/apple/swift-algorithms/pull/125 [#125]: https://github.com/apple/swift-algorithms/pull/125
[#130]: https://github.com/apple/swift-algorithms/pull/130 [#130]: https://github.com/apple/swift-algorithms/pull/130
[#138]: https://github.com/apple/swift-algorithms/pull/138 [#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 [#162]: https://github.com/apple/swift-algorithms/pull/162
<!-- Link references for contributors --> <!-- Link references for contributors -->
@@ -363,13 +317,11 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
[CTMacUser]: https://github.com/apple/swift-algorithms/commits?author=CTMacUser [CTMacUser]: https://github.com/apple/swift-algorithms/commits?author=CTMacUser
[danielctull]: https://github.com/apple/swift-algorithms/commits?author=danielctull [danielctull]: https://github.com/apple/swift-algorithms/commits?author=danielctull
[dhruvshah8]: https://github.com/apple/swift-algorithms/commits?author=dhruvshah8 [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 [egorzhdan]: https://github.com/apple/swift-algorithms/commits?author=egorzhdan
[fedeci]: https://github.com/apple/swift-algorithms/commits?author=fedeci [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 [hashemi]: https://github.com/apple/swift-algorithms/commits?author=hashemi
[iainsmith]: https://github.com/apple/swift-algorithms/commits?author=iainsmith
[IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen [IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen
[iainsmith]: https://github.com/apple/swift-algorithms/commits?author=iainsmith
[iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7 [iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7
[karwa]: https://github.com/apple/swift-algorithms/commits?author=karwa [karwa]: https://github.com/apple/swift-algorithms/commits?author=karwa
[kylemacomber]: https://github.com/apple/swift-algorithms/commits?author=kylemacomber [kylemacomber]: https://github.com/apple/swift-algorithms/commits?author=kylemacomber
@@ -381,7 +333,6 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
[mpangburn]: https://github.com/apple/swift-algorithms/commits?author=mpangburn [mpangburn]: https://github.com/apple/swift-algorithms/commits?author=mpangburn
[natecook1000]: https://github.com/apple/swift-algorithms/commits?author=natecook1000 [natecook1000]: https://github.com/apple/swift-algorithms/commits?author=natecook1000
[nordicio]: https://github.com/apple/swift-algorithms/commits?author=nordicio [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 [ollieatkinson]: https://github.com/apple/swift-algorithms/commits?author=ollieatkinson
[pmtao]: https://github.com/apple/swift-algorithms/commits?author=pmtao [pmtao]: https://github.com/apple/swift-algorithms/commits?author=pmtao
[Qata]: https://github.com/apple/swift-algorithms/commits?author=Qata [Qata]: https://github.com/apple/swift-algorithms/commits?author=Qata
+39 -56
View File
@@ -3,16 +3,16 @@
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Chunked.swift) | [[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)] [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ChunkedTests.swift)]
Break a collection into nonoverlapping subsequences: Break a collection into subsequences where consecutive elements pass a binary
predicate, or where all elements in each chunk project to the same value.
* `chunked(by:)` forms chunks of consecutive elements that pass a binary predicate, Also includes a `chunks(ofCount:)` that breaks a collection into subsequences
* `chunked(on:)` forms chunks of consecutive elements that project to equal values, of a given `count`.
* `chunks(ofCount:)` forms chunks of a given size, and
* `evenlyChunked(in:)` forms a given number of equally-sized chunks.
`chunked(by:)` uses a binary predicate to test consecutive elements, separating There are two variations of the `chunked` method: `chunked(by:)` and
chunks where the predicate returns `false`. For example, you can chunk a `chunked(on:)`. `chunked(by:)` uses a binary predicate to test consecutive
collection into ascending sequences using this method: elements, separating chunks where the predicate returns `false`. For example,
you can chunk a collection into ascending sequences using this method:
```swift ```swift
let numbers = [10, 20, 30, 10, 40, 40, 10, 20] let numbers = [10, 20, 30, 10, 40, 40, 10, 20]
@@ -31,10 +31,11 @@ let chunks = names.chunked(on: \.first!)
// [("D", ["David"]), ("K", ["Kyle", "Karoy"]), ("N", ["Nate"])] // [("D", ["David"]), ("K", ["Kyle", "Karoy"]), ("N", ["Nate"])]
``` ```
The `chunks(ofCount:)` method takes a `count` parameter (required to be > 0) and The `chunks(ofCount:)` method takes a `count` parameter (greater than zero)
separates the collection into chunks of this given count. If the length of the and separates the collection into chunks of this given count. If the `count`
collection is a multiple of the `count` parameter, all chunks will have the parameter is evenly divided by the count of the base `Collection`, all the
a count equal to the parameter. Otherwise, the last chunk will contain the remaining elements. chunks will have a count equal to the parameter. Otherwise, the last chunk will
contain the remaining elements.
```swift ```swift
let names = ["David", "Kyle", "Karoy", "Nate"] let names = ["David", "Kyle", "Karoy", "Nate"]
@@ -45,26 +46,11 @@ let remaining = names.chunks(ofCount: 3)
// equivalent to [["David", "Kyle", "Karoy"], ["Nate"]] // equivalent to [["David", "Kyle", "Karoy"], ["Nate"]]
``` ```
The `chunks(ofCount:)` method was previously [proposed](proposal) for inclusion The `chunks(ofCount:)` is the subject of an [existing SE proposal][proposal].
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, When "chunking" a collection, the entire collection is included in the result,
unlike the `split` family of methods, where separators are dropped. unlike the `split` family of methods, where separators are dropped.
Joining the result of a chunking method call results in a collection equivalent Joining the result of a chunking method call recreates the original collection.
to the original.
```swift ```swift
c.elementsEqual(c.chunked(...).joined()) c.elementsEqual(c.chunked(...).joined())
@@ -75,45 +61,42 @@ c.elementsEqual(c.chunked(...).joined())
## Detailed Design ## Detailed Design
The four methods are added to `Collection`, with matching versions of The three methods are added as extension to `Collection`. `chunked(by:)` and
`chunked(by:)` and `chunked(on:)` that return a lazy wrapper added to `chunked(on:)` are eager by default, both with a matching version that return a
`LazyCollectionProtocol`. lazy wrapper added to `LazySequenceProtocol`.
```swift ```swift
extension Collection { extension Collection {
public func chunked( public func chunked(
by belongInSameGroup: (Element, Element) -> Bool by belongInSameGroup: (Element, Element) -> Bool
) -> [SubSequence] ) -> [SubSequence]
public func chunked<Subject: Equatable>( public func chunked<Subject: Equatable>(
on projection: (Element) -> Subject on projection: (Element) -> Subject
) -> [SubSequence] ) -> [(Subject, SubSequence)]
public func chunks(ofCount count: Int) -> ChunkedByCount<Self> public func chunks(ofCount count: Int) -> ChunksOfCountCollection<Self>
public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection<Self>
} }
extension LazyCollectionProtocol { extension LazySequenceProtocol where Self: Collection, Elements: Collection {
public func chunked( public func chunked(
by belongInSameGroup: @escaping (Element, Element) -> Bool by belongInSameGroup: @escaping (Element, Element) -> Bool
) -> ChunkedByCollection<Elements> ) -> ChunkedByCollection<Elements, Element>
public func chunked<Subject: Equatable>( public func chunked<Subject: Equatable>(
on projection: @escaping (Element) -> Subject on projection: @escaping (Element) -> Subject
) -> ChunkedOnCollection<Elements, Subject> ) -> ChunkedOnCollection<Elements, Subject>
} }
``` ```
Each of the "chunked" collection types are bidirectional when the wrapped The `ChunkedByCollection`, `ChunkedOnCollection`, and `ChunksOfCountCollection`
collection is bidirectional. `ChunksOfCountCollection` and types are bidirectional when the wrapped collection is bidirectional.
`EvenlyChunkedCollection` also conform to `RandomAccessCollection` and `ChunksOfCountCollection` also conforms to `LazySequenceProtocol` when the base
`LazySequenceProtocol` when their base collections conform. collection conforms.
### Complexity ### Complexity
The eager methods are O(_n_) where _n_ is the number of elements in the The eager methods are O(_n_), the lazy methods are O(_1_).
collection. The lazy methods are O(_n_) because the start index is pre-computed.
### Naming ### Naming
@@ -137,5 +120,5 @@ into potentially overlapping subsequences.
**Ruby:** Ruby’s `Enumerable` class defines `chunk_while` and `chunk`, which map **Ruby:** Ruby’s `Enumerable` class defines `chunk_while` and `chunk`, which map
to the proposed `chunked(by:)` and `chunked(on:)` methods. to the proposed `chunked(by:)` and `chunked(on:)` methods.
**Rust:** Rust defines a variety of size-based `chunks` methods, of which the **Rust:** Rust defines a variety of size-based `chunks` methods, but doesn’t
standard version corresponds to the `chunks(ofCount:)` method defined here. include any with the functionality described here.
+1 -24
View File
@@ -42,20 +42,6 @@ let p = numbers.partitioningIndex(where: { $0.isMultiple(of: 20) })
// numbers[p...] = [20, 40, 60] // numbers[p...] = [20, 40, 60]
``` ```
The standard library’s existing `filter(_:)` method provides functionality to
get the elements that do match a given predicate. `partitioned(by:)` returns
both the elements that match the predicate as well as those that don’t, as a
tuple.
```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"]"
```
## Detailed Design ## Detailed Design
All mutating methods are declared as extensions to `MutableCollection`. All mutating methods are declared as extensions to `MutableCollection`.
@@ -83,17 +69,11 @@ extension Collection {
where belongsInSecondPartition: (Element) throws -> Bool where belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index ) rethrows -> Index
} }
extension Sequence {
public func partitioned(
by predicate: (Element) throws -> Bool
) rethrows -> (falseElements: [Element], trueElements: [Element])
}
``` ```
### Complexity ### Complexity
The existing partition is an O(_n_) operation, where _n_ is the length of the The existing partition is an O(_n_) operations, where _n_ is the length of the
range to be partitioned, while the stable partition is O(_n_ log _n_). Both range to be partitioned, while the stable partition is O(_n_ log _n_). Both
partitions have algorithms with improved performance for bidirectional partitions have algorithms with improved performance for bidirectional
collections, so it would be ideal for those to be customization points were they collections, so it would be ideal for those to be customization points were they
@@ -102,9 +82,6 @@ to eventually land in the standard library.
`partitioningIndex(where:)` is a slight generalization of a binary search, and `partitioningIndex(where:)` is a slight generalization of a binary search, and
is an O(log _n_) operation for random-access collections; O(_n_) otherwise. is an O(log _n_) operation for random-access collections; O(_n_) otherwise.
`partitioned(by:)` is an O(_n_) operation, where _n_ is the number of elements
in the original sequence.
### Comparison with other languages ### Comparison with other languages
**C++:** The `<algorithm>` library defines `partition`, `stable_partition`, and **C++:** The `<algorithm>` library defines `partition`, `stable_partition`, and
+2 -2
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.4 // swift-tools-version:5.1
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// //
// This source file is part of the Swift Algorithms open source project // This source file is part of the Swift Algorithms open source project
@@ -20,7 +20,7 @@ let package = Package(
targets: ["Algorithms"]), targets: ["Algorithms"]),
], ],
dependencies: [ dependencies: [
.package(url: "https://github.com/apple/swift-numerics.git", from: "1.0.0"), .package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"),
], ],
targets: [ targets: [
.target( .target(
+1 -2
View File
@@ -27,7 +27,6 @@ Read more about the package, and the intent behind it, in the [announcement on s
#### Subsetting operations #### 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. - [`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. - [`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. - [`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. - [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
@@ -73,7 +72,7 @@ Finally, add `import Algorithms` to your source code.
## Source Stability ## Source Stability
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 Swift Numerics 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 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.
+2 -13
View File
@@ -10,8 +10,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
extension Sequence { extension Sequence {
/// Returns a sequence of overlapping adjacent pairs of the elements of this /// Creates a sequence of adjacent pairs of elements from this sequence.
/// sequence.
/// ///
/// In the `AdjacentPairsSequence` returned by this method, the elements of /// 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 /// the *i*th pair are the *i*th and *(i+1)*th elements of the underlying
@@ -25,11 +24,6 @@ extension Sequence {
/// // Prints "(2, 3)" /// // Prints "(2, 3)"
/// // Prints "(3, 4)" /// // Prints "(3, 4)"
/// // Prints "(4, 5)" /// // Prints "(4, 5)"
///
/// The resulting sequence is empty when called on an empty or single-element
/// sequence.
///
/// - Complexity: O(1)
@inlinable @inlinable
public func adjacentPairs() -> AdjacentPairsSequence<Self> { public func adjacentPairs() -> AdjacentPairsSequence<Self> {
AdjacentPairsSequence(base: self) AdjacentPairsSequence(base: self)
@@ -37,7 +31,7 @@ extension Sequence {
} }
extension Collection { extension Collection {
/// Returns a collection of overlapping adjacent pairs of the elements of this /// A collection of adjacent pairs of elements built from an underlying
/// collection. /// collection.
/// ///
/// In an `AdjacentPairsCollection`, the elements of the *i*th pair are the /// In an `AdjacentPairsCollection`, the elements of the *i*th pair are the
@@ -52,11 +46,6 @@ extension Collection {
/// // Prints "(2, 3)" /// // Prints "(2, 3)"
/// // Prints "(3, 4)" /// // Prints "(3, 4)"
/// // Prints "(4, 5)" /// // Prints "(4, 5)"
///
/// The resulting collection is empty when called on an empty or
/// single-element collection.
///
/// - Complexity: O(1)
@inlinable @inlinable
public func adjacentPairs() -> AdjacentPairsCollection<Self> { public func adjacentPairs() -> AdjacentPairsCollection<Self> {
AdjacentPairsCollection(base: self) AdjacentPairsCollection(base: self)
+27 -314
View File
@@ -198,210 +198,6 @@ extension ChunkedOnCollection: BidirectionalCollection
extension ChunkedOnCollection: LazyCollectionProtocol {} extension ChunkedOnCollection: LazyCollectionProtocol {}
/// A collection wrapper that evenly breaks a collection into a given number of
/// chunks.
public struct EvenlyChunkedCollection<Base: Collection> {
/// 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 EvenlyChunkedCollection {
/// 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..<end, offset: offset)
}
/// Returns the index that corresponds to the chunk that ends at the given
/// base index.
@inlinable
internal func indexOfChunk(endingAt end: Base.Index, offset: Int) -> Index {
let start = startOfChunk(endingAt: end, offset: offset)
return Index(start..<end, offset: offset)
}
}
extension EvenlyChunkedCollection: Collection {
public struct Index: Comparable {
/// The range corresponding to the chunk at this position.
@usableFromInline
internal var baseRange: Range<Base.Index>
/// 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<Base.Index>, 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..<firstUpperBound, offset: 0)
}
@inlinable
public var endIndex: Index {
Index(base.endIndex..<base.endIndex, offset: numberOfChunks)
}
@inlinable
public func index(after i: Index) -> 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..<distance).contains(self.distance(from: i, to: limit)) {
return nil
}
} else {
if (0..<(-distance)).contains(self.distance(from: limit, to: i)) {
return nil
}
}
return index(i, offsetBy: distance)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
end.offset - start.offset
}
}
extension EvenlyChunkedCollection.Index: Hashable where Base.Index: Hashable {}
extension EvenlyChunkedCollection: 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 EvenlyChunkedCollection: RandomAccessCollection
where Base: RandomAccessCollection {}
extension EvenlyChunkedCollection: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension EvenlyChunkedCollection: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// lazy.chunked(by:) / lazy.chunked(on:) // lazy.chunked(by:) / lazy.chunked(on:)
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
@@ -410,9 +206,6 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
/// Returns a lazy collection of subsequences of this collection, chunked by /// Returns a lazy collection of subsequences of this collection, chunked by
/// the given predicate. /// 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. /// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable @inlinable
public func chunked( public func chunked(
@@ -425,11 +218,7 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
} }
/// Returns a lazy collection of subsequences of this collection, chunked by /// Returns a lazy collection of subsequences of this collection, chunked by
/// grouping elements that project to equal values. /// grouping elements that project to the same value.
///
/// - 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. /// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable @inlinable
@@ -450,10 +239,6 @@ extension Collection {
/// Returns a collection of subsequences of this collection, chunked by the /// Returns a collection of subsequences of this collection, chunked by the
/// given predicate. /// 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. /// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable @inlinable
public func chunked( public func chunked(
@@ -481,11 +266,7 @@ extension Collection {
} }
/// Returns a collection of subsequences of this collection, chunked by /// Returns a collection of subsequences of this collection, chunked by
/// grouping elements that project to equal values. /// grouping elements that project to the same value.
///
/// - 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. /// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable @inlinable
@@ -522,7 +303,7 @@ extension Collection {
/// A collection that presents the elements of its base collection in /// A collection that presents the elements of its base collection in
/// `SubSequence` chunks of any given count. /// `SubSequence` chunks of any given count.
/// ///
/// A `ChunksOfCountCollection` is a lazy view on the base `Collection`, but it /// A `ChunksOfCountCollection` is a lazy view on the base Collection, but it
/// does not implicitly confer laziness on algorithms applied to its result. In /// does not implicitly confer laziness on algorithms applied to its result. In
/// other words, for ordinary collections `c`: /// other words, for ordinary collections `c`:
/// ///
@@ -705,11 +486,11 @@ extension ChunksOfCountCollection {
_ i: Index, _ distance: Int _ i: Index, _ distance: Int
) -> Int { ) -> Int {
if i == endIndex { if i == endIndex {
let remainder = base.count % chunkCount let remainder = base.count%chunkCount
// We have to take it into account when calculating offsets. // We have to take it into account when calculating offsets.
if remainder != 0 { if remainder != 0 {
// Distance "minus" one (at this point distance is negative) because we // Distance "minus" one(at this point distance is negative) because we
// need to adjust for the last position that have a variadic (remainder) // need to adjust for the last position that have a variadic(remainder)
// number of elements. // number of elements.
return ((distance + 1) * chunkCount) - remainder return ((distance + 1) * chunkCount) - remainder
} }
@@ -731,7 +512,7 @@ extension ChunksOfCountCollection {
) )
} }
// Helper to compute `index(offsetBy:)` index. // Helper to compute index(offsetBy:) index.
@inlinable @inlinable
internal func makeOffsetIndex( internal func makeOffsetIndex(
from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int, from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int,
@@ -744,13 +525,13 @@ extension ChunksOfCountCollection {
if let limit = limit { if let limit = limit {
if baseIdx == nil { if baseIdx == nil {
// If we passed the bounds while advancing forward, and the limit is the // If we past the bounds while advancing forward and the limit is the
// `endIndex`, since the computation on `base` don't take into account // `endIndex`, since the computation on base don't take into account the
// the remainder, we have to make sure that passing the bound was // remainder, we have to make sure that passing the bound was because of
// because of the distance not just because of a remainder. Special // the distance not just because of a remainder. Special casing is less
// casing is less expensive than always using `count` (which could be // expensive than always use count(which could be O(n) for non-random
// O(n) for non-random access collection base) to compute the base // access collection base) to compute the base distance taking remainder
// distance taking remainder into account. // into account.
if baseDistance > 0 && limit == endIndex { if baseDistance > 0 && limit == endIndex {
if self.distance(from: i, to: limit) < distance { if self.distance(from: i, to: limit) < distance {
return nil return nil
@@ -777,37 +558,22 @@ extension ChunksOfCountCollection {
} }
extension Collection { extension Collection {
/// Returns a collection of subsequences, each with up to the specified /// Returns a `ChunksOfCountCollection<Self>` view presenting the elements in
/// length. /// chunks with count of the given count parameter.
/// ///
/// If the number of elements in the collection is evenly divided by `count`, /// - Parameter count: The size of the chunks. If the count parameter is
/// then every chunk will have a length equal to `count`. Otherwise, every /// evenly divided by the count of the base `Collection` all the chunks will
/// chunk but the last will have a length equal to `count`, with the /// have the count equals to size. Otherwise, the last chunk will contain
/// remaining elements in the last chunk. /// the remaining elements.
/// ///
/// let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] /// let c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
/// for chunk in numbers.chunks(ofCount: 5) { /// print(c.chunks(ofCount: 5).map(Array.init))
/// print(chunk) /// // [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
/// }
/// // [1, 2, 3, 4, 5]
/// // [6, 7, 8, 9, 10]
/// ///
/// for chunk in numbers.chunks(ofCount: 3) { /// print(c.chunks(ofCount: 3).map(Array.init))
/// print(chunk) /// // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
/// }
/// // [1, 2, 3]
/// // [4, 5, 5]
/// // [7, 8, 9]
/// // [10]
///
/// - 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`.
/// ///
/// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable @inlinable
public func chunks(ofCount count: Int) -> ChunksOfCountCollection<Self> { public func chunks(ofCount count: Int) -> ChunksOfCountCollection<Self> {
precondition(count > 0, "Cannot chunk with count <= 0!") precondition(count > 0, "Cannot chunk with count <= 0!")
@@ -817,58 +583,5 @@ extension Collection {
extension ChunksOfCountCollection.Index: Hashable where Base.Index: Hashable {} extension ChunksOfCountCollection.Index: Hashable where Base.Index: Hashable {}
extension ChunksOfCountCollection: LazySequenceProtocol extension ChunksOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
extension ChunksOfCountCollection: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
//===----------------------------------------------------------------------===//
// evenlyChunked(in:)
//===----------------------------------------------------------------------===//
extension 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
/// 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!"
///
/// 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) -> EvenlyChunkedCollection<Self> {
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 EvenlyChunkedCollection(base: self, numberOfChunks: count)
}
}
+2 -2
View File
@@ -289,8 +289,8 @@ extension Collection {
/// - Parameter k: The number of elements to include in each combination. /// - Parameter k: The number of elements to include in each combination.
/// ///
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n* /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since /// is the number of elements in the base collection, since
/// `CombinationsSequence` accesses the `count` of the base collection. /// `CombinationsSequence` accesses the `count` of the base collection.
@inlinable @inlinable
public func combinations(ofCount k: Int) -> CombinationsSequence<Self> { public func combinations(ofCount k: Int) -> CombinationsSequence<Self> {
precondition(k >= 0, "Can't have combinations with a negative number of elements.") precondition(k >= 0, "Can't have combinations with a negative number of elements.")
@@ -1,41 +0,0 @@
# ``Algorithms``
**Swift Algorithms** is an open-source package of sequence and collection algorithms,
along with their related types.
## Overview
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
- <doc:CombinationsPermutations>
- <doc:SlicingSplitting>
- <doc:Chunking>
- <doc:Joining>
- <doc:Extending>
- <doc:Trimming>
- <doc:Sampling>
- <doc:MinAndMax>
- <doc:Selecting>
- <doc:Filtering>
- <doc:Reductions>
- <doc:Partitioning>
@@ -1,40 +0,0 @@
# Chunking
Break collections into consecutive chunks by length, count, or based on closure-based logic.
## 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
- ``Swift/Collection/chunks(ofCount:)``
- ``Swift/Collection/evenlyChunked(in:)``
### Chunking a Collection by Predicate
- ``Swift/Collection/chunked(by:)``
- ``Swift/LazySequenceProtocol/chunked(by:)``
### Chunking a Collection by Subject
- ``Swift/Collection/chunked(on:)``
- ``Swift/LazySequenceProtocol/chunked(on:)``
### Supporting Types
- ``ChunkedByCollection``
- ``ChunkedOnCollection``
- ``ChunksOfCountCollection``
- ``EvenlyChunkedCollection``
@@ -1,32 +0,0 @@
# 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``
@@ -1,14 +0,0 @@
# DeprecatedScan
These methods are deprecated; use the `reductions` family of methods instead.
See: <doc:Reductions>
## Topics
- ``Swift/Sequence/scan(_:)``
- ``Swift/Sequence/scan(_:_:)``
- ``Swift/Sequence/scan(into:_:)``
- ``Swift/LazySequenceProtocol/scan(_:)``
- ``Swift/LazySequenceProtocol/scan(_:_:)``
- ``Swift/LazySequenceProtocol/scan(into:_:)``
@@ -1,42 +0,0 @@
# Extending
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
- ``chain(_:_:)``
### Cycling a Collection
- ``Swift/Collection/cycled()``
- ``Swift/Collection/cycled(times:)``
### Supporting Types
- ``Chain2Sequence``
- ``CycledSequence``
- ``CycledTimesCollection``
@@ -1,41 +0,0 @@
# Filtering
Remove duplicated elements or strip the `nil` values from a sequence or collection.
## Overview
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
### Uniquing 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``
@@ -1,35 +0,0 @@
# 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``
@@ -1,23 +0,0 @@
# 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:)``
@@ -1,63 +0,0 @@
# 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.
## 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
- ``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:)``
@@ -1,35 +0,0 @@
# Reductions
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(_:)``
- ``Swift/Sequence/reductions(_:_:)``
- ``Swift/Sequence/reductions(into:_:)``
- ``Swift/LazySequenceProtocol/reductions(_:)``
- ``Swift/LazySequenceProtocol/reductions(_:_:)``
- ``Swift/LazySequenceProtocol/reductions(into:_:)``
### Supporting Types
- ``InclusiveReductionsSequence``
- ``ExclusiveReductionsSequence``
### Deprecated Methods
- <doc:DeprecatedScan>
@@ -1,17 +0,0 @@
# 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:)``
@@ -1,25 +0,0 @@
# 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``
@@ -1,29 +0,0 @@
# 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
- ``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``
@@ -1,27 +0,0 @@
# 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:)``
+1 -5
View File
@@ -94,10 +94,6 @@ extension Collection {
/// Returns a collection of pairs *(i, x)*, where *i* represents an index of /// Returns a collection of pairs *(i, x)*, where *i* represents an index of
/// the collection, and *x* represents an element. /// 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 /// This example iterates over the indices and elements of a set, building an
/// array consisting of indices of names with five or fewer letters. /// array consisting of indices of names with five or fewer letters.
/// ///
@@ -109,7 +105,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 @inlinable
public func indexed() -> IndexedCollection<Self> { public func indexed() -> IndexedCollection<Self> {
IndexedCollection(base: self) IndexedCollection(base: self)
+6 -4
View File
@@ -28,9 +28,11 @@ extension Sequence {
while let e = iterator.next() { while let e = iterator.next() {
// To be part of `result`, `e` must be strictly less than `result.last`. // To be part of `result`, `e` must be strictly less than `result.last`.
guard try areInIncreasingOrder(e, result.last!) else { continue } guard try areInIncreasingOrder(e, result.last!) else { continue }
result.removeLast()
let insertionIndex = let insertionIndex =
try result.partitioningIndex { try areInIncreasingOrder(e, $0) } try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
assert(insertionIndex != result.endIndex)
result.removeLast()
result.insert(e, at: insertionIndex) result.insert(e, at: insertionIndex)
} }
@@ -125,7 +127,7 @@ extension Sequence {
/// largest values: /// largest values:
/// ///
/// let numbers = [7, 1, 6, 2, 8, 3, 9] /// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let largestThree = numbers.max(count: 3, sortedBy: <) /// let smallestThree = numbers.max(count: 3, sortedBy: <)
/// // [7, 8, 9] /// // [7, 8, 9]
/// ///
/// If you need to sort a sequence but only need to access its largest /// If you need to sort a sequence but only need to access its largest
@@ -197,7 +199,7 @@ extension Sequence where Element: Comparable {
/// largest values: /// largest values:
/// ///
/// let numbers = [7, 1, 6, 2, 8, 3, 9] /// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let largestThree = numbers.max(count: 3) /// let smallestThree = numbers.max(count: 3)
/// // [7, 8, 9] /// // [7, 8, 9]
/// ///
/// If you need to sort a sequence but only need to access its largest /// If you need to sort a sequence but only need to access its largest
@@ -280,7 +282,7 @@ extension Collection {
/// largest values: /// largest values:
/// ///
/// let numbers = [7, 1, 6, 2, 8, 3, 9] /// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let largestThree = numbers.max(count: 3, sortedBy: <) /// let smallestThree = numbers.max(count: 3, sortedBy: <)
/// // [7, 8, 9] /// // [7, 8, 9]
/// ///
/// If you need to sort a collection but only need to access its largest /// If you need to sort a collection but only need to access its largest
+4 -139
View File
@@ -2,7 +2,7 @@
// //
// This source file is part of the Swift Algorithms open source project // This source file is part of the Swift Algorithms open source project
// //
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors // Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception // Licensed under Apache License v2.0 with Runtime Library Exception
// //
// See https://swift.org/LICENSE.txt for license information // See https://swift.org/LICENSE.txt for license information
@@ -168,8 +168,8 @@ extension MutableCollection where Self: BidirectionalCollection {
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
extension Collection { extension Collection {
/// Returns the start index of the partition of a collection that matches /// Returns the index of the first element in the collection that matches
/// the given predicate. /// the predicate.
/// ///
/// The collection must already be partitioned according to the predicate. /// The collection must already be partitioned according to the predicate.
/// That is, there should be an index `i` where for every element in /// That is, there should be an index `i` where for every element in
@@ -179,8 +179,7 @@ extension Collection {
/// - Parameter belongsInSecondPartition: A predicate that partitions the /// - Parameter belongsInSecondPartition: A predicate that partitions the
/// collection. /// collection.
/// - Returns: The index of the first element in the collection for which /// - Returns: The index of the first element in the collection for which
/// `predicate` returns `true`, or `endIndex` if there are no elements /// `predicate` returns `true`.
/// for which `predicate` returns `true`.
/// ///
/// - Complexity: O(log *n*), where *n* is the length of this collection if /// - Complexity: O(log *n*), where *n* is the length of this collection if
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*). /// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
@@ -205,137 +204,3 @@ extension Collection {
} }
} }
//===----------------------------------------------------------------------===//
// partitioned(by:)
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns two arrays containing, in order, the elements of the sequence that
/// do and don’t satisfy the given predicate.
///
/// In this example, `partitioned(by:)` is used to separate the input based on
/// whether a name is shorter than five characters:
///
/// 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"]"
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the element
/// should be included in the second returned array. Otherwise, the element
/// will appear in the first returned array.
///
/// - 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.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func partitioned(
by predicate: (Element) throws -> Bool
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
var lhs = [Element]()
var rhs = [Element]()
for element in self {
if try predicate(element) {
rhs.append(element)
} else {
lhs.append(element)
}
}
return (lhs, rhs)
}
}
extension Collection {
/// Returns two arrays containing, in order, the elements of the collection
/// that do and don’t satisfy the given predicate.
///
/// In this example, `partitioned(by:)` is used to separate the input based on
/// whether a name is shorter than five characters.
///
/// 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"]"
///
/// - Parameter predicate: A closure that takes an element of the collection
/// as its argument and returns a Boolean value indicating whether the element
/// should be included in the second returned array. Otherwise, the element
/// will appear in the first returned array.
///
/// - 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.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func partitioned(
by predicate: (Element) throws -> Bool
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
guard !self.isEmpty else {
return ([], [])
}
// Since collections have known sizes, we can allocate one array of size
// `self.count`, then insert items at the beginning or end of that contiguous
// block. This way, we don’t have to do any dynamic array resizing. Since we
// insert the right elements on the right side in reverse order, we need to
// reverse them back to the original order at the end.
let count = self.count
// Inside of the `initializer` closure, we set what the actual mid-point is.
// We will use this to partition the single array into two.
var midPoint: Int = 0
let elements = try [Element](
unsafeUninitializedCapacity: count,
initializingWith: { buffer, initializedCount in
var lhs = buffer.baseAddress!
var rhs = lhs + buffer.count
do {
for element in self {
if try predicate(element) {
rhs -= 1
rhs.initialize(to: element)
} else {
lhs.initialize(to: element)
lhs += 1
}
}
precondition(lhs == rhs, """
Collection's `count` differed from the number of elements iterated.
"""
)
let rhsIndex = rhs - buffer.baseAddress!
buffer[rhsIndex...].reverse()
initializedCount = buffer.count
midPoint = rhsIndex
} catch {
let lhsCount = lhs - buffer.baseAddress!
let rhsCount = (buffer.baseAddress! + buffer.count) - rhs
buffer.baseAddress!.deinitialize(count: lhsCount)
rhs.deinitialize(count: rhsCount)
throw error
}
})
let lhs = elements[..<midPoint]
let rhs = elements[midPoint...]
return (
Array(lhs),
Array(rhs)
)
}
}
+19
View File
@@ -0,0 +1,19 @@
//===----------------------------------------------------------*- 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`
-----------------------------------------------------
""")
+3 -33
View File
@@ -87,6 +87,9 @@ 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].lazy.chunked(by: { $1 - $0 == 1 }),
[[1, 2, 3, 4], [6, 7, 8, 9]]) [[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( XCTAssertEqualSequences(
[1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }).reversed(), [1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }).reversed(),
[[6, 7, 8, 9], [1, 2, 3, 4]]) [[6, 7, 8, 9], [1, 2, 3, 4]])
@@ -170,37 +173,4 @@ final class ChunkedTests: XCTestCase {
expectedCount: range.count / i + (range.count % i).signum()) 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<EvenlyChunkedCollection<Range<Int>>>()
[
(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) }
}
} }
@@ -92,26 +92,6 @@ final class PartitionTests: XCTestCase {
} }
} }
func testPartitioningIndexWithEmptyInput() {
let input: [Int] = []
let a = input.partitioningIndex(where: { _ in return true })
XCTAssertEqual(a, input.startIndex)
let b = input.partitioningIndex(where: { _ in return false })
XCTAssertEqual(b, input.endIndex)
}
func testPartitioningIndexWithOneEmptyPartition() {
let input: Range<Int> = (0 ..< 10)
let a = input.partitioningIndex(where: { $0 > 10 })
XCTAssertEqual(a, input.endIndex)
let b = input.partitioningIndex(where: { $0 >= 0 })
XCTAssertEqual(b, input.startIndex)
}
func testPartitionWithSubrangeBidirectionalCollection() { func testPartitionWithSubrangeBidirectionalCollection() {
for length in 10...20 { for length in 10...20 {
let a = Array(0..<length) let a = Array(0..<length)
@@ -153,40 +133,4 @@ final class PartitionTests: XCTestCase {
} }
} }
} }
func testPartitionedWithEmptyInput() {
let input: [Int] = []
let s0 = input.partitioned(by: { _ in return true })
XCTAssertTrue(s0.0.isEmpty)
XCTAssertTrue(s0.1.isEmpty)
}
/// Test the example given in the `partitioned(by:)` documentation
func testPartitionedExample() throws {
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
XCTAssertEqual(longNames, ["Vivien", "Marlon"])
XCTAssertEqual(shortNames, ["Kim", "Karl"])
}
func testPartitionedWithPredicate() throws {
let s0 = ["A", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() })
let s1 = ["a", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() })
let s2 = ["a", "B", "c", "D"].partitioned(by: { $0 == $0.lowercased() })
let s3 = ["a", "B", "c", "d"].partitioned(by: { $0 == $0.lowercased() })
XCTAssertEqual(s0.0, ["A", "B", "C", "D"])
XCTAssertEqual(s0.1, [])
XCTAssertEqual(s1.0, ["B", "C", "D"])
XCTAssertEqual(s1.1, ["a"])
XCTAssertEqual(s2.0, ["B", "D"])
XCTAssertEqual(s2.1, ["a", "c"])
XCTAssertEqual(s3.0, ["B"])
XCTAssertEqual(s3.1, ["a", "c", "d"])
}
} }