Compare commits

..
Author SHA1 Message Date
Nate Cook eb93e564d4 Add Sequence.randomElement()
The stdlib's randomElement() method extends Collection, since it
operates by selecting a random index. This adds randomElement() as
a Sequence method, specializing the reservoir sampling algorithm
from randomSample(count:) for a count of 1.
2022-03-07 18:17:41 -06:00
Nate Cook 11fda519ef Various and sundry random test improvements 2022-03-07 18:14:08 -06:00
49 changed files with 359 additions and 2212 deletions

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
version: 1
builder:
configs:
- documentation_targets: [Algorithms]
+2 -85
View File
@@ -10,75 +10,6 @@ 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
@@ -338,9 +269,7 @@ 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.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
[Unreleased]: https://github.com/apple/swift-algorithms/compare/1.0.0...HEAD
[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
@@ -370,7 +299,6 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
[#85]: https://github.com/apple/swift-algorithms/pull/85
[#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
@@ -379,42 +307,32 @@ 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
[iainsmith]: https://github.com/apple/swift-algorithms/commits?author=iainsmith
[IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen
[iainsmith]: https://github.com/apple/swift-algorithms/commits?author=iainsmith
[iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7
[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
@@ -426,4 +344,3 @@ 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,6 +5,9 @@
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()
+39 -56
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 nonoverlapping subsequences:
Break a collection into subsequences where consecutive elements pass a binary
predicate, or where all elements in each chunk project to the same value.
* `chunked(by:)` forms chunks of consecutive elements that pass a binary predicate,
* `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.
Also includes a `chunks(ofCount:)` that breaks a collection into subsequences
of a given `count`.
`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:
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:
```swift
let numbers = [10, 20, 30, 10, 40, 40, 10, 20]
@@ -31,10 +31,11 @@ let chunks = names.chunked(on: \.first!)
// [("D", ["David"]), ("K", ["Kyle", "Karoy"]), ("N", ["Nate"])]
```
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.
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.
```swift
let names = ["David", "Kyle", "Karoy", "Nate"]
@@ -45,26 +46,11 @@ let remaining = names.chunks(ofCount: 3)
// equivalent to [["David", "Kyle", "Karoy"], ["Nate"]]
```
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]
```
The `chunks(ofCount:)` is the subject of an [existing SE proposal][proposal].
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 results in a collection equivalent
to the original.
Joining the result of a chunking method call recreates the original collection.
```swift
c.elementsEqual(c.chunked(...).joined())
@@ -75,45 +61,42 @@ c.elementsEqual(c.chunked(...).joined())
## Detailed Design
The four methods are added to `Collection`, with matching versions of
`chunked(by:)` and `chunked(on:)` that return a lazy wrapper added to
`LazyCollectionProtocol`.
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`.
```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
) -> [SubSequence]
public func chunks(ofCount count: Int) -> ChunkedByCount<Self>
public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection<Self>
) -> [(Subject, SubSequence)]
public func chunks(ofCount count: Int) -> ChunksOfCountCollection<Self>
}
extension LazyCollectionProtocol {
public func chunked(
by belongInSameGroup: @escaping (Element, Element) -> Bool
) -> ChunkedByCollection<Elements>
extension LazySequenceProtocol where Self: Collection, Elements: Collection {
public func chunked(
by belongInSameGroup: @escaping (Element, Element) -> Bool
) -> ChunkedByCollection<Elements, Element>
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>
}
```
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.
The `ChunkedByCollection`, `ChunkedOnCollection`, and `ChunksOfCountCollection`
types are bidirectional when the wrapped collection is bidirectional.
`ChunksOfCountCollection` also conforms to `LazySequenceProtocol` when the base
collection conforms.
### Complexity
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.
The eager methods are O(_n_), the lazy methods are O(_1_).
### Naming
@@ -137,5 +120,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, of which the
standard version corresponds to the `chunks(ofCount:)` method defined here.
**Rust:** Rust defines a variety of size-based `chunks` methods, but doesn’t
include any with the functionality described 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's API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/). A few other options were considered:
Swift API 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
@@ -1,68 +0,0 @@
# 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
@@ -1,78 +0,0 @@
# 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`.
-53
View File
@@ -1,53 +0,0 @@
# 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
+29 -50
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)]
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.
Returns a `SubSequence` formed by discarding all elements at the start and 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,44 +17,24 @@ 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
New methods are added to `Collection` and `BidirectionalCollection`:
A new method is added to `BidirectionalCollection`:
```swift
extension Collection {
func trimmingPrefix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
}
extension BidirectionalCollection {
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
public func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
}
```
There are also overloads of the mutating methods when `Self == Self.SubSequence`,
for non-range-replaceable self-slicing types.
This method requires `BidirectionalCollection` for an efficient implementation
which visits as few elements as possible.
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:
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 {
@@ -70,29 +50,28 @@ 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.
#### Supporting Methods
### >= 0.3.0
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.
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.
```swift
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
}
let myString = " hello, world "
print(myString.trimmingPrefix(while: \.isWhitespace)) // "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
}
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"
```
### Complexity
+3 -8
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.7
// swift-tools-version:5.1
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
@@ -20,19 +20,14 @@ let package = Package(
targets: ["Algorithms"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-numerics.git", from: "1.0.0"),
.package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"),
],
targets: [
.target(
name: "Algorithms",
dependencies: [
.product(name: "RealModule", package: "swift-numerics"),
],
swiftSettings: [
.define("INSERTION_TEMP"),
// .define("INSERTION_MAX_32"),
]
),
]),
.testTarget(
name: "SwiftAlgorithmsTests",
dependencies: ["Algorithms"]),
+42 -26
View File
@@ -2,35 +2,55 @@
**Swift Algorithms** is an open-source package of sequence and collection algorithms, along with their related types.
## Overview
Read more about the package, and the intent behind it, in the [announcement on swift.org](https://swift.org/blog/swift-algorithms/).
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.
## Contents
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 / 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]]
```
- [`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.
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:
#### Mutating algorithms
```swift
let names = ["Cassie", "Chloe", "Jasmine", "Jordan", "Taylor"]
let chunks = names.chunked(on: \.first)
// [["Cassie", "Chloe"], ["Jasmine", "Jordan"], ["Taylor"]]
```
- [`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.
Explore more chunking methods and the remainder of the `Algorithms` package in the links below.
#### Combining collections
## Documentation
- [`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.
For API documentation, see the library's official documentation in Xcode or on the Web.
#### Subsetting operations
- [API documentation][docs]
- [Swift.org announcement][announcement]
- [API Proposals/Guides][guides]
- [`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.
- [`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.
## Adding Swift Algorithms as a Dependency
@@ -38,7 +58,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.2.0"),
.package(url: "https://github.com/apple/swift-algorithms", from: "1.0.0"),
```
Include `"Algorithms"` as a dependency for your executable target:
@@ -55,12 +75,8 @@ Finally, add `import Algorithms` to your source code.
The Swift Algorithms package is source stable; version numbers follow [Semantic Versioning](https://semver.org/). Source breaking changes to public API can only land in a new major version.
The public API of the `swift-algorithms` package consists of non-underscored declarations that are marked `public` in the `Algorithms` module. Interfaces that aren't part of the public API may continue to change in any release, including patch releases.
The public API of version 1.0 of the `swift-algorithms` package consists of non-underscored declarations that are marked `public` in the `Algorithms` module. Interfaces that aren't part of the public API may continue to change in any release, including patch releases.
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
+2 -13
View File
@@ -10,8 +10,7 @@
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a sequence of overlapping adjacent pairs of the elements of this
/// sequence.
/// Creates a sequence of adjacent pairs of elements from 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
@@ -25,11 +24,6 @@ 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)
@@ -37,7 +31,7 @@ extension Sequence {
}
extension Collection {
/// Returns a collection of overlapping adjacent pairs of the elements of this
/// A collection of adjacent pairs of elements built from an underlying
/// collection.
///
/// In an `AdjacentPairsCollection`, the elements of the *i*th pair are the
@@ -52,11 +46,6 @@ 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)
+15 -302
View File
@@ -198,210 +198,6 @@ 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:)
//===----------------------------------------------------------------------===//
@@ -410,9 +206,6 @@ 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(
@@ -425,11 +218,7 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
}
/// Returns a lazy collection of subsequences of this collection, chunked by
/// 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.
/// grouping elements that project to the same value.
///
/// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable
@@ -450,10 +239,6 @@ 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(
@@ -481,11 +266,7 @@ extension Collection {
}
/// Returns a collection of subsequences of this collection, chunked by
/// 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.
/// grouping elements that project to the same value.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable
@@ -777,37 +558,22 @@ extension ChunksOfCountCollection {
}
extension Collection {
/// Returns a collection of subsequences, each with up to the specified
/// length.
/// Returns a `ChunksOfCountCollection<Self>` view presenting the elements in
/// chunks with count of the given count parameter.
///
/// 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.
/// - 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.
///
/// 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]
/// 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]]
///
/// 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`.
/// print(c.chunks(ofCount: 3).map(Array.init))
/// // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
///
/// - 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!")
@@ -817,58 +583,5 @@ extension Collection {
extension ChunksOfCountCollection.Index: Hashable where Base.Index: Hashable {}
extension ChunksOfCountCollection: LazySequenceProtocol
extension ChunksOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {}
extension ChunksOfCountCollection: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
//===----------------------------------------------------------------------===//
// evenlyChunked(in:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns a collection of evenly divided consecutive subsequences of this
/// collection.
///
/// This method divides the collection into a given number of evenly sized
/// chunks. If the length of the collection is not divisible by `count`, the
/// chunks at the start will be longer than the chunks at the end, like in
/// this example:
///
/// for chunk in "Hello, world!".evenlyChunked(in: 5) {
/// print(chunk)
/// }
/// // "Hel"
/// // "lo,"
/// // " wo"
/// // "rl"
/// // "d!"
///
/// If the number passed as `count` is greater than the number of elements in
/// the collection, the result will include one or more empty subsequences.
///
/// for chunk in "Hi!".evenlyChunked(in: 5) {
/// print(chunk)
/// }
/// // "H"
/// // "i"
/// // "!"
/// // ""
/// // ""
///
/// - Parameter count: The number of chunks to evenly divide this collection
/// into. If this collection is non-empty, `count` must be greater than
/// zero; otherwise, `count` may be zero or greater.
/// - Returns: A collection of `count` subsequences of this collection,
/// divided as evenly as possible.
///
/// - Complexity: O(1) if the collection conforms to `RandomAccessCollection`;
/// otherwise, O(*n*), where *n* is the length of the collection.
@inlinable
public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection<Self> {
precondition(count >= 0, "Can't divide into a negative number of chunks")
precondition(count > 0 || isEmpty, "Can't divide a non-empty collection into 0 chunks")
return EvenlyChunkedCollection(base: self, numberOfChunks: count)
}
}
+2 -6
View File
@@ -78,10 +78,6 @@ 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 {
@@ -293,8 +289,8 @@ extension Collection {
/// - Parameter k: The number of elements to include in each combination.
///
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since
/// `CombinationsSequence` accesses the `count` of the base collection.
/// is the number of elements in the base collection, since
/// `CombinationsSequence` accesses the `count` of the base collection.
@inlinable
public func combinations(ofCount k: Int) -> CombinationsSequence<Self> {
precondition(k >= 0, "Can't have combinations with a negative number of elements.")
@@ -1,42 +0,0 @@
# ``Algorithms``
**Swift Algorithms** is an open-source package of sequence and collection algorithms,
along with their related types.
## Overview
The Algorithms package provides a variety of sequence and collection operations, letting you cycle over a collection's elements, find combinations and permutations, create a random sample, and more.
For example, the package includes a group of "chunking" methods, each of which breaks a collection into consecutive subsequences. One version tests adjacent elements to find the breaking point between chunks — you can use it to quickly separate an array into ascending runs:
```swift
let numbers = [10, 20, 30, 10, 40, 40, 10, 20]
let chunks = numbers.chunked(by: { $0 <= $1 })
// [[10, 20, 30], [10, 40, 40], [10, 20]]
```
Another version looks for a change in the transformation of each successive value. You can use that to separate a list of names into groups by the first character:
```swift
let names = ["Cassie", "Chloe", "Jasmine", "Jordan", "Taylor"]
let chunks = names.chunked(on: \.first)
// [["Cassie", "Chloe"], ["Jasmine", "Jordan"], ["Taylor"]]
```
Explore more chunking methods and the remainder of the Algorithms package, grouped in the following topics.
## Topics
- <doc:CombinationsPermutations>
- <doc:SlicingSplitting>
- <doc:Chunking>
- <doc:Joining>
- <doc:Extending>
- <doc:Trimming>
- <doc:Keying>
- <doc:Sampling>
- <doc:MinAndMax>
- <doc:Selecting>
- <doc:Filtering>
- <doc:Reductions>
- <doc:Partitioning>
@@ -1,40 +0,0 @@
# Chunking
Break collections into consecutive chunks by length, count, or based on closure-based logic.
## Overview
_Chunking_ is the process of breaking a collection into consecutive subsequences, without dropping or duplicating any of the collection's elements. After chunking a collection, joining the resulting subsequences produces the original collection of elements, unlike _splitting_, which consumes the separator element(s).
```swift
let names = ["Ji-sun", "Jin-su", "Min-jae", "Young-ho"]
let evenlyChunked = names.chunks(ofCount: 2)
// ~ [["Ji-sun", "Jin-su"], ["Min-jae", "Young-ho"]]
let chunkedByFirstLetter = names.chunked(on: \.first)
// equivalent to [("J", ["Ji-sun", "Jin-su"]), ("M", ["Min-jae"]), ("Y", ["Young-ho"])]
```
## Topics
### Chunking a Collection by Count
- ``Swift/Collection/chunks(ofCount:)``
- ``Swift/Collection/evenlyChunked(in:)``
### Chunking a Collection by Predicate
- ``Swift/Collection/chunked(by:)``
- ``Swift/LazySequenceProtocol/chunked(by:)``
### Chunking a Collection by Subject
- ``Swift/Collection/chunked(on:)``
- ``Swift/LazySequenceProtocol/chunked(on:)``
### Supporting Types
- ``ChunkedByCollection``
- ``ChunkedOnCollection``
- ``ChunksOfCountCollection``
- ``EvenlyChunkedCollection``
@@ -1,32 +0,0 @@
# Combinations and Permutations
Find the combinations and permutations of any collection's elements,
or the product of two different collections.
## Topics
### Combinations
- ``Swift/Collection/combinations(ofCount:)-26o4x``
- ``Swift/Collection/combinations(ofCount:)-53jql``
### Permutations
- ``Swift/Collection/permutations(ofCount:)-7rc99``
- ``Swift/Collection/permutations(ofCount:)-5zvhn``
### Unique Permutations
- ``Swift/Collection/uniquePermutations(ofCount:)-2extq``
- ``Swift/Collection/uniquePermutations(ofCount:)-48r1k``
### Product
- ``product(_:_:)``
### Supporting Types
- ``CombinationsSequence``
- ``PermutationsSequence``
- ``UniquePermutationsSequence``
- ``Product2Sequence``
@@ -1,14 +0,0 @@
# DeprecatedScan
These methods are deprecated; use the `reductions` family of methods instead.
See: <doc:Reductions>
## Topics
- ``Swift/Sequence/scan(_:)``
- ``Swift/Sequence/scan(_:_:)``
- ``Swift/Sequence/scan(into:_:)``
- ``Swift/LazySequenceProtocol/scan(_:)``
- ``Swift/LazySequenceProtocol/scan(_:_:)``
- ``Swift/LazySequenceProtocol/scan(into:_:)``
@@ -1,42 +0,0 @@
# Extending
Chain two collections end-to-end,
or repeat a collection forever or a specific number of times.
## Overview
_Chaining_ two collections
```swift
let letters = chain("abcd", "EFGH")
// String(letters) == "abcdEFGH"
for (num, letter) in zip((1...3).cycled(), letters) {
print(num, letter)
}
// 1 a
// 2 b
// 3 c
// 1 d
// 2 E
// 3 F
// 1 G
// 2 H
```
## Topics
### Chaining Two Collections
- ``chain(_:_:)``
### Cycling a Collection
- ``Swift/Collection/cycled()``
- ``Swift/Collection/cycled(times:)``
### Supporting Types
- ``Chain2Sequence``
- ``CycledSequence``
- ``CycledTimesCollection``
@@ -1,41 +0,0 @@
# Filtering
Remove duplicated elements or strip the `nil` values from a sequence or collection.
## Overview
Use the _uniquing_ methods to remove duplicates from a sequence or collection, or to remove elements that have a duplicated property.
```swift
let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1]
let unique = numbers.uniqued()
// Array(unique) == [1, 2, 3]
```
The `compacted()` method removes all `nil` values from a sequence or collection of optionals:
```swift
let array: [Int?] = [10, nil, 30, nil, 2, 3, nil, 5]
let withNoNils = array.compacted()
// Array(withNoNils) == [10, 30, 2, 3, 5]
```
## Topics
### Uniquing Elements
- ``Swift/Sequence/uniqued()``
- ``Swift/Sequence/uniqued(on:)``
- ``Swift/LazySequenceProtocol/uniqued(on:)``
### Filtering out `nil` Elements
- ``Swift/Collection/compacted()``
- ``Swift/Sequence/compacted()``
### Supporting Types
- ``UniquedSequence``
- ``CompactedSequence``
- ``CompactedCollection``
@@ -1,35 +0,0 @@
# Joining
Join the parts of a collection of collections,
providing a connecting element or collection,
or a closure that produces the connector.
## Topics
### Joining by an Element
- ``Swift/Sequence/joined(by:)-6mrf9``
- ``Swift/Sequence/joined(by:)-9hyaf``
- ``Swift/Collection/joined(by:)-430ue``
- ``Swift/LazySequenceProtocol/joined(by:)-3yjw0``
- ``Swift/LazySequenceProtocol/joined(by:)-47xvy``
### Joining by a Collection
- ``Swift/Sequence/joined(by:)-62j1h``
- ``Swift/Sequence/joined(by:)-9b108``
- ``Swift/Collection/joined(by:)-28n3b``
- ``Swift/LazySequenceProtocol/joined(by:)-4neii``
- ``Swift/LazySequenceProtocol/joined(by:)-49xws``
### Interspersing Elements
- ``Swift/Sequence/interspersed(with:)``
### Supporting Types
- ``JoinedBySequence``
- ``JoinedByCollection``
- ``JoinedByClosureSequence``
- ``JoinedByClosureCollection``
- ``InterspersedSequence``
@@ -1,14 +0,0 @@
# 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:)``
@@ -1,23 +0,0 @@
# Finding the Minimum and Maximum
Find the minimum and maximum elements simultaneously,
or a specific number of elements at the minimum and maximum.
## Topics
### Finding Minimum or Maximum Elements
- ``Swift/Sequence/min(count:)``
- ``Swift/Collection/min(count:)``
- ``Swift/Sequence/min(count:sortedBy:)``
- ``Swift/Collection/min(count:sortedBy:)``
- ``Swift/Sequence/max(count:)``
- ``Swift/Collection/max(count:)``
- ``Swift/Sequence/max(count:sortedBy:)``
- ``Swift/Collection/max(count:sortedBy:)``
### Finding the Minimum and Maximum Elements Simultaneously
- ``Swift/Sequence/minAndMax()``
- ``Swift/Sequence/minAndMax(by:)``
@@ -1,63 +0,0 @@
# Partitioning and Rotating
Partition a collection according to a unary predicate,
rotate a collection around a particular index,
or find the index where a collection is already partitioned.
## Overview
A _stable partition_ maintains the relative order of elements within both partitions.
```swift
// partition(by:) - unstable ordering
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
let p1 = numbers.partition(by: { $0.isMultiple(of: 20) })
// p1 == 4
// numbers == [10, 70, 30, 50, 40, 60, 20, 80]
// ^ start of second partition
// stablePartition(by:) - maintains relative ordering
numbers = [10, 20, 30, 40, 50, 60, 70, 80]
let p2 = numbers.stablePartition(by: { $0.isMultiple(of: 20) })
// p2 == 4
// numbers == [10, 30, 50, 70, 20, 40, 60, 80]
// ^ start of second partition
```
Use the `rotate` method to shift the elements of a collection to start at a new position, moving the displaced elements to the end:
```swift
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
let p = numbers.rotate(toStartAt: 2)
// numbers == [30, 40, 50, 60, 70, 80, 10, 20]
// p == 6 -- numbers[p] == 10
```
## Topics
### Stable Partition
- ``Swift/MutableCollection/stablePartition(by:)``
- ``Swift/MutableCollection/stablePartition(subrange:by:)``
- ``Swift/Sequence/partitioned(by:)``
- ``Swift/Collection/partitioned(by:)``
### Partition of Subranges
- ``Swift/MutableCollection/partition(subrange:by:)-5vdh7``
- ``Swift/MutableCollection/partition(subrange:by:)-4gpqz``
### Finding a Partition Index
- ``Swift/Collection/partitioningIndex(where:)``
### Rotation
- ``Swift/MutableCollection/rotate(toStartAt:)-9fp48``
- ``Swift/MutableCollection/rotate(toStartAt:)-2r55j``
- ``Swift/MutableCollection/rotate(subrange:toStartAt:)-ov6a``
- ``Swift/MutableCollection/rotate(subrange:toStartAt:)-5teoq``
### Reversing
- ``Swift/MutableCollection/reverse(subrange:)``
@@ -1,35 +0,0 @@
# Reductions
Find the incremental values of a sequence "reduce" operation.
## Overview
Call one of the `reductions` methods when you want the result of a `reduce` operation along with all of its intermediate values:
```swift
let exclusiveRunningTotal = (1...5).reductions(0, +)
print(exclusiveRunningTotal)
// prints [0, 1, 3, 6, 10, 15]
let inclusiveRunningTotal = (1...5).reductions(+)
print(inclusiveRunningTotal)
// prints [1, 3, 6, 10, 15]
```
## Topics
- ``Swift/Sequence/reductions(_:)``
- ``Swift/Sequence/reductions(_:_:)``
- ``Swift/Sequence/reductions(into:_:)``
- ``Swift/LazySequenceProtocol/reductions(_:)``
- ``Swift/LazySequenceProtocol/reductions(_:_:)``
- ``Swift/LazySequenceProtocol/reductions(into:_:)``
### Supporting Types
- ``InclusiveReductionsSequence``
- ``ExclusiveReductionsSequence``
### Deprecated Methods
- <doc:DeprecatedScan>
@@ -1,17 +0,0 @@
# Random Sampling
Choose a specified number of random elements from a sequence or collection.
## Topics
### Random Sampling
- ``Swift/Sequence/randomSample(count:)``
- ``Swift/Collection/randomSample(count:)``
- ``Swift/Collection/randomStableSample(count:)``
### Random Sampling with a Generator
- ``Swift/Sequence/randomSample(count:using:)``
- ``Swift/Collection/randomSample(count:using:)``
- ``Swift/Collection/randomStableSample(count:using:)``
@@ -1,25 +0,0 @@
# Selecting Elements
Select elements at a particular interval, the first mapped value,
or iterate of elements with their indices.
## Topics
### Selecting Elements at an Interval
- ``Swift/Sequence/striding(by:)``
- ``Swift/Collection/striding(by:)``
### Conditionally Finding the First Mapped Value
- ``Swift/Sequence/firstNonNil(_:)``
### Iterating Over Elements with Their Indices
- ``Swift/Collection/indexed()``
### Supporting Types
- ``IndexedCollection``
- ``StridingSequence``
- ``StridingCollection``
@@ -1,29 +0,0 @@
# Slicing and Splitting
Iterate over tuple pairs of adjacent elements, overlapping windows of a specified size, or lazily-calculated splits.
## Topics
### Adjacent Pairs
- ``Swift/Sequence/adjacentPairs()``
- ``Swift/Collection/adjacentPairs()``
### Windows
- ``Swift/Collection/windows(ofCount:)``
### Lazily Splitting a Collection
- ``Swift/LazySequenceProtocol/split(separator:maxSplits:omittingEmptySubsequences:)-4q4x8``
- ``Swift/LazySequenceProtocol/split(maxSplits:omittingEmptySubsequences:whereSeparator:)-68oqf``
- ``Swift/LazySequenceProtocol/split(separator:maxSplits:omittingEmptySubsequences:)-a46s``
- ``Swift/LazySequenceProtocol/split(maxSplits:omittingEmptySubsequences:whereSeparator:)-3rwee``
### Supporting Types
- ``AdjacentPairsSequence``
- ``AdjacentPairsCollection``
- ``WindowsOfCountCollection``
- ``SplitSequence``
- ``SplitCollection``
@@ -1,32 +0,0 @@
# Trimming
Remove unwanted elements from the start, the end, or both ends of a collection.
## Topics
### Trimming Both Ends of a Collection
- ``Swift/BidirectionalCollection/trimming(while:)``
- ``Swift/BidirectionalCollection/trim(while:)-781az``
- ``Swift/BidirectionalCollection/trim(while:)-6cbz3``
### Trimming from the Start
- ``Swift/Collection/trimmingPrefix(while:)``
- ``Swift/Collection/trimPrefix(while:)-2r8n8``
- ``Swift/Collection/trimPrefix(while:)-93obt``
### Trimming from the End
- ``Swift/BidirectionalCollection/trimmingSuffix(while:)``
- ``Swift/BidirectionalCollection/trimSuffix(while:)-33ubj``
- ``Swift/BidirectionalCollection/trimSuffix(while:)-3o6x9``
### Finding the Suffix of a Collection
- ``Swift/BidirectionalCollection/suffix(while:)``
### Finding Boundaries within a Collection
- ``Swift/Collection/endOfPrefix(while:)``
- ``Swift/BidirectionalCollection/startOfSuffix(while:)``
-25
View File
@@ -1,25 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Sequence {
/// Groups up elements of `self` into a new Dictionary,
/// whose values are Arrays of grouped elements,
/// each keyed by the group key returned by the given closure.
/// - Parameters:
/// - keyForValue: A closure that returns a key for each element in
/// `self`.
/// - Returns: A dictionary containing grouped elements of self, keyed by
/// the keys derived by the `keyForValue` closure.
@inlinable
public func grouped<GroupKey>(by keyForValue: (Element) throws -> GroupKey) rethrows -> [GroupKey: [Element]] {
try Dictionary(grouping: self, by: keyForValue)
}
}
+1 -5
View File
@@ -94,10 +94,6 @@ 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.
///
@@ -109,7 +105,7 @@ extension Collection {
/// }
/// }
///
/// - Returns: A collection of paired indices and elements of this collection.
/// Returns: A collection of paired indices and elements of this collection.
@inlinable
public func indexed() -> IndexedCollection<Self> {
IndexedCollection(base: self)
-65
View File
@@ -1,65 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Sequence {
/// Creates a new Dictionary from the elements of `self`, keyed by the
/// results returned by the given `keyForValue` closure.
///
/// If the key derived for a new element collides with an existing key from a previous element,
/// the latest value will be kept.
///
/// - Parameters:
/// - keyForValue: A closure that returns a key for each element in `self`.
@inlinable
public func keyed<Key>(
by keyForValue: (Element) throws -> Key
) rethrows -> [Key: Element] {
return try self.keyed(by: keyForValue, resolvingConflictsWith: { _, old, new in new })
}
/// Creates a new Dictionary from the elements of `self`, keyed by the
/// results returned by the given `keyForValue` closure. As the dictionary is
/// built, the initializer calls the `resolve` closure with the current and
/// new values for any duplicate keys. Pass a closure as `resolve` that
/// returns the value to use in the resulting dictionary: The closure can
/// choose between the two values, combine them to produce a new value, or
/// even throw an error.
///
/// - Parameters:
/// - keyForValue: A closure that returns a key for each element in `self`.
/// - resolve: A closure that is called with the values for any duplicate
/// keys that are encountered. The closure returns the desired value for
/// the final dictionary.
@inlinable
public func keyed<Key>(
by keyForValue: (Element) throws -> Key,
resolvingConflictsWith resolve: (Key, Element, Element) throws -> Element
) rethrows -> [Key: Element] {
var result = [Key: Element]()
for element in self {
let key = try keyForValue(element)
if let oldValue = result.updateValue(element, forKey: key) {
let valueToKeep = try resolve(key, oldValue, element)
// This causes a second look-up for the same key. The standard library can avoid that
// by calling `mutatingFind` to get access to the bucket where the value will end up,
// and updating in place.
// Swift Algorithms doesn't have access to that API, so we make do.
// When this gets merged into the standard library, we should optimize this.
result[key] = valueToKeep
}
}
return result
}
}
+11 -11
View File
@@ -125,7 +125,7 @@ extension Sequence {
/// largest values:
///
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let largestThree = numbers.max(count: 3, sortedBy: <)
/// let smallestThree = numbers.max(count: 3, sortedBy: <)
/// // [7, 8, 9]
///
/// If you need to sort a sequence but only need to access its largest
@@ -197,7 +197,7 @@ extension Sequence where Element: Comparable {
/// largest values:
///
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let largestThree = numbers.max(count: 3)
/// let smallestThree = numbers.max(count: 3)
/// // [7, 8, 9]
///
/// If you need to sort a sequence but only need to access its largest
@@ -256,14 +256,14 @@ extension Collection {
"""
)
// Make sure we are within bounds.
let prefixCount = Swift.min(count, self.count)
// Do nothing if we're prefixing nothing.
guard prefixCount > 0 else {
guard count > 0 else {
return []
}
// Make sure we are within bounds.
let prefixCount = Swift.min(count, self.count)
// If we're attempting to prefix more than 10% of the collection, it's
// faster to sort everything.
guard prefixCount < (self.count / 10) else {
@@ -280,7 +280,7 @@ extension Collection {
/// largest values:
///
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let largestThree = numbers.max(count: 3, sortedBy: <)
/// let smallestThree = numbers.max(count: 3, sortedBy: <)
/// // [7, 8, 9]
///
/// If you need to sort a collection but only need to access its largest
@@ -310,14 +310,14 @@ extension Collection {
"""
)
// Make sure we are within bounds.
let suffixCount = Swift.min(count, self.count)
// Do nothing if we're suffixing nothing.
guard suffixCount > 0 else {
guard count > 0 else {
return []
}
// Make sure we are within bounds.
let suffixCount = Swift.min(count, self.count)
// If we're attempting to prefix more than 10% of the collection, it's
// faster to sort everything.
guard suffixCount < (self.count / 10) else {
-539
View File
@@ -1,539 +0,0 @@
extension Int {
@inlinable
internal var _log2: Int {
Self.bitWidth - leadingZeroBitCount
}
}
@inlinable internal var _partialInsertionSortSwapLimit: Int { 8 }
@inlinable internal var _insertionSortMaxCount: Int {
#if INSERTION_MAX_32
32
#else
20
#endif
}
@inlinable internal var _medianOfMediansMinCount: Int { 200 }
extension MutableCollection where Self: BidirectionalCollection {
@inlinable
internal mutating func _partialInsertionSort(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Bool {
if range.isEmpty {
return true
}
var sortedEnd = index(after: range.lowerBound)
var swaps = 0
// Continue sorting until the sorted elements cover the whole sequence.
while sortedEnd != range.upperBound {
var i = sortedEnd
// Look backwards for `self[i]`'s position in the sorted sequence,
// moving each element forward to make room.
repeat {
let j = index(before: i)
// If `self[i]` doesn't belong before `self[j]`, we've found
// its position.
if try !areInIncreasingOrder(self[i], self[j]) {
break
}
swapAt(i, j)
i = j
// Quit if we've completed more than the swap limit.
swaps += 1
if swaps > _partialInsertionSortSwapLimit { return false }
} while i != range.lowerBound
formIndex(after: &sortedEnd)
}
return true
}
/// Sorts `self[range]` according to `areInIncreasingOrder`. Stable.
///
/// - Precondition: `sortedEnd != range.lowerBound`
/// - Precondition: `elements[..<sortedEnd]` are already in order.
@inlinable
public
mutating func _insertionSort(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
if range.isEmpty {
return
}
var sortedEnd = index(after: range.lowerBound)
// Continue sorting until the sorted elements cover the whole sequence.
while sortedEnd != range.upperBound {
var i = sortedEnd
#if INSERTION_TEMP
let temp = self[i]
#endif
// Look backwards for `self[i]`'s position in the sorted sequence,
// moving each element forward to make room.
repeat {
let j = index(before: i)
// If `self[i]` doesn't belong before `self[j]`, we've found
// its position.
#if INSERTION_TEMP
if try !areInIncreasingOrder(temp, self[j]) {
break
}
self[j] = self[i]
#else
if try !areInIncreasingOrder(self[i], self[j]) {
break
}
swapAt(i, j)
#endif
i = j
} while i != range.lowerBound
#if INSERTION_TEMP
self[i] = temp
#endif
formIndex(after: &sortedEnd)
}
}
@inlinable
internal mutating func _sort2(
_ a: Index, _ b: Index,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
if try areInIncreasingOrder(self[b], self[a]) {
swapAt(a, b)
}
}
@inlinable
internal mutating func _sort3a(
_ a: Index, _ b: Index, _ c: Index,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
try _sort2(a, b, by: areInIncreasingOrder)
try _sort2(b, c, by: areInIncreasingOrder)
try _sort2(a, b, by: areInIncreasingOrder)
}
/// Sorts the elements at `elements[a]`, `elements[b]`, and `elements[c]` to
/// match the relative order of `a`, `b`, and `c`.
@inlinable
internal mutating func _sort3(
_ a: Index, _ b: Index, _ c: Index,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
// There are thirteen possible permutations for the original ordering of
// the elements at indices `a`, `b`, and `c`. The comments in the code below
// show the relative ordering of the three elements using a three-digit
// number as shorthand for the position and comparative relationship of
// each element. For example, "312" indicates that the element at `a` is the
// largest of the three, the element at `b` is the smallest, and the element
// at `c` is the median. This hypothetical input array has a 312 ordering for
// `a`, `b`, and `c`:
//
// [ 7, 4, 3, 9, 2, 0, 3, 7, 6, 5 ]
// ^ ^ ^
// a b c
//
// - If each of the three elements is distinct, they could be ordered as any
// of the permutations of 1, 2, and 3: 123, 132, 213, 231, 312, or 321.
// - If two elements are equivalent and one is distinct, they could be
// ordered as any permutation of 1, 1, and 2 or 1, 2, and 2: 112, 121, 211,
// 122, 212, or 221.
// - If all three elements are equivalent, they are already in order: 111.
switch try (areInIncreasingOrder(self[b], self[a]),
areInIncreasingOrder(self[c], self[b])) {
case (false, false):
// 0 swaps: 123, 112, 122, 111
break
case (true, true):
// 1 swap: 321
// swap(a, c): 312->123
swapAt(a, c)
case (true, false):
// 1 swap: 213, 212 --- 2 swaps: 312, 211
// swap(a, b): 213->123, 212->122, 312->132, 211->121
swapAt(a, b)
if try areInIncreasingOrder(self[c], self[b]) {
// 132 (started as 312), 121 (started as 211)
// swap(b, c): 132->123, 121->112
swapAt(b, c)
}
case (false, true):
// 1 swap: 132, 121 --- 2 swaps: 231, 221
// swap(b, c): 132->123, 121->112, 231->213, 221->212
swapAt(b, c)
if try areInIncreasingOrder(self[b], self[a]) {
// 213 (started as 231), 212 (started as 221)
// swap(a, b): 213->123, 212->122
swapAt(a, b)
}
}
}
}
extension MutableCollection where Self: RandomAccessCollection {
@inlinable
internal mutating func _siftDown(
_ idx: Index,
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
var idx = idx
var countToIndex = distance(from: range.lowerBound, to: idx)
var countFromIndex = distance(from: idx, to: range.upperBound)
// Check if left child is within bounds. If not, stop iterating, because
// there are no children of the given node in the heap.
while countToIndex + 1 < countFromIndex {
let left = index(idx, offsetBy: countToIndex + 1)
var largest = idx
if try areInIncreasingOrder(self[largest], self[left]) {
largest = left
}
// Check if right child is also within bounds before trying to examine it.
if countToIndex + 2 < countFromIndex {
let right = index(after: left)
if try areInIncreasingOrder(self[largest], self[right]) {
largest = right
}
}
// If a child is bigger than the current node, swap them and continue
// sifting down.
if largest != idx {
swapAt(idx, largest)
idx = largest
countToIndex = distance(from: range.lowerBound, to: idx)
countFromIndex = distance(from: idx, to: range.upperBound)
} else {
break
}
}
}
@inlinable
internal mutating func _heapify(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
// Here we build a heap starting from the lowest nodes and moving to the
// root. On every step we sift down the current node to obey the max-heap
// property:
// parent >= max(leftChild, rightChild)
//
// We skip the rightmost half of the array, because these nodes don't have
// any children.
let root = range.lowerBound
let half = distance(from: range.lowerBound, to: range.upperBound) / 2
var node = index(root, offsetBy: half)
while node != root {
formIndex(before: &node)
try _siftDown(node, within: range, by: areInIncreasingOrder)
}
}
@inlinable
internal mutating func _heapSort(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
var hi = range.upperBound
let lo = range.lowerBound
try _heapify(within: range, by: areInIncreasingOrder)
formIndex(before: &hi)
while hi != lo {
swapAt(lo, hi)
try _siftDown(lo, within: lo..<hi, by: areInIncreasingOrder)
formIndex(before: &hi)
}
}
}
extension MutableCollection where Self: BidirectionalCollection {
@inlinable
public // testing
mutating func _partitionLeft(
subrange: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Index {
assert(distance(from: subrange.lowerBound, to: subrange.upperBound) >= 2)
var (low, high) = (subrange.lowerBound, subrange.upperBound)
let pivot = self[subrange.lowerBound]
// Search from end for last element equal to or less than pivot.
repeat {
formIndex(before: &high)
// Don't need a separate `high > low` check, since self[low] == pivot,
// which is a terminating condition based on comparison above.
} while try areInIncreasingOrder(pivot, self[high])
// Search from beginning for first element greater than pivot.
if high == index(before: subrange.upperBound) {
while low < high {
formIndex(after: &low)
guard try !areInIncreasingOrder(pivot, self[low]) else {
break
}
}
} else {
repeat {
formIndex(after: &low)
} while try !areInIncreasingOrder(pivot, self[low])
}
// Swap remaining elements as needed.
while low < high {
swapAt(low, high)
repeat {
formIndex(before: &high)
} while try areInIncreasingOrder(pivot, self[high])
repeat {
formIndex(after: &low)
} while try !areInIncreasingOrder(pivot, self[low])
}
// Move pivot to end of lower partition and return its position.
swapAt(subrange.lowerBound, high)
return high
}
@inlinable
public // testing
mutating func _partitionRight(
subrange: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> (Index, alreadyPartitioned: Bool) {
assert(distance(from: subrange.lowerBound, to: subrange.upperBound) >= 2)
var (low, high) = (subrange.lowerBound, subrange.upperBound)
let pivot = self[subrange.lowerBound]
// Search from start for first element greater than or equal to pivot.
repeat {
formIndex(after: &low)
} while try areInIncreasingOrder(self[low], pivot)
// Search from end for last element less than pivot.
if low == index(after: subrange.lowerBound) {
while low < high {
formIndex(before: &high)
guard try !areInIncreasingOrder(self[high], pivot) else {
break
}
}
} else {
repeat {
formIndex(before: &high)
} while try !areInIncreasingOrder(self[high], pivot)
}
let noSwapsRequired = low >= high
// Swap remaining elements as needed.
while low < high {
swapAt(low, high)
repeat {
formIndex(after: &low)
} while try areInIncreasingOrder(self[low], pivot)
repeat {
formIndex(before: &high)
} while try !areInIncreasingOrder(self[high], pivot)
}
// Move pivot to start of upper partition and return its position.
let result = index(before: low)
swapAt(subrange.lowerBound, result)
return (result, noSwapsRequired)
}
}
extension MutableCollection where Self: RandomAccessCollection {
@inlinable
public // testing
mutating func _preparePivot(
subrange: Range<Index>,
count: Int,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
let low = subrange.lowerBound
let high = index(before: subrange.upperBound)
let mid = index(low, offsetBy: count / 2)
if count > _medianOfMediansMinCount {
// Sort three "letter groups" of elements:
// [A1, B1, C1, ..., A2, B2, C2, ..., C3, B3, A3]
let low2 = index(after: low)
let high2 = index(before: high)
let midLo = index(before: mid)
let midHi = index(after: mid)
try _sort3(low, midLo, high, by: areInIncreasingOrder)
try _sort3(low2, mid, high2, by: areInIncreasingOrder)
try _sort3(
index(after: low2), midHi, index(before: high2),
by: areInIncreasingOrder)
// After sorting, each lettered group of elements is sorted, so the
// middle three elements are the three medians. Sort those three.
try _sort3(midLo, mid, midHi, by: areInIncreasingOrder)
// The median of medians is the pivot; move it to the front.
swapAt(low, mid)
} else {
// Note the order of index parameters; the smallest element will be at `mid`,
// the middle element at `low`, and the largest element at `high`:
try _sort3(mid, low, high, by: areInIncreasingOrder)
}
}
@inlinable
internal mutating func _shuffleElements(subrange: Range<Index>, count: Int) {
guard count > _insertionSortMaxCount else { return }
var low = subrange.lowerBound
var lowQuarter = index(low, offsetBy: count / 4)
var high = index(before: subrange.upperBound)
var highQuarter = index(high, offsetBy: -count / 4)
swapAt(low, lowQuarter)
swapAt(high, highQuarter)
if count > _insertionSortMaxCount {
for _ in 0..<2 {
formIndex(after: &low)
formIndex(before: &lowQuarter)
formIndex(before: &high)
formIndex(after: &highQuarter)
swapAt(low, lowQuarter)
swapAt(high, highQuarter)
}
}
}
@inlinable
internal mutating func _pdqSortImpl(
subrange: Range<Index>,
count: Int,
isLeftmost: Bool,
remainingBadPartitions: Int,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
guard count > _insertionSortMaxCount else {
try _insertionSort(within: subrange, by: areInIncreasingOrder)
return
}
try _preparePivot(subrange: subrange, count: count, by: areInIncreasingOrder)
if !isLeftmost {
let predecessor = index(before: subrange.lowerBound)
if try !areInIncreasingOrder(self[predecessor], self[subrange.lowerBound]) {
let newLow = try _partitionLeft(subrange: subrange, by: areInIncreasingOrder)
try _pdqSortImpl(
subrange: newLow..<subrange.upperBound,
count: distance(from: newLow, to: subrange.upperBound),
isLeftmost: false,
remainingBadPartitions: remainingBadPartitions,
by: areInIncreasingOrder)
return
}
}
let (pivot, alreadyPartitioned) = try _partitionRight(
subrange: subrange, by: areInIncreasingOrder)
let startOfUpper = index(after: pivot)
let lowerCount = distance(from: subrange.lowerBound, to: pivot)
let upperCount = count - lowerCount - 1
let minPartitionSize = count / 8
let isBadPartition = lowerCount < minPartitionSize || upperCount < minPartitionSize
var remainingBadPartitions = remainingBadPartitions
if isBadPartition {
// If we've had too many bad partitions, fall back to heap sort.
remainingBadPartitions -= 1
guard remainingBadPartitions > 0 else {
try _heapSort(within: subrange, by: areInIncreasingOrder)
return
}
// Try shuffling elements within the partition to decrease chance of poor
// pivot selection.
_shuffleElements(subrange: subrange.lowerBound..<pivot, count: lowerCount)
_shuffleElements(subrange: startOfUpper..<subrange.upperBound, count: upperCount)
} else {
// If there were no swaps required, use insertion sort to scan for already
// sorted partitions, including some minor fix-ups.
if alreadyPartitioned {
if try _partialInsertionSort(within: subrange.lowerBound..<pivot, by: areInIncreasingOrder)
&& _partialInsertionSort(within: startOfUpper..<subrange.upperBound, by: areInIncreasingOrder) {
return
}
}
}
try _pdqSortImpl(
subrange: subrange.lowerBound..<pivot,
count: lowerCount,
isLeftmost: isLeftmost,
remainingBadPartitions: remainingBadPartitions,
by: areInIncreasingOrder)
try _pdqSortImpl(
subrange: startOfUpper..<subrange.upperBound,
count: upperCount,
isLeftmost: false,
remainingBadPartitions: remainingBadPartitions,
by: areInIncreasingOrder)
}
@inlinable
public mutating func sortUnstable(
subrange: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
let count = distance(from: subrange.lowerBound, to: subrange.upperBound)
try _pdqSortImpl(
subrange: subrange,
count: count,
isLeftmost: true,
remainingBadPartitions: count._log2,
by: areInIncreasingOrder)
}
@inlinable
public mutating func sortUnstable(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
try sortUnstable(subrange: startIndex..<endIndex, by: areInIncreasingOrder)
}
}
extension MutableCollection where Self: RandomAccessCollection, Element: Comparable {
@inlinable
public mutating func sortUnstable(subrange: Range<Index>) {
sortUnstable(subrange: subrange, by: <)
}
@inlinable
public mutating func sortUnstable() {
sortUnstable(by: <)
}
}
+6 -10
View File
@@ -210,8 +210,8 @@ extension Collection {
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns two arrays containing the elements of the sequence that
/// don’t and do satisfy the given predicate, respectively.
/// Returns two arrays containing, in order, the elements of the sequence that
/// do and don’t satisfy the given predicate.
///
/// In this example, `partitioned(by:)` is used to separate the input based on
/// whether a name is shorter than five characters:
@@ -230,9 +230,7 @@ extension Sequence {
///
/// - Returns: Two arrays with all of the elements of the receiver. The
/// first array contains all the elements that `predicate` didn’t allow, and
/// the second array contains all the elements that `predicate` allowed. The
/// order of the elements in the arrays matches the order of the elements in
/// the original sequence.
/// the second array contains all the elements that `predicate` allowed.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
@@ -255,8 +253,8 @@ extension Sequence {
}
extension Collection {
/// Returns two arrays containing the elements of the collection that
/// don’t and do satisfy the given predicate, respectively.
/// Returns two arrays containing, in order, the elements of the collection
/// that do and don’t satisfy the given predicate.
///
/// In this example, `partitioned(by:)` is used to separate the input based on
/// whether a name is shorter than five characters.
@@ -275,9 +273,7 @@ extension Collection {
///
/// - Returns: Two arrays with all of the elements of the receiver. The
/// first array contains all the elements that `predicate` didn’t allow, and
/// the second array contains all the elements that `predicate` allowed. The
/// order of the elements in the arrays matches the order of the elements in
/// the original collection.
/// the second array contains all the elements that `predicate` allowed.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
+58 -6
View File
@@ -10,14 +10,8 @@
//===----------------------------------------------------------------------===//
// For log(_:) and root(_:_:)
#if swift(>=5.11)
internal import RealModule
#elseif swift(>=5.10)
import RealModule
#else
@_implementationOnly
import RealModule
#endif
//===----------------------------------------------------------------------===//
// randomStableSample(count:)
@@ -241,3 +235,61 @@ extension Sequence {
return randomSample(count: k, using: &g)
}
}
//===----------------------------------------------------------------------===//
// randomElement()
//===----------------------------------------------------------------------===//
// This method is a single-element specialization of `randomSample(count:)`,
// and extends the stdlib's `randomElement()` functionality (which is available
// for collections) down to sequences.
extension Sequence {
/// Randomly selects an element from this sequence, using the given generator
/// as the source of randomness.
///
/// - Parameter rng: The random number generator to use for sampling.
/// - Returns: A random element. If the sequence has no elements, this method
/// returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func randomElement<G: RandomNumberGenerator>(
using rng: inout G
) -> Element? {
var iterator = makeIterator()
guard var result = iterator.next() else {
return nil
}
var w = 1.0
while true {
w *= nextW(k: 1, using: &rng)
var offset = nextOffset(w: w, using: &rng)
while offset > 0, let _ = iterator.next() {
offset -= 1
}
guard let nextElement = iterator.next()
else { break }
result = nextElement
}
return result
}
/// Randomly selects an element from this sequence.
///
/// This method is equivalent to calling `randomSample(using:)`, passing in
/// the system's default random generator.
///
/// - Returns: A random element. If the sequence has no elements, this method
/// returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func randomElement() -> Element? {
var g = SystemRandomNumberGenerator()
return randomElement(using: &g)
}
}
+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
// subsequence ended with a separator. Start searching for the next
// susequence ended with a separator. Start searching for the next
// subsequence at the following element.
subsequenceStart = base.index(after: i.baseRange.upperBound)
}
+2 -2
View File
@@ -46,7 +46,7 @@ extension Collection {
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func endOfPrefix(
internal func endOfPrefix(
while predicate: (Element) throws -> Bool
) rethrows -> Index {
var index = startIndex
@@ -72,7 +72,7 @@ extension BidirectionalCollection {
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func startOfSuffix(
internal func startOfSuffix(
while predicate: (Element) throws -> Bool
) rethrows -> Index {
var index = endIndex
+6 -6
View File
@@ -32,7 +32,7 @@ extension Collection {
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
let start = try endOfPrefix(while: predicate)
return self[start..<endIndex]
return self[start...]
}
}
@@ -61,8 +61,8 @@ extension Collection where Self: RangeReplaceableCollection {
public mutating func trimPrefix(
while predicate: (Element) throws -> Bool
) rethrows {
let startOfResult = try endOfPrefix(while: predicate)
removeSubrange(startIndex..<startOfResult)
let end = try endOfPrefix(while: predicate)
removeSubrange(startIndex..<end)
}
}
@@ -135,7 +135,7 @@ extension BidirectionalCollection {
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
let end = try startOfSuffix(while: predicate)
return self[startIndex..<end]
return self[..<end]
}
}
@@ -188,8 +188,8 @@ extension BidirectionalCollection where Self: RangeReplaceableCollection {
public mutating func trimSuffix(
while predicate: (Element) throws -> Bool
) rethrows {
let endOfResult = try startOfSuffix(while: predicate)
removeSubrange(endOfResult..<endIndex)
let start = try startOfSuffix(while: predicate)
removeSubrange(start..<endIndex)
}
}
+19
View File
@@ -0,0 +1,19 @@
//===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Argument Parser open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#error("""
-----------------------------------------------------
Please test with `swift test --enable-test-discovery`
-----------------------------------------------------
""")
+3 -33
View File
@@ -87,6 +87,9 @@ final class ChunkedTests: XCTestCase {
[1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }),
[[1, 2, 3, 4], [6, 7, 8, 9]])
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]])
@@ -170,37 +173,4 @@ 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,63 +15,57 @@ import Algorithms
final class CombinationsTests: XCTestCase {
func testCount() {
let c = "ABCD"
/// 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)
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)
// `k` greater than element count results in same number of combinations
check(cHas: 1, combinationsOfLengths: 4...10)
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)
// `k` entirely greater than element count results in no combinations
check(cHas: 0, combinationsOfLengths: 5...10)
let c12 = c.combinations(ofCount: 5...10).count
XCTAssertEqual(c12, 0)
check(cHas: 16, combinationsOfLengths: 0...)
check(cHas: 15, combinationsOfLengths: ...3)
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)
}
func testCombinations() {
@@ -1,46 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import Algorithms
final class GroupedTests: XCTestCase {
private class SampleError: Error {}
// Based on https://github.com/apple/swift/blob/4d1d8a9de5ebc132a17aee9fc267461facf89bf8/validation-test/stdlib/Dictionary.swift#L1974-L1988
func testGroupedBy() {
let r = 0..<10
let d1 = r.grouped(by: { $0 % 3 })
XCTAssertEqual(3, d1.count)
XCTAssertEqual(d1[0]!, [0, 3, 6, 9])
XCTAssertEqual(d1[1]!, [1, 4, 7])
XCTAssertEqual(d1[2]!, [2, 5, 8])
let d2 = r.grouped(by: { $0 })
XCTAssertEqual(10, d2.count)
let d3 = (0..<0).grouped(by: { $0 })
XCTAssertEqual(0, d3.count)
}
func testThrowingFromKeyFunction() {
let input = ["Apple", "Banana", "Cherry"]
let error = SampleError()
XCTAssertThrowsError(
try input.grouped(by: { (_: String) -> Character in throw error })
) { thrownError in
XCTAssertIdentical(error, thrownError as? SampleError)
}
}
}
@@ -1,88 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import Algorithms
final class KeyedTests: XCTestCase {
private class SampleError: Error {}
func testUniqueKeys() {
let d = ["Apple", "Banana", "Cherry"].keyed(by: { $0.first! })
XCTAssertEqual(d.count, 3)
XCTAssertEqual(d["A"]!, "Apple")
XCTAssertEqual(d["B"]!, "Banana")
XCTAssertEqual(d["C"]!, "Cherry")
XCTAssertNil(d["D"])
}
func testEmpty() {
let d = EmptyCollection<String>().keyed(by: { $0.first! })
XCTAssertEqual(d.count, 0)
}
func testNonUniqueKeys() throws {
let d = ["Apple", "Avocado", "Banana", "Cherry"].keyed(by: { $0.first! })
XCTAssertEqual(d.count, 3)
XCTAssertEqual(d["A"]!, "Avocado", "On a key-collision, keyed(by:) should take the latest value.")
XCTAssertEqual(d["B"]!, "Banana")
XCTAssertEqual(d["C"]!, "Cherry")
}
func testNonUniqueKeysWithMergeFunction() {
var resolveCallHistory = [(key: Character, current: String, new: String)]()
let expectedCallHistory = [
(key: "A", current: "Apple", new: "Avocado"),
(key: "C", current: "Cherry", new: "Coconut"),
]
let d = ["Apple", "Avocado", "Banana", "Cherry", "Coconut"].keyed(
by: { $0.first! },
resolvingConflictsWith: { key, older, newer in
resolveCallHistory.append((key, older, newer))
return "\(older)-\(newer)"
}
)
XCTAssertEqual(d.count, 3)
XCTAssertEqual(d["A"]!, "Apple-Avocado")
XCTAssertEqual(d["B"]!, "Banana")
XCTAssertEqual(d["C"]!, "Cherry-Coconut")
XCTAssertNil(d["D"])
XCTAssertEqual(
resolveCallHistory.map(String.init(describing:)), // quick/dirty workaround: tuples aren't Equatable
expectedCallHistory.map(String.init(describing:))
)
}
func testThrowingFromKeyFunction() {
let input = ["Apple", "Banana", "Cherry"]
let error = SampleError()
XCTAssertThrowsError(
try input.keyed(by: { (_: String) -> Character in throw error })
) { thrownError in
XCTAssertIdentical(error, thrownError as? SampleError)
}
}
func testThrowingFromCombineFunction() {
let input = ["Apple", "Avocado", "Banana", "Cherry"]
let error = SampleError()
XCTAssertThrowsError(
try input.keyed(by: { $0.first! }, resolvingConflictsWith: { _, _, _ in throw error })
) { thrownError in
XCTAssertIdentical(error, thrownError as? SampleError)
}
}
}
@@ -1,68 +0,0 @@
//===----------------------------------------------------------------------===//
//
// 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 PDQSortTests: XCTestCase {
func testPartitionLeft() {
for _ in 1...1000 {
var a = (0...20).map { _ in Int.random(in: 1...5) }
a._preparePivot(subrange: a.indices, count: a.indices.count, by: <)
let pivot = a._partitionLeft(subrange: a.indices, by: <)
for x in a[..<pivot] {
XCTAssertLessThanOrEqual(x, a[pivot])
}
for x in a[(pivot + 1)...] {
XCTAssertGreaterThan(x, a[pivot])
}
}
}
func testPartitionRight() {
for _ in 1...1000 {
var a = (0...20).map { _ in Int.random(in: 1...5) }
a._preparePivot(subrange: a.indices, count: a.indices.count, by: <)
let (pivot, _) = a._partitionRight(subrange: a.indices, by: <)
for x in a[..<pivot] {
XCTAssertLessThan(x, a[pivot])
}
for x in a[(pivot + 1)...] {
XCTAssertGreaterThanOrEqual(x, a[pivot])
}
}
}
func testSort() {
var empty: [Int] = []
empty.sortUnstable()
var inOrder = Array(1...1000)
inOrder.sortUnstable()
XCTAssert(inOrder.isSorted())
var reversed = Array((1...1000).reversed())
reversed.sortUnstable()
XCTAssert(reversed.isSorted())
for _ in 1...1000 {
var a = (0...Int.random(in: 100...1000)).map { _ in Int.random(in: 1...50) }
a.sortUnstable()
XCTAssert(a.isSorted())
}
}
func testSpecialCase() {
var a = (1...10).shuffled() + [20] + (31...40).shuffled()
a.sortUnstable()
XCTAssert(a.isSorted())
}
}
@@ -12,13 +12,17 @@
import XCTest
@testable import Algorithms
func expectedRange(for value: Int) -> ClosedRange<Int> {
((value / 3) * 2) ... ((value / 3) * 4)
}
func validateRandomSamples<S: Sequence>(
_ samples: [Int: Int],
elements: S,
expectedValue: Int,
file: StaticString = #file, line: UInt = #line
) where S.Element == Int {
let expectedRange = ((expectedValue / 3) * 2) ... ((expectedValue / 3) * 4)
let expectedRange = expectedRange(for: expectedValue)
XCTAssertEqualSequences(samples.keys.sorted(), elements,
file: file, line: line)
for v in samples.values {
@@ -28,41 +32,44 @@ func validateRandomSamples<S: Sequence>(
private let n = 100
private let k = 12
private let iterations = 10_000
private let iterations = 1000
/// A collection to sample from.
private let c = 0..<n
/// A sequence to sample from.
private let s = sequence(first: 0, next: { $0 == n - 1 ? nil : $0 + 1 })
/// An empty sequence
private let emptySequence = sequence(state: 0, next: { (_) -> Int? in nil })
final class RandomSampleTests: XCTestCase {
func testRandomStableSampleCollection() {
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
let sample = c.randomStableSample(count: k)
XCTAssert(sample.isSorted())
for x in sample {
result[x, default: 0] += 1
}
result.merge(sample.frequencies, uniquingKeysWith: +)
}
validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
}
func testRandomSampleCollection() {
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
for x in c.randomSample(count: k) {
result[x, default: 0] += 1
}
result.merge(c.randomSample(count: k).frequencies, uniquingKeysWith: +)
}
validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
}
func testRandomSampleSequence() {
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
for x in s.randomSample(count: k) {
result[x, default: 0] += 1
}
result.merge(s.randomSample(count: k).frequencies, uniquingKeysWith: +)
}
validateRandomSamples(samples, elements: s, expectedValue: (k * iterations) / n)
}
func testRandomSampleEdgeCases() {
XCTAssert(emptySequence.randomSample(count: 10).isEmpty)
XCTAssert(([] as [Int]).randomSample(count: 10).isEmpty)
XCTAssert(([] as [Int]).randomStableSample(count: 10).isEmpty)
XCTAssert(c.randomStableSample(count: 0).isEmpty)
XCTAssertEqualSequences(c.randomStableSample(count: n), c)
XCTAssertEqualSequences(c.randomStableSample(count: n * 2), c)
@@ -77,21 +84,23 @@ final class RandomSampleTests: XCTestCase {
}
func testRandomSampleRepeatable() {
var generator = SplitMix64(seed: 0)
let seed = UInt64.random(in: 0 ... .max)
var generator = SplitMix64(seed: seed)
let sample1a = c.randomSample(count: k, using: &generator)
generator = SplitMix64(seed: 0)
generator = SplitMix64(seed: seed)
let sample2a = c.randomSample(count: k, using: &generator)
XCTAssertEqual(sample1a, sample2a)
generator = SplitMix64(seed: 0)
generator = SplitMix64(seed: seed)
let sample1b = s.randomSample(count: k, using: &generator)
generator = SplitMix64(seed: 0)
generator = SplitMix64(seed: seed)
let sample2b = s.randomSample(count: k, using: &generator)
XCTAssertEqual(sample1b, sample2b)
generator = SplitMix64(seed: 0)
generator = SplitMix64(seed: seed)
let sample1c = c.randomStableSample(count: k, using: &generator)
generator = SplitMix64(seed: 0)
generator = SplitMix64(seed: seed)
let sample2c = c.randomStableSample(count: k, using: &generator)
XCTAssertEqual(sample1c, sample2c)
}
@@ -123,4 +132,37 @@ final class RandomSampleTests: XCTestCase {
almostAllZero = AlmostAllZeroGenerator(seed: 0)
_ = c.randomSample(count: k, using: &almostAllZero) // must not crash
}
func testSequenceRandomElement() {
XCTAssertNil(emptySequence.randomElement())
let expectedRange = expectedRange(for: iterations)
let randomElements = (0..<(n*iterations)).map { _ in
s.randomElement()!
}.frequencies
XCTAssertEqual(randomElements.count, n)
XCTAssert(randomElements.values.allSatisfy { expectedRange.contains($0) })
let oneElementSequence = sequence(first: 0, next: { _ in nil })
let randomOneElement = (0..<iterations).map { _ in
oneElementSequence.randomElement()!
}
XCTAssert(randomOneElement.allSatisfy { $0 == 0 })
let twoElementSequence = sequence(state: [1, 2].makeIterator(), next: { $0.next() })
let randomTwoElement = (0..<(2*iterations)).map { _ in
twoElementSequence.randomElement()!
}.frequencies
XCTAssertEqual(randomTwoElement.count, 2)
XCTAssert(randomElements.values.allSatisfy { expectedRange.contains($0) })
}
func testSequenceRandomElementRepeatable() {
let seed = UInt64.random(in: 0 ... .max)
var generator = SplitMix64(seed: seed)
let elements1 = (0..<500).map { _ in s.randomElement(using: &generator)! }
generator = SplitMix64(seed: seed)
let elements2 = (0..<500).map { _ in s.randomElement(using: &generator)! }
XCTAssertEqual(elements1, elements2)
}
}
+1 -1
View File
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
import XCTest
import Algorithms
@testable import Algorithms
final class SuffixTests: XCTestCase {
func testSuffix() {
@@ -23,6 +23,12 @@ extension Sequence where Element: Comparable {
}
}
extension Sequence where Element: Hashable {
var frequencies: [Element: Int] {
reduce(into: [:]) { $0[$1, default: 0] += 1 }
}
}
extension Numeric {
func factorial() -> Self {
guard self != 0 else { return 1 }
@@ -216,7 +222,7 @@ extension IndexValidator {
/// - expectedCount:
///
/// - Complexity: O(*n*^3) where *n* is the length of the collection if the
/// collection conforms to `RandomAccessCollection`, otherwise O(*n*^4).
/// collection conforms to `RandomAccesCollection`, otherwise O(*n*^4).
func validate(
_ collection: C,
expectedCount: Int? = nil,