Compare commits

..
36 Commits
Author SHA1 Message Date
Nate Cook 0bd7f4dcb1 Migrate to typed errors across the board
Along with converting to typed errors, this also bumps the swiftlang
version in Package.swift to 6.0 (to support typed errors).
2024-12-22 15:58:42 -06:00
Nate Cook 34eec0dd27 Update project to depend on Swift 5.7 (#240) 2024-08-21 17:19:30 -05:00
Guillaume Lessard 09dc5e4354 Merge pull request #227 from CheATSlark/main
Update Suffix.md
2024-06-25 11:01:42 -07:00
slark 0a01f21eae Merge branch 'main' into main 2024-06-25 15:46:29 +08:00
Jed Fox 34b1705efd Clarify the docs for partitioned(by:) (#228) 2024-05-07 12:53:17 -07:00
jerry ae92f2b33f Update Suffix.md
Fix 'Suffix.md'  example code
2024-04-12 16:09:42 +08:00
Marcos Griselli 33abb69428 Remove @_implementationOnly annotations (#225)
Signed-off-by: Marcos Griselli <marcosg@lyft.com>
2024-03-09 13:35:42 -06:00
Takumi Muraishi 82ee335a48 Fix typo in TestUtilities.swift (#223) 2024-02-17 00:58:00 -06:00
Dimitris Apostolou 9e3900be49 Fix typos (#222) 2024-02-07 00:18:57 -06:00
Dave Abrahams 9dd88e5eaf CombinationsSequence: underestimatedCount == count (#220)
Not doing this makes it needlessly costly to create an Array of the
results.
2024-01-20 10:04:45 -06:00
Kenny c3b3acbca3 Fix Typo in README Xocde -> Xcode 2023-11-26 13:32:29 -06:00
Nate Cook f6919dfc30 Documentation improvements
- Restructure the project README, moving the list of guides into a
README in the `Guides` directory
- Curate the `keyed(by:)` and `grouped(by:)` methods
2023-11-14 21:50:39 -06:00
Nate Cook f2fd047eed Update changelog for 1.2.0 release 2023-11-14 21:50:39 -06:00
Nate Cook 5c54f200e7 Update guide/docs/tests. 2023-11-14 13:00:34 -06:00
Matthew Young 2e71e228c0 Update Suffix.swift
Change `endOfPrefix(while:)` and `startOfSuffix(while:)` from internal to public
2023-11-14 13:00:34 -06:00
Alexander Momchilov 328631d60c Add grouped(by:) and keyed(by:) (#197)
* Add Grouped and Keyed

* Add `Key` to `combine` closure

* Split `keyed(by:)` into two overloads

* Rename uniquingKeysWith → resolvingConflictsWith

* Keep latest instead of throwing on collision
2023-11-07 14:29:10 -06:00
Stephen Canon 0ebed148c2 Merge pull request #210 from amomchilov/tweak-docs
[Docs] Add link and remove redundant doc line
2023-11-01 11:57:28 -04:00
Alexander Momchilov c8ae549e42 [Docs] Add link and remove redundant doc line 2023-10-31 20:25:50 -04:00
Taras Tsugrii dd4e0e70ff [minmax] Do nothing for empty suffix/prefix. (#202)
It's a semantical noop but slightly more efficient for the case when max/min is requested for an empty Collection.
2023-10-31 11:03:19 -05:00
Nate Cook bcd4f369ac Update changelog for 1.1.0 release (#206) 2023-10-05 14:45:17 -05:00
Nate Cook 4f53c9cf40 Finish sub-page documentation updates (#204)
* Finish sub-page documentation updates

Some of these pages could use introductions, but the current state is
ready for publication.

* Add SPI yaml file for building docs
2023-10-05 13:10:03 -05:00
Nate Cook 0d6f943832 Increase the package version to 5.4 (#205)
The latest Swift versions appear to have a problem with the
LinuxMain.swift again, which we haven't needed for quite some time.
Linux test autodiscovery has been enabled since 5.4, so we can
update to that version and drop the file.
2023-10-05 13:03:25 -05:00
Nate Cook fc8fdfd4dc Curate documentation for Algorithms module (#201) 2023-08-24 14:17:38 -05:00
Matt Zanchelli bfcaaa8758 Correct Chunked documentation (#182)
* Clarify that the determining factor for being grouped is equality (`Equatable`), which doesn’t necessarily mean the _same_ value (identity)
* Correct algorithmic complexity documentation on the lazy Chunked functions
* Document `belongInSameGroup` and `projection`
2023-08-02 10:18:17 -05:00
Nate Cook 0f81ef4a70 Chunked type / documentation cleanup (#200)
This change improves the documentation for `evenlyChunked(in:)` and
`chunks(ofCount:)` and renames `EvenChunksCollection` to
`EvenlyChunkedCollection` to follow the pattern of wrapper type
names matching their producing functions.
2023-07-26 13:15:35 -05:00
Tim VermeulenandTim Vermeulen de3efbc567 Evenly divide a collection into chunks (#96)
Adds `evenlyChunked(in:)` as a `Collection` method that divides a
collection into a specific number of chunks as evenly as possible.

Co-authored-by: Tim Vermeulen <tvermeulen@apple.com>
2023-07-26 11:17:25 -05:00
Gwynne Raskind df51f1780b Specify dependency URL in consistent fashion (#194) 2023-07-03 15:15:33 -05:00
Matt Dickoff 288d8b00f2 Merge pull request #191 from dickoff/dickoff/fix-max-code-documentation
Corrects variable name in documentation for max functions to better reflect usage
2022-12-07 13:27:05 -06:00
Matt Dickoff aa6349dea0 Corrects variable name in max functions to better reflect usage
The variable smallestThree should really be named largestThree. Looks
like this was originally a copy paste error from the min documentation.
2022-12-01 11:37:32 -06:00
Matt ZanchelliandMatt Zanchelli 195e0316d7 Update comments in Chunked.swift (#179)
* Use back ticks around code references

* Add missing spaces before parenthesis

* Use “passed” instead of “past”
Add missing comma
Add back ticks around code references
Add missing space before parenthesis

* Consistently use spaces around `%` operator

Co-authored-by: Matt Zanchelli <mattt@apple.com>
2022-02-23 13:07:19 -06:00
Matt Zanchelli da475ea9af Clarify endIndex behavior of partitioningIndex(where:) in documentation (Resolves #170) (#171)
The returned index isn’t necessarily an index of an element. In the case where it returns `endIndex`, it’s not valid for subscripting the collection.
2021-12-16 07:10:17 -06:00
Matt Zanchelli 19c1d00177 Remove the last element before determining the insertion index (#173)
This could result in fewer comparisons.

Additionally, it ensures that the insertion index is valid for insertion. The `removeLast()` documentation states:
> Calling this method may invalidate all saved indices of this collection. Do not rely on a previously stored index value after altering a collection with any operation that can change its length.
2021-12-04 00:25:02 -06:00
e2fa131d62 Add partitioned(by:) (#152)
* Add `partitioned(_:)`

`partitioned(_:)` works like `filter(_:)`, but also returns the excluded elements by returning a tuple of two `Array`s

* For collections with fewer than 8 elements, use the `Sequence`-based implementation

This constant was determined using benchmarking. More information: https://github.com/apple/swift-algorithms/pull/152#issuecomment-887130149

* Remove check for collections fewer than 8 elements

* Make `_partitioned` `internal`

* Prefer `Array` over `ContiguousArray`

* Document `partitioned(_:)` on `Collection`

* Remove `partitioned(upTo:)`

* Remove `_tupleMap`

* Remove `_partitioned` and use it inline (since it’s no longer used by the `Collection` implementation

* Remove unnecessary conversation of `Array` to `Array`

* Correct indentation

Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>

* Consistent syntax

Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>

* Add an external `by:` label to `partitioned`

* Add labels to returned tuple `falseElements`, `trueElements`

* Correct function signature

* Rename `belongsInSecondCollection` parameter name to simply `predicate`

The parameter name was potentially confusing. Unlike the other `partition` functions, this function can rely on its named tuple to clarify its behavior.

* Update copyright information

Co-authored-by: Nate Cook <natecook@apple.com>

* Update documentation

Co-authored-by: Nate Cook <natecook@apple.com>

* Update comment

* Add a precondition to ensure that the count matches up with the number of actual elements found while iterating

Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
Co-authored-by: Nate Cook <natecook@apple.com>
2021-10-20 22:21:39 +02:00
Ole Begemann aeead5ab20 Fix typo in readme
Looks like a copy/paste oversight.
2021-09-13 14:22:39 -07:00
Tim Vermeulen c5ea9e3e36 Prepare for Swift Algorithms 1.0 (#167)
* Rename types to include a Sequence or Collection suffix, and clean up some guides

* Various refactors

* Replace `validateIndexTraversals` test method with `IndexValidator` type

* Add LazySequenceProtocol to StridingSequence, StridingCollection

* Update the Numerics dependency to 1.0

* Set `IndexedCollection.Indices` to `Base.Indices`

* Remove deprecations

* Update the changelog/README for the 1.0.0 release

* Fix compiler error on Linux

* Rename `WindowsCollection` to `WindowsOfCountCollection`
2021-09-09 01:01:36 +02:00
Stephen Canon e195266e1f Make Algorithms depend on Numerics product instead of RealModule. (#164)
The RealModule _library product_ will be removed from Numerics at some future point (the _module_ will continue to exist). Update Package.swift to depend on the Numerics library instead.
2021-08-26 18:51:34 +02:00
53 changed files with 2019 additions and 392 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
version: 1
builder:
configs:
- documentation_targets: [Algorithms]
+85 -2
View File
@@ -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
-3
View File
@@ -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
View File
@@ -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.
+1 -1
View File
@@ -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
+68
View File
@@ -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.
+78
View File
@@ -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 alternative, and matches the past tense of [Swift's API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/), though perhaps we'd spell it `associated(by:)`.
#### Customization points
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
View File
@@ -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
+53
View File
@@ -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.
+1 -1
View File
@@ -9,7 +9,7 @@ collection until predicate returns `false` and skipping the remaining elements.
This example uses `suffix(while: )` to iterate through collection of integers
from the end until the predicate returns false, in this case when `$0 <= 5`
```swift
(0...10).suffix(while: { $0 > 5 } // == [6,7,8,9,10]
(0...10).suffix(while: { $0 > 5 }) // == [6,7,8,9,10]
```
## Detailed Design
+50 -29
View File
@@ -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
+11 -3
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.1
// swift-tools-version:6.0
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
@@ -12,6 +12,13 @@
import PackageDescription
let availabilityDefinition = PackageDescription.SwiftSetting.unsafeFlags([
"-Xfrontend",
"-define-availability",
"-Xfrontend",
"SwiftStdlib 5.7:macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0",
])
let package = Package(
name: "swift-algorithms",
products: [
@@ -20,14 +27,15 @@ 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(
name: "Algorithms",
dependencies: [
.product(name: "RealModule", package: "swift-numerics"),
]),
],
swiftSettings: [availabilityDefinition]),
.testTarget(
name: "SwiftAlgorithmsTests",
dependencies: ["Algorithms"]),
+27 -42
View File
@@ -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 Xcode 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
+13 -2
View File
@@ -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)
+320 -33
View File
@@ -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,11 +450,15 @@ 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(
by belongInSameGroup: (Element, Element) throws -> Bool
) rethrows -> [SubSequence] {
public func chunked<E: Error>(
by belongInSameGroup: (Element, Element) throws(E) -> Bool
) throws(E) -> [SubSequence] {
guard !isEmpty else { return [] }
var result: [SubSequence] = []
@@ -266,13 +481,17 @@ 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
public func chunked<Subject: Equatable>(
on projection: (Element) throws -> Subject
) rethrows -> [(Subject, SubSequence)] {
public func chunked<Subject: Equatable, E: Error>(
on projection: (Element) throws(E) -> Subject
) throws(E) -> [(Subject, SubSequence)] {
guard !isEmpty else { return [] }
var result: [(Subject, SubSequence)] = []
@@ -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)
}
}
+6 -2
View File
@@ -78,6 +78,10 @@ public struct CombinationsSequence<Base: Collection> {
binomial(n: n, k: $0)
}.reduce(0, +)
}
/// The total number of combinations.
@inlinable
public var underestimatedCount: Int { count }
}
extension CombinationsSequence: Sequence {
@@ -289,8 +293,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 Simultaneously
- ``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:)``
+3 -3
View File
@@ -31,9 +31,9 @@ extension Sequence {
/// - Complexity: O(*n*), where *n* is the number of elements at the start of
/// the sequence that result in `nil` when applying the transformation.
@inlinable
public func firstNonNil<Result>(
_ transform: (Element) throws -> Result?
) rethrows -> Result? {
public func firstNonNil<Result, E: Error>(
_ transform: (Element) throws(E) -> Result?
) throws(E) -> Result? {
for value in self {
if let value = try transform(value) {
return value
+33
View File
@@ -0,0 +1,33 @@
//===----------------------------------------------------------------------===//
//
// 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, E: Error>(
by keyForValue: (Element) throws(E) -> GroupKey
) throws(E) -> [GroupKey: [Element]] {
do {
// This stdlib Dictionary initializer doesn't use typed errors,
// so we need to catch and cast any thrown error to our expected type.
return try Dictionary(grouping: self, by: keyForValue)
} catch {
throw error as! E
}
}
}
+5 -1
View File
@@ -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)
+19 -11
View File
@@ -355,9 +355,9 @@ extension Sequence where Element: Sequence {
}
@inlinable
internal func _joined(
by update: (inout [Element.Element], Element, Element) throws -> Void
) rethrows -> [Element.Element] {
internal func _joined<E: Error>(
by update: (inout [Element.Element], Element, Element) throws(E) -> Void
) throws(E) -> [Element.Element] {
var iterator = makeIterator()
guard let first = iterator.next() else { return [] }
@@ -381,10 +381,14 @@ extension Sequence where Element: Sequence {
/// }
/// // 1, 2, 6, 3, 4, 20, 5, 6
@inlinable
public func joined(
by separator: (Element, Element) throws -> Element.Element
) rethrows -> [Element.Element] {
try _joined(by: { $0.append(try separator($1, $2)) })
public func joined<E: Error>(
by separator: (Element, Element) throws(E) -> Element.Element
) throws(E) -> [Element.Element] {
// An anonymous closure is inferred as `throws(any Error)`, so we give it
// the correct type here.
let joiner: (inout [Element.Element], Element, Element) throws(E) -> Void
= { $0.append(try separator($1, $2)) }
return try _joined(by: joiner)
}
/// Returns the concatenation of the elements in this sequence of sequences,
@@ -395,12 +399,16 @@ extension Sequence where Element: Sequence {
/// }
/// // 1, 2, 200, 300, 3, 4, 400, 500, 5, 6
@inlinable
public func joined<Separator>(
by separator: (Element, Element) throws -> Separator
) rethrows -> [Element.Element]
public func joined<Separator, E: Error>(
by separator: (Element, Element) throws(E) -> Separator
) throws(E) -> [Element.Element]
where Separator: Sequence, Separator.Element == Element.Element
{
try _joined(by: { $0.append(contentsOf: try separator($1, $2)) })
// An anonymous closure is inferred as `throws(any Error)`, so we give it
// the correct type here.
let joiner: (inout [Element.Element], Element, Element) throws(E) -> Void
= { $0.append(contentsOf: try separator($1, $2)) }
return try _joined(by: joiner)
}
}
+68
View File
@@ -0,0 +1,68 @@
//===----------------------------------------------------------------------===//
//
// 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, E: Error>(
by keyForValue: (Element) throws(E) -> Key
) throws(E) -> [Key: Element] {
// An anonymous closure is inferred as `throws(any Error)`, so we give it
// the correct type here.
let resolve: (Key, Element, Element) throws(E) -> Element = { _, _, new in new }
return try self.keyed(by: keyForValue, resolvingConflictsWith: resolve)
}
/// 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, E: Error>(
by keyForValue: (Element) throws(E) -> Key,
resolvingConflictsWith resolve: (Key, Element, Element) throws(E) -> Element
) throws(E) -> [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
}
}
+70 -44
View File
@@ -12,10 +12,10 @@
extension Sequence {
/// Implementation for min(count:areInIncreasingOrder:)
@inlinable
internal func _minImplementation(
internal func _minImplementation<E: Error>(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
sortedBy areInIncreasingOrder: (Element, Element) throws(E) -> Bool
) throws(E) -> [Element] {
var iterator = makeIterator()
var result: [Element] = []
@@ -23,16 +23,22 @@ extension Sequence {
while result.count < count, let e = iterator.next() {
result.append(e)
}
try result.sort(by: areInIncreasingOrder)
do {
// The stdlib `sort(by:)` method doesn't use typed errors,
// so we need to catch and cast any thrown error to our expected type.
try result.sort(by: areInIncreasingOrder)
} catch {
throw error as! E
}
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 }
let insertionIndex =
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
assert(insertionIndex != result.endIndex)
result.removeLast()
// An anonymous closure is inferred as `throws(any Error)`, so we give it
// the correct type here.
let pred: (Element) throws(E) -> Bool = { try areInIncreasingOrder(e, $0) }
let insertionIndex = try result.partitioningIndex(where: pred)
result.insert(e, at: insertionIndex)
}
@@ -41,10 +47,10 @@ extension Sequence {
/// Implementation for max(count:areInIncreasingOrder:)
@inlinable
internal func _maxImplementation(
internal func _maxImplementation<E: Error>(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
sortedBy areInIncreasingOrder: (Element, Element) throws(E) -> Bool
) throws(E) -> [Element] {
var iterator = makeIterator()
var result: [Element] = []
@@ -52,13 +58,21 @@ extension Sequence {
while result.count < count, let e = iterator.next() {
result.append(e)
}
try result.sort(by: areInIncreasingOrder)
do {
// The stdlib `sort(by:)` method doesn't use typed errors,
// so we need to catch and cast any thrown error to our expected type.
try result.sort(by: areInIncreasingOrder)
} catch {
throw error as! E
}
while let e = iterator.next() {
// To be part of `result`, `e` must be greater/equal to `result.first`.
guard try !areInIncreasingOrder(e, result.first!) else { continue }
let insertionIndex =
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
// An anonymous closure is inferred as `throws(any Error)`, so we give it
// the correct type here.
let pred: (Element) throws(E) -> Bool = { try areInIncreasingOrder(e, $0) }
let insertionIndex = try result.partitioningIndex(where: pred)
assert(insertionIndex > 0)
// Inserting `e` and then removing the first element (or vice versa)
@@ -103,10 +117,10 @@ extension Sequence {
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`.
@inlinable
public func min(
public func min<E: Error>(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
sortedBy areInIncreasingOrder: (Element, Element) throws(E) -> Bool
) throws(E) -> [Element] {
precondition(count >= 0, """
Cannot find a minimum with a negative count of elements!
"""
@@ -127,7 +141,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
@@ -148,10 +162,10 @@ extension Sequence {
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`.
@inlinable
public func max(
public func max<E: Error>(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
sortedBy areInIncreasingOrder: (Element, Element) throws(E) -> Bool
) throws(E) -> [Element] {
precondition(count >= 0, """
Cannot find a maximum with a negative count of elements!
"""
@@ -199,7 +213,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
@@ -249,27 +263,33 @@ extension Collection {
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`.
@inlinable
public func min(
public func min<E: Error>(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
sortedBy areInIncreasingOrder: (Element, Element) throws(E) -> Bool
) throws(E) -> [Element] {
precondition(count >= 0, """
Cannot find a minimum with a negative count of elements!
"""
)
// 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.
guard prefixCount < (self.count / 10) else {
return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount))
do {
// The stdlib `sorted(by:)` method doesn't use typed errors,
// so we need to catch and cast any thrown error to our expected type.
return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount))
} catch {
throw error as! E
}
}
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
@@ -282,7 +302,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
@@ -303,27 +323,33 @@ extension Collection {
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`.
@inlinable
public func max(
public func max<E: Error>(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
sortedBy areInIncreasingOrder: (Element, Element) throws(E) -> Bool
) throws(E) -> [Element] {
precondition(count >= 0, """
Cannot find a maximum with a negative count of elements!
"""
)
// 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.
guard suffixCount < (self.count / 10) else {
return Array(try sorted(by: areInIncreasingOrder).suffix(suffixCount))
do {
// The stdlib `sorted(by:)` method doesn't use typed errors,
// so we need to catch and cast any thrown error to our expected type.
return Array(try sorted(by: areInIncreasingOrder).suffix(suffixCount))
} catch {
throw error as! E
}
}
return try _maxImplementation(count: count, sortedBy: areInIncreasingOrder)
@@ -429,9 +455,9 @@ extension Sequence {
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func minAndMax(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> (min: Element, max: Element)? {
public func minAndMax<E: Error>(
by areInIncreasingOrder: (Element, Element) throws(E) -> Bool
) throws(E) -> (min: Element, max: Element)? {
// Check short sequences.
var iterator = makeIterator()
guard var lowest = iterator.next() else { return nil }
+178 -24
View File
@@ -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
@@ -22,11 +22,11 @@ extension MutableCollection {
/// - Precondition:
/// `n == distance(from: range.lowerBound, to: range.upperBound)`
@inlinable
internal mutating func stablePartition(
internal mutating func stablePartition<E: Error>(
count n: Int,
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
by belongsInSecondPartition: (Element) throws(E) -> Bool
) throws(E) -> Index {
if n == 0 { return subrange.lowerBound }
if n == 1 {
return try belongsInSecondPartition(self[subrange.lowerBound])
@@ -58,10 +58,10 @@ extension MutableCollection {
///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
@inlinable
public mutating func stablePartition(
public mutating func stablePartition<E: Error>(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index {
by belongsInSecondPartition: (Element) throws(E) -> Bool
) throws(E) -> Index {
try stablePartition(
count: distance(from: subrange.lowerBound, to: subrange.upperBound),
subrange: subrange,
@@ -78,9 +78,9 @@ extension MutableCollection {
///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
@inlinable
public mutating func stablePartition(
by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index {
public mutating func stablePartition<E: Error>(
by belongsInSecondPartition: (Element) throws(E) -> Bool
) throws(E) -> Index {
try stablePartition(
subrange: startIndex..<endIndex,
by: belongsInSecondPartition)
@@ -97,14 +97,22 @@ extension MutableCollection {
///
/// - Complexity: O(*n*) where n is the length of the collection.
@inlinable
public mutating func partition(
public mutating func partition<E: Error>(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
by belongsInSecondPartition: (Element) throws(E) -> Bool
) throws(E) -> Index {
// This version of `partition(subrange:)` is half stable; the elements in
// the first partition retain their original relative order.
guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition)
else { return subrange.upperBound }
var i: Index
do {
// The stdlib `firstIndex(where:)` method doesn't use typed errors,
// so we need to catch and cast any thrown error to our expected type.
guard let firstI = try self[subrange].firstIndex(where: belongsInSecondPartition)
else { return subrange.upperBound }
i = firstI
} catch {
throw error as! E
}
var j = index(after: i)
while j != subrange.upperBound {
@@ -125,10 +133,10 @@ extension MutableCollection where Self: BidirectionalCollection {
///
/// - Complexity: O(*n*) where n is the length of the collection.
@inlinable
public mutating func partition(
public mutating func partition<E: Error>(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
by belongsInSecondPartition: (Element) throws(E) -> Bool
) throws(E) -> Index {
var lo = subrange.lowerBound
var hi = subrange.upperBound
@@ -168,8 +176,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,14 +187,15 @@ 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*).
@inlinable
public func partitioningIndex(
where belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
public func partitioningIndex<E: Error>(
where belongsInSecondPartition: (Element) throws(E) -> Bool
) throws(E) -> Index {
var n = count
var l = startIndex
@@ -204,3 +213,148 @@ extension Collection {
}
}
//===----------------------------------------------------------------------===//
// partitioned(by:)
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns two arrays containing the elements of the sequence that
/// don’t and do satisfy the given predicate, respectively.
///
/// In this example, `partitioned(by:)` is used to separate the input based on
/// whether a name is shorter than five characters:
///
/// 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. The
/// order of the elements in the arrays matches the order of the elements in
/// the original sequence.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func partitioned<E: Error>(
by predicate: (Element) throws(E) -> Bool
) throws(E) -> (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 the elements of the collection that
/// don’t and do satisfy the given predicate, respectively.
///
/// In this example, `partitioned(by:)` is used to separate the input based on
/// whether a name is shorter than five characters.
///
/// 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. The
/// order of the elements in the arrays matches the order of the elements in
/// the original collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func partitioned<E: Error>(
by predicate: (Element) throws(E) -> Bool
) throws(E) -> (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: [Element]
do {
// This stdlib `Array` initializer doesn't use typed errors,
// so we need to catch and cast any thrown error to our expected type.
elements = try Array(
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
}
})
} catch {
throw error as! E
}
let lhs = elements[..<midPoint]
let rhs = elements[midPoint...]
return (
Array(lhs),
Array(rhs)
)
}
}
+6
View File
@@ -10,8 +10,14 @@
//===----------------------------------------------------------------------===//
// For log(_:) and root(_:_:)
#if swift(>=5.11)
internal import RealModule
#elseif swift(>=5.10)
import RealModule
#else
@_implementationOnly
import RealModule
#endif
//===----------------------------------------------------------------------===//
// randomStableSample(count:)
+22 -20
View File
@@ -112,13 +112,16 @@ extension Sequence {
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable
public func reductions<Result>(
public func reductions<Result, E: Error>(
_ initial: Result,
_ transform: (Result, Element) throws -> Result
) rethrows -> [Result] {
try reductions(into: initial) { result, element in
_ transform: (Result, Element) throws(E) -> Result
) throws(E) -> [Result] {
// An anonymous closure is inferred as `throws(any Error)`, so we give it
// the correct type here.
let reducer: (inout Result, Element) throws(E) -> Void = { result, element in
result = try transform(result, element)
}
return try reductions(into: initial, reducer)
}
/// Returns an array containing the accumulated results of combining the
@@ -156,11 +159,10 @@ extension Sequence {
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable
public func reductions<Result>(
public func reductions<Result, E: Error>(
into initial: Result,
_ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result] {
_ transform: (inout Result, Element) throws(E) -> Void
) throws(E) -> [Result] {
var output = [Result]()
output.reserveCapacity(underestimatedCount + 1)
output.append(initial)
@@ -415,9 +417,9 @@ extension Sequence {
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable
public func reductions(
_ transform: (Element, Element) throws -> Element
) rethrows -> [Element] {
public func reductions<E: Error>(
_ transform: (Element, Element) throws(E) -> Element
) throws(E) -> [Element] {
var iterator = makeIterator()
guard let initial = iterator.next() else { return [] }
return try IteratorSequence(iterator).reductions(initial, transform)
@@ -582,19 +584,19 @@ extension LazySequenceProtocol {
extension Sequence {
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
@inlinable
public func scan<Result>(
public func scan<Result, E: Error>(
_ initial: Result,
_ transform: (Result, Element) throws -> Result
) rethrows -> [Result] {
_ transform: (Result, Element) throws(E) -> Result
) throws(E) -> [Result] {
try reductions(initial, transform)
}
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
@inlinable
public func scan<Result>(
public func scan<Result, E: Error>(
into initial: Result,
_ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result] {
_ transform: (inout Result, Element) throws(E) -> Void
) throws(E) -> [Result] {
try reductions(into: initial, transform)
}
}
@@ -612,9 +614,9 @@ extension LazySequenceProtocol {
extension Sequence {
@available(*, deprecated, message: "Use reductions(_:) instead.")
@inlinable
public func scan(
_ transform: (Element, Element) throws -> Element
) rethrows -> [Element] {
public func scan<E: Error>(
_ transform: (Element, Element) throws(E) -> Element
) throws(E) -> [Element] {
try reductions(transform)
}
}
+1 -1
View File
@@ -512,7 +512,7 @@ extension SplitCollection: Collection {
var subsequenceStart = i.baseRange.upperBound
if subsequenceStart < base.endIndex {
// If we're not already at the end of the base collection, the previous
// susequence ended with a separator. Start searching for the next
// subsequence ended with a separator. Start searching for the next
// subsequence at the following element.
subsequenceStart = base.index(after: i.baseRange.upperBound)
}
+10 -10
View File
@@ -24,9 +24,9 @@ extension BidirectionalCollection {
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func suffix(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
public func suffix<E: Error>(
while predicate: (Element) throws(E) -> Bool
) throws(E) -> SubSequence {
try self[startOfSuffix(while: predicate)...]
}
}
@@ -46,11 +46,11 @@ extension Collection {
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
internal func endOfPrefix(
while predicate: (Element) throws -> Bool
) rethrows -> Index {
public func endOfPrefix<E: Error>(
while predicate: (Element) throws(E) -> Bool
) throws(E) -> Index {
var index = startIndex
while try index != endIndex && predicate(self[index]) {
while index != endIndex, try predicate(self[index]) {
formIndex(after: &index)
}
return index
@@ -72,9 +72,9 @@ extension BidirectionalCollection {
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
internal func startOfSuffix(
while predicate: (Element) throws -> Bool
) rethrows -> Index {
public func startOfSuffix<E: Error>(
while predicate: (Element) throws(E) -> Bool
) throws(E) -> Index {
var index = endIndex
while index != startIndex {
let after = index
+39 -45
View File
@@ -26,13 +26,12 @@ extension Collection {
/// omitted from the resulting slice.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable
public func trimmingPrefix(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
public func trimmingPrefix<E: Error>(
while predicate: (Element) throws(E) -> Bool
) throws(E) -> SubSequence {
let start = try endOfPrefix(while: predicate)
return self[start...]
return self[start..<endIndex]
}
}
@@ -55,14 +54,13 @@ extension Collection where Self: RangeReplaceableCollection {
/// removed from the string.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable
@_disfavoredOverload
public mutating func trimPrefix(
while predicate: (Element) throws -> Bool
) rethrows {
let end = try endOfPrefix(while: predicate)
removeSubrange(startIndex..<end)
public mutating func trimPrefix<E: Error>(
while predicate: (Element) throws(E) -> Bool
) throws(E) {
let startOfResult = try endOfPrefix(while: predicate)
removeSubrange(startIndex..<startOfResult)
}
}
@@ -81,12 +79,12 @@ extension Collection where Self == Self.SubSequence {
/// be removed from the string.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable
public mutating func trimPrefix(
while predicate: (Element) throws -> Bool
) rethrows {
self = try trimmingPrefix(while: predicate)
public mutating func trimPrefix<E: Error>(
while predicate: (Element) throws(E) -> Bool
) throws(E) {
let start = try endOfPrefix(while: predicate)
self = self[start..<endIndex]
}
}
@@ -108,12 +106,12 @@ extension BidirectionalCollection {
/// omitted from the resulting slice.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable
public func trimming(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
try trimmingPrefix(while: predicate).trimmingSuffix(while: predicate)
public func trimming<E: Error>(
while predicate: (Element) throws(E) -> Bool
) throws(E) -> SubSequence {
let start = try endOfPrefix(while: predicate)
return try self[start..<endIndex].trimmingSuffix(while: predicate)
}
/// Returns a `SubSequence` formed by discarding all elements at the end of
@@ -129,13 +127,12 @@ extension BidirectionalCollection {
/// omitted from the resulting slice.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable
public func trimmingSuffix(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
public func trimmingSuffix<E: Error>(
while predicate: (Element) throws(E) -> Bool
) throws(E) -> SubSequence {
let end = try startOfSuffix(while: predicate)
return self[..<end]
return self[startIndex..<end]
}
}
@@ -158,14 +155,14 @@ extension BidirectionalCollection where Self: RangeReplaceableCollection {
/// removed from the string.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable
@_disfavoredOverload
public mutating func trim(
while predicate: (Element) throws -> Bool
) rethrows {
public mutating func trim<E: Error>(
while predicate: (Element) throws(E) -> Bool
) throws(E) {
let start = try endOfPrefix(while: predicate)
self.removeSubrange(startIndex..<start)
try trimSuffix(while: predicate)
try trimPrefix(while: predicate)
}
/// Mutates a `BidirectionalCollection` by discarding all elements at the end
@@ -182,14 +179,13 @@ extension BidirectionalCollection where Self: RangeReplaceableCollection {
/// removed from the string.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable
@_disfavoredOverload
public mutating func trimSuffix(
while predicate: (Element) throws -> Bool
) rethrows {
let start = try startOfSuffix(while: predicate)
removeSubrange(start..<endIndex)
public mutating func trimSuffix<E: Error>(
while predicate: (Element) throws(E) -> Bool
) throws(E) {
let endOfResult = try startOfSuffix(while: predicate)
removeSubrange(endOfResult..<endIndex)
}
}
@@ -208,11 +204,10 @@ extension BidirectionalCollection where Self == Self.SubSequence {
/// removed from the string.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable
public mutating func trim(
while predicate: (Element) throws -> Bool
) rethrows {
public mutating func trim<E: Error>(
while predicate: (Element) throws(E) -> Bool
) throws(E) {
self = try trimming(while: predicate)
}
@@ -230,11 +225,10 @@ extension BidirectionalCollection where Self == Self.SubSequence {
/// removed from the string.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable
public mutating func trimSuffix(
while predicate: (Element) throws -> Bool
) rethrows {
public mutating func trimSuffix<E: Error>(
while predicate: (Element) throws(E) -> Bool
) throws(E) {
self = try trimmingSuffix(while: predicate)
}
}
+3 -3
View File
@@ -112,9 +112,9 @@ extension Sequence {
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func uniqued<Subject: Hashable>(
on projection: (Element) throws -> Subject
) rethrows -> [Element] {
public func uniqued<Subject: Hashable, E: Error>(
on projection: (Element) throws(E) -> Subject
) throws(E) -> [Element] {
var seen: Set<Subject> = []
var result: [Element] = []
for element in self {
-19
View File
@@ -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`
-----------------------------------------------------
""")
+33 -3
View File
@@ -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) }
}
}
@@ -15,57 +15,63 @@ import Algorithms
final class CombinationsTests: XCTestCase {
func testCount() {
let c = "ABCD"
let c0 = c.combinations(ofCount: 0).count
XCTAssertEqual(c0, 1)
let c1 = c.combinations(ofCount: 1).count
XCTAssertEqual(c1, 4)
let c2 = c.combinations(ofCount: 2).count
XCTAssertEqual(c2, 6)
let c3 = c.combinations(ofCount: 3).count
XCTAssertEqual(c3, 4)
let c4 = c.combinations(ofCount: 4).count
XCTAssertEqual(c4, 1)
let c5 = c.combinations(ofCount: 0...0).count
XCTAssertEqual(c5, 1)
let c6 = c.combinations(ofCount: 1...1).count
XCTAssertEqual(c6, 4)
let c7 = c.combinations(ofCount: 1...2).count
XCTAssertEqual(c7, 10)
let c8 = c.combinations(ofCount: 1...3).count
XCTAssertEqual(c8, 14)
let c9 = c.combinations(ofCount: 2...4).count
XCTAssertEqual(c9, 11)
/// XCTAsserts that `x`'s `count` and `underestimatedCount` are both `l` at
/// the given `file` and `line`.
func check(
_ x: CombinationsSequence<String>, countsAre l: Int,
file: StaticString, line: UInt)
{
XCTAssertEqual(x.count, l, "unexpected count", file: file, line: line)
XCTAssertEqual(
x.underestimatedCount, l, "unexpected underestimatedCount",
file: file, line: line)
}
/// XCTAsserts that the `count` and `underestimatedCount` of
/// `c.combinations(ofCount: l)` are both `n` at the given `file` and
/// `line`.
func check(
cHas n: Int,
combinationsOfLength l: Int,
file: StaticString = #filePath, line: UInt = #line)
{
check(c.combinations(ofCount: l), countsAre: n, file: file, line: line)
}
/// XCTAsserts that the `count` and `underestimatedCount` of
/// `c.combinations(ofCount: l)` are both `n` at the given `file` and
/// `line`.
func check<R: RangeExpression>(
cHas n: Int,
combinationsOfLengths l: R,
file: StaticString = #filePath, line: UInt = #line) where R.Bound == Int
{
check(c.combinations(ofCount: l), countsAre: n, file: file, line: line)
}
check(cHas: 1, combinationsOfLength: 0)
check(cHas: 4, combinationsOfLength: 1)
check(cHas: 6, combinationsOfLength: 2)
check(cHas: 1, combinationsOfLength: 4)
check(cHas: 1, combinationsOfLengths: 0...0)
check(cHas: 4, combinationsOfLengths: 1...1)
check(cHas: 10, combinationsOfLengths: 1...2)
check(cHas: 14, combinationsOfLengths: 1...3)
check(cHas: 11, combinationsOfLengths: 2...4)
// `k` greater than element count results in same number of combinations
check(cHas: 5, combinationsOfLengths: 3...10)
// `k` greater than element count results in same number of combinations
let c10 = c.combinations(ofCount: 3...10).count
XCTAssertEqual(c10, 5)
// `k` greater than element count results in same number of combinations
let c11 = c.combinations(ofCount: 4...10).count
XCTAssertEqual(c11, 1)
check(cHas: 1, combinationsOfLengths: 4...10)
// `k` entirely greater than element count results in no combinations
let c12 = c.combinations(ofCount: 5...10).count
XCTAssertEqual(c12, 0)
check(cHas: 0, combinationsOfLengths: 5...10)
let c13 = c.combinations(ofCount: 0...).count
XCTAssertEqual(c13, 16)
let c14 = c.combinations(ofCount: ...3).count
XCTAssertEqual(c14, 15)
let c15 = c.combinations(ofCount: 0...).count
XCTAssertEqual(c15, 16)
check(cHas: 16, combinationsOfLengths: 0...)
check(cHas: 15, combinationsOfLengths: ...3)
}
func testCombinations() {
@@ -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 final 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 final 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"])
}
}
+1 -1
View File
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
import XCTest
@testable import Algorithms
import Algorithms
final class SuffixTests: XCTestCase {
func testSuffix() {
@@ -216,7 +216,7 @@ extension IndexValidator {
/// - expectedCount:
///
/// - Complexity: O(*n*^3) where *n* is the length of the collection if the
/// collection conforms to `RandomAccesCollection`, otherwise O(*n*^4).
/// collection conforms to `RandomAccessCollection`, otherwise O(*n*^4).
func validate(
_ collection: C,
expectedCount: Int? = nil,
+3 -2
View File
@@ -75,9 +75,10 @@ final class TrimTests: XCTestCase {
}
// Self == Self.Subsequence
func testTrimPrefixNoAmbiguity() {
func testTrimPrefixNoAmbiguity() throws {
var values = [2, 10, 12, 15, 20, 100] as ArraySlice
values.trimPrefix { $0.isMultiple(of: 2) }
// FIXME: `trimPrefix` in the _StringProcessing module always `throws`
try values.trimPrefix { $0.isMultiple(of: 2) }
XCTAssertEqual(values, [15, 20, 100])
}