mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-22 04:10:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6919dfc30 | ||
|
|
f2fd047eed | ||
|
|
5c54f200e7 | ||
|
|
2e71e228c0 | ||
|
|
328631d60c | ||
|
|
0ebed148c2 | ||
|
|
c8ae549e42 | ||
|
|
dd4e0e70ff | ||
|
|
bcd4f369ac | ||
|
|
4f53c9cf40 | ||
|
|
0d6f943832 | ||
|
|
fc8fdfd4dc | ||
|
|
bfcaaa8758 | ||
|
|
0f81ef4a70 | ||
|
|
de3efbc567 | ||
|
|
df51f1780b | ||
|
|
288d8b00f2 | ||
|
|
aa6349dea0 | ||
|
|
195e0316d7 | ||
|
|
da475ea9af | ||
|
|
19c1d00177 | ||
|
|
e2fa131d62 | ||
|
|
aeead5ab20 | ||
|
|
c5ea9e3e36 | ||
|
|
e195266e1f |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [Algorithms]
|
||||
|
||||
+85
-2
@@ -10,6 +10,75 @@ This project follows semantic versioning.
|
||||
|
||||
*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])
|
||||
|
||||
The 1.2.0 release includes contributions from [amomchilov], [mattyoung], [natecook1000], [stephentyrone], and [ttsugriy].
|
||||
Thank you!
|
||||
|
||||
---
|
||||
|
||||
## [1.1.0] - 2023-10-05
|
||||
|
||||
### 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
|
||||
@@ -269,7 +338,9 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
|
||||
<!-- Link references for releases -->
|
||||
|
||||
[Unreleased]: https://github.com/apple/swift-algorithms/compare/1.0.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
|
||||
[0.2.0]: https://github.com/apple/swift-algorithms/compare/0.1.1...0.2.0
|
||||
@@ -299,6 +370,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,32 +379,42 @@ 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
|
||||
[#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
|
||||
|
||||
<!-- Link references for contributors -->
|
||||
|
||||
[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
|
||||
[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
|
||||
[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
|
||||
[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
|
||||
@@ -344,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
|
||||
@@ -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()
|
||||
|
||||
+56
-39
@@ -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,11 +45,26 @@ 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.
|
||||
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())
|
||||
@@ -61,42 +75,45 @@ 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<Subject: Equatable>(
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: (Element) -> Subject
|
||||
) -> [(Subject, SubSequence)]
|
||||
|
||||
public func chunks(ofCount count: Int) -> ChunksOfCountCollection<Self>
|
||||
) -> [SubSequence]
|
||||
|
||||
public func chunks(ofCount count: Int) -> ChunkedByCount<Self>
|
||||
|
||||
public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection<Self>
|
||||
}
|
||||
|
||||
extension LazySequenceProtocol where Self: Collection, Elements: Collection {
|
||||
public func chunked(
|
||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||
) -> ChunkedByCollection<Elements, Element>
|
||||
extension LazyCollectionProtocol {
|
||||
public func chunked(
|
||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||
) -> ChunkedByCollection<Elements>
|
||||
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: @escaping (Element) -> Subject
|
||||
) -> ChunkedOnCollection<Elements, Subject>
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: @escaping (Element) -> Subject
|
||||
) -> ChunkedOnCollection<Elements, Subject>
|
||||
}
|
||||
```
|
||||
|
||||
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
|
||||
`EvenlyChunkedCollection` also conform to `RandomAccessCollection` and
|
||||
`LazySequenceProtocol` when their base collections conform.
|
||||
|
||||
### 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
|
||||
|
||||
@@ -120,5 +137,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.
|
||||
@@ -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
|
||||
|
||||
@@ -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<GroupKey>(
|
||||
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.
|
||||
@@ -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<Key>(
|
||||
by keyForValue: (Element) throws -> Key
|
||||
) rethrows -> [Key: Element]
|
||||
|
||||
public func keyed<Key>(
|
||||
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`.
|
||||
+24
-1
@@ -42,6 +42,20 @@ let p = numbers.partitioningIndex(where: { $0.isMultiple(of: 20) })
|
||||
// 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
|
||||
|
||||
All mutating methods are declared as extensions to `MutableCollection`.
|
||||
@@ -69,11 +83,17 @@ extension Collection {
|
||||
where belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
public func partitioned(
|
||||
by predicate: (Element) throws -> Bool
|
||||
) rethrows -> (falseElements: [Element], trueElements: [Element])
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
The existing partition is an O(_n_) operations, where _n_ is the length of the
|
||||
The existing partition is an O(_n_) operation, where _n_ is the length of the
|
||||
range to be partitioned, while the stable partition is O(_n_ log _n_). Both
|
||||
partitions have algorithms with improved performance for bidirectional
|
||||
collections, so it would be ideal for those to be customization points were they
|
||||
@@ -82,6 +102,9 @@ to eventually land in the standard library.
|
||||
`partitioningIndex(where:)` is a slight generalization of a binary search, and
|
||||
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
|
||||
|
||||
**C++:** The `<algorithm>` library defines `partition`, `stable_partition`, and
|
||||
|
||||
@@ -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.
|
||||
+50
-29
@@ -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: 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
|
||||
|
||||
+2
-2
@@ -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
|
||||
@@ -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(
|
||||
|
||||
@@ -2,54 +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.
|
||||
- [`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.
|
||||
- [`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.
|
||||
- [`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
|
||||
|
||||
@@ -57,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:
|
||||
@@ -72,10 +53,14 @@ Finally, add `import Algorithms` to your source code.
|
||||
|
||||
## Source Stability
|
||||
|
||||
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 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
|
||||
@@ -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<Self> {
|
||||
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<Self> {
|
||||
AdjacentPairsCollection(base: self)
|
||||
|
||||
@@ -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 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:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
@@ -206,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(
|
||||
@@ -218,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
|
||||
@@ -239,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(
|
||||
@@ -266,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
|
||||
@@ -303,7 +522,7 @@ extension Collection {
|
||||
/// A collection that presents the elements of its base collection in
|
||||
/// `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
|
||||
/// other words, for ordinary collections `c`:
|
||||
///
|
||||
@@ -486,11 +705,11 @@ extension ChunksOfCountCollection {
|
||||
_ i: Index, _ distance: Int
|
||||
) -> Int {
|
||||
if i == endIndex {
|
||||
let remainder = base.count%chunkCount
|
||||
let remainder = base.count % chunkCount
|
||||
// We have to take it into account when calculating offsets.
|
||||
if remainder != 0 {
|
||||
// Distance "minus" one(at this point distance is negative) because we
|
||||
// need to adjust for the last position that have a variadic(remainder)
|
||||
// Distance "minus" one (at this point distance is negative) because we
|
||||
// need to adjust for the last position that have a variadic (remainder)
|
||||
// number of elements.
|
||||
return ((distance + 1) * chunkCount) - remainder
|
||||
}
|
||||
@@ -512,7 +731,7 @@ extension ChunksOfCountCollection {
|
||||
)
|
||||
}
|
||||
|
||||
// Helper to compute index(offsetBy:) index.
|
||||
// Helper to compute `index(offsetBy:)` index.
|
||||
@inlinable
|
||||
internal func makeOffsetIndex(
|
||||
from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int,
|
||||
@@ -525,13 +744,13 @@ extension ChunksOfCountCollection {
|
||||
|
||||
if let limit = limit {
|
||||
if baseIdx == nil {
|
||||
// If we past the bounds while advancing forward and the limit is the
|
||||
// `endIndex`, since the computation on base don't take into account the
|
||||
// remainder, we have to make sure that passing the bound was because of
|
||||
// the distance not just because of a remainder. Special casing is less
|
||||
// expensive than always use count(which could be O(n) for non-random
|
||||
// access collection base) to compute the base distance taking remainder
|
||||
// into account.
|
||||
// If we passed the bounds while advancing forward, and the limit is the
|
||||
// `endIndex`, since the computation on `base` don't take into account
|
||||
// the remainder, we have to make sure that passing the bound was
|
||||
// because of the distance not just because of a remainder. Special
|
||||
// casing is less expensive than always using `count` (which could be
|
||||
// O(n) for non-random access collection base) to compute the base
|
||||
// distance taking remainder into account.
|
||||
if baseDistance > 0 && limit == endIndex {
|
||||
if self.distance(from: i, to: limit) < distance {
|
||||
return nil
|
||||
@@ -558,22 +777,37 @@ extension ChunksOfCountCollection {
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
/// Returns a `ChunksOfCountCollection<Self>` view presenting the elements in
|
||||
/// chunks with count of the given count parameter.
|
||||
/// Returns a collection of subsequences, each with up to 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: 3) {
|
||||
/// print(chunk)
|
||||
/// }
|
||||
/// // [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
|
||||
public func chunks(ofCount count: Int) -> ChunksOfCountCollection<Self> {
|
||||
precondition(count > 0, "Cannot chunk with count <= 0!")
|
||||
@@ -583,5 +817,58 @@ 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 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)
|
||||
}
|
||||
}
|
||||
@@ -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<Self> {
|
||||
precondition(k >= 0, "Can't have combinations with a negative number of elements.")
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# ``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:Keying>
|
||||
- <doc:Sampling>
|
||||
- <doc:MinAndMax>
|
||||
- <doc:Selecting>
|
||||
- <doc:Filtering>
|
||||
- <doc:Reductions>
|
||||
- <doc:Partitioning>
|
||||
@@ -0,0 +1,40 @@
|
||||
# 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``
|
||||
@@ -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``
|
||||
@@ -0,0 +1,14 @@
|
||||
# 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:_:)``
|
||||
@@ -0,0 +1,42 @@
|
||||
# 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``
|
||||
@@ -0,0 +1,41 @@
|
||||
# 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``
|
||||
@@ -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``
|
||||
@@ -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:)``
|
||||
@@ -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:)``
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# 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:)``
|
||||
@@ -0,0 +1,35 @@
|
||||
# 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>
|
||||
@@ -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:)``
|
||||
@@ -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``
|
||||
@@ -0,0 +1,29 @@
|
||||
# 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``
|
||||
@@ -0,0 +1,32 @@
|
||||
# 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:)``
|
||||
|
||||
### Finding Boundaries within a Collection
|
||||
|
||||
- ``Swift/Collection/endOfPrefix(while:)``
|
||||
- ``Swift/BidirectionalCollection/startOfSuffix(while:)``
|
||||
@@ -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<GroupKey>(by keyForValue: (Element) throws -> GroupKey) rethrows -> [GroupKey: [Element]] {
|
||||
try Dictionary(grouping: self, by: keyForValue)
|
||||
}
|
||||
}
|
||||
@@ -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<Self> {
|
||||
IndexedCollection(base: self)
|
||||
|
||||
Executable
+65
@@ -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<Key>(
|
||||
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<Key>(
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -28,11 +28,9 @@ extension Sequence {
|
||||
while let e = iterator.next() {
|
||||
// To be part of `result`, `e` must be strictly less than `result.last`.
|
||||
guard try areInIncreasingOrder(e, result.last!) else { continue }
|
||||
result.removeLast()
|
||||
let insertionIndex =
|
||||
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
|
||||
|
||||
assert(insertionIndex != result.endIndex)
|
||||
result.removeLast()
|
||||
result.insert(e, at: insertionIndex)
|
||||
}
|
||||
|
||||
@@ -127,7 +125,7 @@ extension Sequence {
|
||||
/// largest values:
|
||||
///
|
||||
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
/// let smallestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// let largestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// // [7, 8, 9]
|
||||
///
|
||||
/// If you need to sort a sequence but only need to access its largest
|
||||
@@ -199,7 +197,7 @@ extension Sequence where Element: Comparable {
|
||||
/// largest values:
|
||||
///
|
||||
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
/// let smallestThree = numbers.max(count: 3)
|
||||
/// let largestThree = numbers.max(count: 3)
|
||||
/// // [7, 8, 9]
|
||||
///
|
||||
/// If you need to sort a sequence but only need to access its largest
|
||||
@@ -258,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.
|
||||
@@ -282,7 +280,7 @@ extension Collection {
|
||||
/// largest values:
|
||||
///
|
||||
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
/// let smallestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// let largestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// // [7, 8, 9]
|
||||
///
|
||||
/// If you need to sort a collection but only need to access its largest
|
||||
@@ -312,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.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Copyright (c) 2020-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
|
||||
@@ -168,8 +168,8 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection {
|
||||
/// Returns the index of the first element in the collection that matches
|
||||
/// the predicate.
|
||||
/// Returns the start index of the partition of a collection that matches
|
||||
/// the given predicate.
|
||||
///
|
||||
/// The collection must already be partitioned according to the predicate.
|
||||
/// That is, there should be an index `i` where for every element in
|
||||
@@ -179,7 +179,8 @@ extension Collection {
|
||||
/// - Parameter belongsInSecondPartition: A predicate that partitions the
|
||||
/// collection.
|
||||
/// - Returns: The index of the first element in the collection for which
|
||||
/// `predicate` returns `true`.
|
||||
/// `predicate` returns `true`, or `endIndex` if there are no elements
|
||||
/// for which `predicate` returns `true`.
|
||||
///
|
||||
/// - Complexity: O(log *n*), where *n* is the length of this collection if
|
||||
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
|
||||
@@ -204,3 +205,137 @@ 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)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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..<endIndex]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,8 +61,8 @@ extension Collection where Self: RangeReplaceableCollection {
|
||||
public mutating func trimPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
let end = try endOfPrefix(while: predicate)
|
||||
removeSubrange(startIndex..<end)
|
||||
let startOfResult = try endOfPrefix(while: predicate)
|
||||
removeSubrange(startIndex..<startOfResult)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ extension BidirectionalCollection {
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> SubSequence {
|
||||
let end = try startOfSuffix(while: predicate)
|
||||
return self[..<end]
|
||||
return self[startIndex..<end]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,8 +188,8 @@ extension BidirectionalCollection where Self: RangeReplaceableCollection {
|
||||
public mutating func trimSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
let start = try startOfSuffix(while: predicate)
|
||||
removeSubrange(start..<endIndex)
|
||||
let endOfResult = try startOfSuffix(while: predicate)
|
||||
removeSubrange(endOfResult..<endIndex)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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`
|
||||
|
||||
-----------------------------------------------------
|
||||
""")
|
||||
@@ -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<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) }
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String>().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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,26 @@ 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() {
|
||||
for length in 10...20 {
|
||||
let a = Array(0..<length)
|
||||
@@ -133,4 +153,40 @@ 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"])
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
@testable import Algorithms
|
||||
import Algorithms
|
||||
|
||||
final class SuffixTests: XCTestCase {
|
||||
func testSuffix() {
|
||||
|
||||
Reference in new issue
Block a user