mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-22 04:10:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb3bafeca0 | ||
|
|
c582aa9d22 | ||
|
|
53354f3f21 | ||
|
|
8ca636d702 | ||
|
|
115abe1f69 | ||
|
|
0dba0e5b87 | ||
|
|
a0b7954f80 | ||
|
|
73c4a21563 | ||
|
|
fb69aacc5d | ||
|
|
2beda36a49 | ||
|
|
864d460a07 | ||
|
|
3782207b2c | ||
|
|
c67dd3419c | ||
|
|
546c8bf7ba | ||
|
|
5c5a95db4a | ||
|
|
dd2ad89a1b | ||
|
|
1df76cfaa4 | ||
|
|
7188edf9c0 | ||
|
|
60d653f008 | ||
|
|
cffb44dceb | ||
|
|
af3eab4fb5 | ||
|
|
b1dee141cf | ||
|
|
cb028ba72a | ||
|
|
a8902448b9 | ||
|
|
7ab0a2014d |
No files matched your search
@@ -17,5 +17,5 @@ Replace this paragraph with a description of your changes and rationale. Provide
|
||||
### Checklist
|
||||
- [ ] I've added at least one test that validates that my change is working, if appropriate
|
||||
- [ ] I've followed the code style of the rest of the project
|
||||
- [ ] I've read the [Contribution Guidelines](CONTRIBUTING.md)
|
||||
- [ ] I've read the [Contribution Guidelines](../CONTRIBUTING.md)
|
||||
- [ ] I've updated the documentation if necessary
|
||||
@@ -34,5 +34,5 @@ What is the impact of this change on existing users? Does it deprecate or remove
|
||||
### Checklist
|
||||
- [ ] I've added at least one test that validates that my change is working, if appropriate
|
||||
- [ ] I've followed the code style of the rest of the project
|
||||
- [ ] I've read the [Contribution Guidelines](CONTRIBUTING.md)
|
||||
- [ ] I've read the [Contribution Guidelines](../../CONTRIBUTING.md)
|
||||
- [ ] I've updated the documentation if necessary
|
||||
@@ -4,3 +4,4 @@
|
||||
/*.xcodeproj
|
||||
xcuserdata/
|
||||
/.swiftpm
|
||||
Package.resolved
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<array/>
|
||||
</plist>
|
||||
+42
-1
@@ -16,6 +16,34 @@ package updates, you can specify your package dependency using
|
||||
|
||||
---
|
||||
|
||||
## [0.0.2] - 2020-10-23
|
||||
|
||||
### Changes
|
||||
|
||||
- The `rotate(at:)` method has been updated to `rotate(toStartAt:)`, with the
|
||||
old name deprecated.
|
||||
- The `chained(with:)` method has been changed to the free function
|
||||
`chain(_:_:)`, with the old version deprecated.
|
||||
- `Algorithms` now uses `RealModule` from the `swift-numerics` package for its
|
||||
cross-platform elementary functions.
|
||||
- Sequence/collection wrapper types, like `Permutations` and `Indexed`, now
|
||||
have conformance to the lazy protocols, so that any following operations
|
||||
maintain their laziness.
|
||||
|
||||
### Fixes
|
||||
|
||||
- Swift Algorithms now builds under SwiftPM on Windows.
|
||||
- A wide variety of errors, misspellings, and ommissions in the documentation
|
||||
and guides have been fixed.
|
||||
- Index/distance calculations for the `Product2` and `Chain` types have been
|
||||
corrected.
|
||||
- Calling `stablePartition(subrange:by:)` now correctly uses the subrange's
|
||||
length instead of the whole collection.
|
||||
|
||||
The 0.0.2 release includes contributions from [AustinConlon], [egorzhdan],
|
||||
[IanKeen], [iSame7], [karwa], [kylemacomber], [natecook1000], [nordicio],
|
||||
[pmtao], [schlagelk], [stephentyrone], and [timvermeulen]. Thank you!
|
||||
|
||||
## [0.0.1] - 2020-10-07
|
||||
|
||||
- **Swift Algorithms** initial release.
|
||||
@@ -26,10 +54,23 @@ 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/0.0.1...HEAD
|
||||
[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.0.2...HEAD
|
||||
[0.0.2]: https://github.com/apple/swift-algorithms/compare/0.0.1...0.0.2
|
||||
[0.0.1]: https://github.com/apple/swift-algorithms/releases/tag/0.0.1
|
||||
|
||||
<!-- Link references for pull requests -->
|
||||
|
||||
<!-- Link references for contributors -->
|
||||
|
||||
[AustinConlon]: https://github.com/apple/swift-algorithms/commits?author=AustinConlon
|
||||
[egorzhdan]: https://github.com/apple/swift-algorithms/commits?author=egorzhdan
|
||||
[IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen
|
||||
[iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7
|
||||
[karwa]: https://github.com/apple/swift-algorithms/commits?author=karwa
|
||||
[kylemacomber]: https://github.com/apple/swift-algorithms/commits?author=kylemacomber
|
||||
[natecook1000]: https://github.com/apple/swift-algorithms/commits?author=natecook1000
|
||||
[nordicio]: https://github.com/apple/swift-algorithms/commits?author=nordicio
|
||||
[pmtao]: https://github.com/apple/swift-algorithms/commits?author=pmtao
|
||||
[schlagelk]: https://github.com/apple/swift-algorithms/commits?author=schlagelk
|
||||
[stephentyrone]: https://github.com/apple/swift-algorithms/commits?author=stephentyrone
|
||||
[timvermeulen]: https://github.com/apple/swift-algorithms/commits?author=timvermeulen
|
||||
+22
-17
@@ -1,17 +1,18 @@
|
||||
# Chain
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Chain.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/ChainTests.swift)]
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ChainTests.swift)]
|
||||
|
||||
Concatenates two collections with the same element type, one after another.
|
||||
|
||||
This operation is available through the `chained(with:)` method on any sequence.
|
||||
This operation is available for any two sequences by calling the `chain(_:_:)`
|
||||
function.
|
||||
|
||||
```swift
|
||||
let numbers = [10, 20, 30].chained(with: 1...5)
|
||||
let numbers = chain([10, 20, 30], 1...5)
|
||||
// Array(numbers) == [10, 20, 30, 1, 2, 3, 4, 5]
|
||||
//
|
||||
let letters = "abcde".chained(with: "FGHIJ")
|
||||
|
||||
let letters = chain("abcde", "FGHIJ")
|
||||
// String(letters) == "abcdeFGHIJ"
|
||||
```
|
||||
|
||||
@@ -21,27 +22,31 @@ the shared conformances of the two underlying types.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `chained(with:)` method is added as an extension method on the `Sequence`
|
||||
protocol:
|
||||
The `chain(_:_:)` function takes two sequences as arguments:
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func chained<S: Sequence>(with other: S) -> Concatenation<Self, S>
|
||||
where Element == S.Element
|
||||
}
|
||||
|
||||
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2<S1, S2>
|
||||
where S1.Element == S2.Element
|
||||
```
|
||||
|
||||
The resulting `Chain` type is a sequence, with conditional conformance to the
|
||||
`Collection`, `BidirectionalCollection`, and `RandomAccessCollection` when both
|
||||
The resulting `Chain2` type is a sequence, with conditional conformance to
|
||||
`Collection`, `BidirectionalCollection`, and `RandomAccessCollection` when both
|
||||
the first and second arguments conform.
|
||||
|
||||
### Naming
|
||||
|
||||
This method’s and type’s name match the term of art used in other languages and
|
||||
libraries.
|
||||
This function's and type's name match the term of art used in other languages
|
||||
and libraries.
|
||||
|
||||
### Comparison with other langauges
|
||||
This operation was previously implemented as a `Sequence` method named
|
||||
`chained(with:)`, and was switched to a free function to align with APIs like
|
||||
`zip` and `product` after [a lengthy forum discussion][naming]. Alternative
|
||||
suggestions for method names include `appending(contentsOf:)`, `followed(by:)`,
|
||||
and `concatenated(to:)`.
|
||||
|
||||
[naming]: https://forums.swift.org/t/naming-of-chained-with/40999/
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
**Rust:** Rust provides a `chain` function that concatenates two iterators.
|
||||
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
# Chunked
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Chunked.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/ChunkedTests.swift)]
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ChunkedTests.swift)]
|
||||
|
||||
Break a collection into subsequences where consecutive elements pass a binary
|
||||
predicate, or where all elements in each chunk project to the same value.
|
||||
@@ -82,7 +82,7 @@ The operation performed by these methods is similar to other ways of breaking a
|
||||
- `sliced`: *Not included in this package or the stdlib.* Breaks a collection into potentially overlapping subsequences.
|
||||
|
||||
|
||||
### Comparison with other langauges
|
||||
### Comparison with other languages
|
||||
|
||||
**Ruby:** Ruby’s `Enumerable` class defines `chunk_while` and `chunk`, which map
|
||||
to the proposed `chunked(by:)` and `chunked(on:)` methods.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Combinations
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Combinations.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/CombinationsTests.swift)]
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/CombinationsTests.swift)]
|
||||
|
||||
A type that computes combinations of a collection’s elements.
|
||||
|
||||
@@ -29,7 +29,7 @@ collection are always treated as separate values in the resulting combinations:
|
||||
```swift
|
||||
let numbers2 = [20, 10, 10]
|
||||
for combo in numbers2.combinations(ofCount: 2) {
|
||||
print(perm)
|
||||
print(combo)
|
||||
}
|
||||
// [20, 10]
|
||||
// [20, 10]
|
||||
@@ -51,7 +51,8 @@ Since the `Combinations` type needs to store an array of the collection’s
|
||||
indices and mutate the array to generate each permutation, `Combinations` only
|
||||
has `Sequence` conformance. Adding `Collection` conformance would require
|
||||
storing the array in the index type, which would in turn lead to copying the
|
||||
array at every index advancement.
|
||||
array at every index advancement. `Combinations` does conform to
|
||||
`LazySequenceProtocol` when the base type conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
@@ -74,7 +75,7 @@ Swift API guidelines. A few other options were considered:
|
||||
- `k` is used a term of art for combinations and permutations, but isn't
|
||||
widely used in programming contexts.
|
||||
|
||||
### Comparison with other langauges
|
||||
### Comparison with other languages
|
||||
|
||||
**Rust/Ruby/Python:** Rust, Ruby, and Python all define functions with
|
||||
essentially the same semantics as the method described here.
|
||||
+8
-6
@@ -1,7 +1,7 @@
|
||||
# Cycle
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Cycle.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/CycleTests.swift)]
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/CycleTests.swift)]
|
||||
|
||||
Iterate over a collection forever, or a set number of times.
|
||||
|
||||
@@ -33,10 +33,12 @@ extension Collection {
|
||||
```
|
||||
|
||||
The new `Cycle` type is a sequence only, given that the `Collection` protocol
|
||||
design makes infinitely large types impossible/impractical. Note that despite
|
||||
its name, the returned `FlattenSequence` will always have `Collection`
|
||||
conformance, and will have `BidirectionalCollection` conformance when called on
|
||||
a bidirectional collection.
|
||||
design makes infinitely large types impossible/impractical. `Cycle` also
|
||||
conforms to `LazySequenceProtocol` when the base type conforms.
|
||||
|
||||
Note that despite its name, the returned `FlattenSequence` will always have
|
||||
`Collection` conformance, and will have `BidirectionalCollection` conformance
|
||||
when called on a bidirectional collection.
|
||||
|
||||
### Complexity
|
||||
|
||||
@@ -50,7 +52,7 @@ run-through of elements (the actual semantics) or starting after the first
|
||||
set. This ambiguity is present in all the different potential names for this
|
||||
function: `repeated(times:)`, `cycled(repetitions:)`, etc.
|
||||
|
||||
### Comparison with other langauges
|
||||
### Comparison with other languages
|
||||
|
||||
**Rust:** The `cycle` method repeats an iterator's elements forever. I don’t see
|
||||
anything that matches the `cycled(times:)` behavior.
|
||||
|
||||
+5
-4
@@ -1,7 +1,7 @@
|
||||
# Indexed
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Indexed.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/IndexedTests.swift)]
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/IndexedTests.swift)]
|
||||
|
||||
The `enumerated` method, but pairing each element with its index instead of an
|
||||
incrementing integer counter.
|
||||
@@ -24,11 +24,12 @@ for (i, n) in numbers.indexed() {
|
||||
The `indexed` method returns an `Indexed` type:
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
extension Collection {
|
||||
func indexed() -> Indexed<Self>
|
||||
}
|
||||
```
|
||||
|
||||
`Indexed` scales from a sequence up to a random-access collection, depending on
|
||||
its base type.
|
||||
`Indexed` scales from a collection up to a random-access collection, depending on
|
||||
its base type. `Indexed` also conforms to `LazySequenceProtocol` when the base type
|
||||
conforms.
|
||||
|
||||
+4
-4
@@ -1,7 +1,7 @@
|
||||
# Partition
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Partition.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/PartitionTests.swift)]
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/PartitionTests.swift)]
|
||||
|
||||
Methods for performing a stable partition on mutable collections, and for
|
||||
finding the partitioning index in an already partitioned collection.
|
||||
@@ -74,15 +74,15 @@ extension Collection {
|
||||
### Complexity
|
||||
|
||||
The existing partition is an O(_n_) operations, where _n_ is the length of the
|
||||
range to be partitioned, while the stable partition is O(_n log n_). Both
|
||||
range to be partitioned, while the stable partition is O(_n_ log _n_). Both
|
||||
partitions have algorithms with improved performance for bidirectional
|
||||
collections, so it would be ideal for those to be customization points were they
|
||||
to eventually land in the standard library.
|
||||
|
||||
`partitioningIndex(where:)` is a slight generalization of a binary search, and
|
||||
is an O(_log n_) operation for random-access collections; O(_n_) otherwise.
|
||||
is an O(log _n_) operation for random-access collections; O(_n_) otherwise.
|
||||
|
||||
### Comparison with other langauges
|
||||
### Comparison with other languages
|
||||
|
||||
**C++:** The `<algorithm>` library defines `partition`, `stable_partition`, and
|
||||
`partition_point` functions with similar semantics to these. Notably, in the C++
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Permutations
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Permutations.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/PermutationsTests.swift)]
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/PermutationsTests.swift)]
|
||||
|
||||
A type that computes permutations of a collection’s elements, or of a subset of
|
||||
those elements.
|
||||
@@ -75,7 +75,8 @@ Since the `Permutations` type needs to store an array of the collection’s
|
||||
indices and mutate the array to generate each permutation, `Permutations` only
|
||||
has `Sequence` conformance. Adding `Collection` conformance would require
|
||||
storing the array in the index type, which would in turn lead to copying the
|
||||
array at every index advancement.
|
||||
array at every index advancement. `Combinations` does conform to
|
||||
`LazySequenceProtocol` when the base type conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
@@ -87,7 +88,7 @@ O(_n_) operation.
|
||||
|
||||
See the ["Naming" section for `combinations(ofCount:)`](Combinations.md#naming) for detail.
|
||||
|
||||
### Comparison with other langauges
|
||||
### Comparison with other languages
|
||||
|
||||
**C++:** The `<algorithm>` library defines a `next_permutation` function that
|
||||
advances an array of comparable values through their lexicographic orderings.
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
# Product
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Product.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/ProductTests.swift)]
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ProductTests.swift)]
|
||||
|
||||
A function for iterating over every pair of elements in two different
|
||||
collections.
|
||||
@@ -53,12 +53,12 @@ collection operations on the resulting wrapper are O(_m \* n_).
|
||||
|
||||
### Naming
|
||||
|
||||
This function and the resulting collection provide the cartestian product of two
|
||||
This function and the resulting collection provide the cartesian product of two
|
||||
collections. While `product` is precedented in other languages, the name has an
|
||||
unfortunate overlap with multiplication, where `product(numbers1, numbers2)`
|
||||
could be seen as producing an element-wise product.
|
||||
|
||||
### Comparison with other langauges
|
||||
### Comparison with other languages
|
||||
|
||||
**Ruby:** You can call the `product` method on an array, passing one or more
|
||||
arrays to form n-ary tuples — passing a single array gives the same semantics as
|
||||
|
||||
+10
-10
@@ -1,7 +1,7 @@
|
||||
# Random Sampling
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/RandomSample.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/RandomSampleTests.swift)]
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/RandomSampleTests.swift)]
|
||||
|
||||
Operations for randomly selecting `k` elements without replacement from a
|
||||
sequence or collection.
|
||||
@@ -74,7 +74,7 @@ returns a single random element. The `randomSample(count:)` name is chosen to
|
||||
align with `randomElement`, but be more distinguishable than something like
|
||||
`randomElements`. Other names considered include `sample` and `choose`.
|
||||
|
||||
### Comparison with other langauges
|
||||
### Comparison with other languages
|
||||
|
||||
**C++:** As of C++17, the `<algorithm>` library includes a `sample` function
|
||||
that provides linear performance. This algorithm is stable for all source
|
||||
@@ -95,7 +95,7 @@ unstable implementation of `randomSample` explicitly shuffles the elements
|
||||
before returning them.
|
||||
|
||||
To see the bias without shuffling, consider the following example that uses a
|
||||
hypothetical `randomElementsUnshuffled` method. When selecting three out of
|
||||
hypothetical `randomSampleUnshuffled` method. When selecting three out of
|
||||
four elements from an array, whenever any of the first three elements are
|
||||
included in the result, they are always in their original positions. Elements
|
||||
selected after the initial `count` are in randomly selected positions.
|
||||
@@ -104,19 +104,19 @@ selected after the initial `count` are in randomly selected positions.
|
||||
// This shows the behavior WITHOUT post-sample shuffling.
|
||||
// Selecting 3/4 elements, there are only four possible outcomes:
|
||||
let source = [10, 20, 30, 40]
|
||||
source.randomElementsUnshuffled(count: 3) // [10, 20, 30]
|
||||
source.randomElementsUnshuffled(count: 3) // [40, 20, 30]
|
||||
source.randomElementsUnshuffled(count: 3) // [10, 40, 30]
|
||||
source.randomElementsUnshuffled(count: 3) // [10, 20, 40]
|
||||
source.randomSampleUnshuffled(count: 3) // [10, 20, 30]
|
||||
source.randomSampleUnshuffled(count: 3) // [40, 20, 30]
|
||||
source.randomSampleUnshuffled(count: 3) // [10, 40, 30]
|
||||
source.randomSampleUnshuffled(count: 3) // [10, 20, 40]
|
||||
```
|
||||
|
||||
The proposed `randomElements` method has no positional bias:
|
||||
The proposed `randomSample` method has no positional bias:
|
||||
|
||||
```swift
|
||||
// The current behavior shuffles the elements, erasing the bias:
|
||||
let source = [10, 20, 30, 40]
|
||||
source.randomElements(count: 3) // [20, 30, 10]
|
||||
source.randomElements(count: 3) // [40, 20, 30]
|
||||
source.randomSample(count: 3) // [20, 30, 10]
|
||||
source.randomSample(count: 3) // [40, 20, 30]
|
||||
// ...several more possible outcomes
|
||||
```
|
||||
|
||||
|
||||
+12
-11
@@ -1,13 +1,13 @@
|
||||
# Rotate
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Rotate.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/RotateTests.swift)]
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/RotateTests.swift)]
|
||||
|
||||
A mutating method that rotates the elements of a collection to new positions.
|
||||
|
||||
```swift
|
||||
var numbers = [10, 20, 30, 40, 50, 60]
|
||||
let p = numbers.rotate(at: 2)
|
||||
let p = numbers.rotate(toStartAt: 2)
|
||||
// numbers == [30, 40, 50, 60, 10, 20]
|
||||
// p == 4 -- numbers[p] == 10
|
||||
```
|
||||
@@ -18,9 +18,9 @@ variants that take a range:
|
||||
|
||||
```swift
|
||||
var numbers = [10, 20, 30, 40, 50, 60]
|
||||
numbers.rotate(subrange: 0..<3, at: 1)
|
||||
numbers.rotate(subrange: 0..<3, toStartAt: 1)
|
||||
// numbers = [20, 30, 10, 40, 50, 60]
|
||||
numbers.rotate(subrange: 3..<6, at: 4)
|
||||
numbers.rotate(subrange: 3..<6, toStartAt: 4)
|
||||
// numbers = [20, 30, 10, 50, 60, 40]
|
||||
```
|
||||
|
||||
@@ -30,11 +30,11 @@ This adds the two `MutableCollection` methods shown above:
|
||||
|
||||
```swift
|
||||
extension MutableCollection {
|
||||
mutating func rotate(at p: Index) -> Index
|
||||
mutating func rotate(toStartAt p: Index) -> Index
|
||||
|
||||
mutating func rotate(
|
||||
subrange: Range<Index>,
|
||||
at p: Index
|
||||
toStartAt p: Index
|
||||
) -> Index
|
||||
}
|
||||
```
|
||||
@@ -49,15 +49,16 @@ the number of swaps required per element, so `rotate` would need to be a
|
||||
### Naming
|
||||
|
||||
The index parameter has been proposed as `shiftingToStart` in the past; this
|
||||
proposal uses the simpler `at` label. `shiftingToStart` introduces the idea of
|
||||
a "shift", which can sound like shifting just that single element to the
|
||||
version uses the `toStartAt` label, instead. `shiftingToStart` introduces the
|
||||
idea of a "shift", which can sound like shifting just that single element to the
|
||||
beginning of the collection.
|
||||
|
||||
For the range-based overloads, the label could be omitted. That is, instead of
|
||||
using `subrange:`, the method could be called as
|
||||
`numbers.rotate(0..<3, at: 2)`.
|
||||
`numbers.rotate(0..<3, toStartAt: 2)`. The label is included here for
|
||||
consistency with other range-based mutating methods.
|
||||
|
||||
### Comparison with other langauges
|
||||
### Comparison with other languages
|
||||
|
||||
**C++:** The `<algorithm>` library defines a `rotate` function with similar
|
||||
semantics to this one.
|
||||
@@ -65,5 +66,5 @@ semantics to this one.
|
||||
**Ruby:** You can rotate the elements of an array by a number of positions,
|
||||
either forward or backward (by passing a negative number). For zero-indexed
|
||||
collections, forward rotation by e.g. 3 elements is equivalent to
|
||||
`rotate(at: 3)`.
|
||||
`rotate(toStartAt: 3)`.
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
# Unique
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Unique.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/UniqueTests.swift)]
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/UniqueTests.swift)]
|
||||
|
||||
Methods to strip repeated elements from a sequence or collection.
|
||||
|
||||
@@ -38,7 +38,7 @@ extension Sequence {
|
||||
|
||||
The `uniqued` methods are O(_n_) in both time and space complexity.
|
||||
|
||||
### Comparison with other langauges
|
||||
### Comparison with other languages
|
||||
|
||||
**C+\+:** The `<algorithm>` library defines a `unique` function that removes
|
||||
consecutive equal elements.
|
||||
|
||||
+4
-1
@@ -20,11 +20,14 @@ let package = Package(
|
||||
targets: ["Algorithms"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-numerics", from: "0.0.1"),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "Algorithms",
|
||||
dependencies: []),
|
||||
dependencies: [
|
||||
.product(name: "RealModule", package: "swift-numerics"),
|
||||
]),
|
||||
.testTarget(
|
||||
name: "SwiftAlgorithmsTests",
|
||||
dependencies: ["Algorithms"]),
|
||||
|
||||
@@ -18,7 +18,7 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
||||
|
||||
#### Combining collections
|
||||
|
||||
- [`chained(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chain.md): Concatenates two collections with the same element type.
|
||||
- [`chain(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chain.md): Concatenates two collections with the same element type.
|
||||
- [`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.
|
||||
- [`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.
|
||||
|
||||
|
||||
+125
-71
@@ -10,7 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A concatenation of two sequences with the same element type.
|
||||
public struct Chain<Base1: Sequence, Base2: Sequence>
|
||||
public struct Chain2<Base1: Sequence, Base2: Sequence>
|
||||
where Base1.Element == Base2.Element
|
||||
{
|
||||
/// The first sequence in this chain.
|
||||
@@ -25,28 +25,34 @@ public struct Chain<Base1: Sequence, Base2: Sequence>
|
||||
}
|
||||
}
|
||||
|
||||
extension Chain: Sequence {
|
||||
extension Chain2: Sequence {
|
||||
/// The iterator for a `Chain` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator1: Base1.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal var iterator2: Base2.Iterator
|
||||
|
||||
internal init(_ concatenation: Chain) {
|
||||
@usableFromInline
|
||||
internal init(_ concatenation: Chain2) {
|
||||
iterator1 = concatenation.base1.makeIterator()
|
||||
iterator2 = concatenation.base2.makeIterator()
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base1.Element? {
|
||||
return iterator1.next() ?? iterator2.next()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Chain: Collection where Base1: Collection, Base2: Collection {
|
||||
extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
/// A position in a `Chain` collection.
|
||||
public struct Index: Comparable {
|
||||
// The internal index representation, which can either be an index of the
|
||||
@@ -54,23 +60,28 @@ extension Chain: Collection where Base1: Collection, Base2: Collection {
|
||||
// is not to be used as a value - iterating over indices should go straight
|
||||
// from the penultimate index of the first collection to the start of the
|
||||
// second.
|
||||
@usableFromInline
|
||||
internal enum Representation : Equatable {
|
||||
case first(Base1.Index)
|
||||
case second(Base2.Index)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal let position: Representation
|
||||
|
||||
/// Creates a new index into the first underlying collection.
|
||||
@usableFromInline
|
||||
internal init(first i: Base1.Index) {
|
||||
position = .first(i)
|
||||
}
|
||||
|
||||
/// Creates a new index into the second underlying collection.
|
||||
@usableFromInline
|
||||
internal init(second i: Base2.Index) {
|
||||
position = .second(i)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
switch (lhs.position, rhs.position) {
|
||||
case (.first, .second):
|
||||
@@ -84,19 +95,27 @@ extension Chain: Collection where Base1: Collection, Base2: Collection {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public var startIndex: Index {
|
||||
// If `base1` is empty, then `base2.startIndex` is either a valid position
|
||||
// of the first element in `base2` or equal to `base2.endIndex`.
|
||||
return base1.isEmpty
|
||||
? Index(second: base2.startIndex)
|
||||
: Index(first: base1.startIndex)
|
||||
|
||||
/// Converts an index of `Base1` to the corresponding `Index` by mapping
|
||||
/// `base1.endIndex` to `base2.startIndex`.
|
||||
@usableFromInline
|
||||
internal func convertIndex(_ i: Base1.Index) -> Index {
|
||||
i == base1.endIndex ? Index(second: base2.startIndex) : Index(first: i)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
// if `base1` is empty, this will return `base2.startIndex` - if `base2` is
|
||||
// also empty, this will correctly equal `base2.endIndex`
|
||||
convertIndex(base1.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
return Index(second: base2.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(i: Index) -> Base1.Element {
|
||||
switch i.position {
|
||||
case let .first(i):
|
||||
@@ -106,19 +125,18 @@ extension Chain: Collection where Base1: Collection, Base2: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
switch i.position {
|
||||
case let .first(i):
|
||||
assert(i != base1.endIndex)
|
||||
let next = base1.index(after: i)
|
||||
return next == base1.endIndex
|
||||
? Index(second: base2.startIndex)
|
||||
: Index(first: next)
|
||||
return convertIndex(base1.index(after: i))
|
||||
case let .second(i):
|
||||
return Index(second: base2.index(after: i))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy n: Int) -> Index {
|
||||
if n == 0 { return i }
|
||||
return n > 0
|
||||
@@ -126,6 +144,7 @@ extension Chain: Collection where Base1: Collection, Base2: Collection {
|
||||
: offsetBackward(i, by: -n, limitedBy: startIndex)!
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
offsetBy n: Int,
|
||||
@@ -137,32 +156,33 @@ extension Chain: Collection where Base1: Collection, Base2: Collection {
|
||||
: offsetBackward(i, by: -n, limitedBy: limit)
|
||||
}
|
||||
|
||||
private func offsetForward(
|
||||
@usableFromInline
|
||||
internal func offsetForward(
|
||||
_ i: Index, by n: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
switch (i.position, limit.position) {
|
||||
case let (.first(i), .first(limit)):
|
||||
let d = base1.distance(from: i, to: base1.endIndex)
|
||||
if n < d {
|
||||
if limit >= i {
|
||||
// `limit` is relevant, so `base2` cannot be reached
|
||||
return base1.index(i, offsetBy: n, limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
} else if let j = base1.index(i, offsetBy: n, limitedBy: base1.endIndex) {
|
||||
// the offset stays within the bounds of `base1`
|
||||
return convertIndex(j)
|
||||
} else {
|
||||
// The limit only has an effect here if it's "above" `i`
|
||||
if limit >= i {
|
||||
return Index(first: limit)
|
||||
} else {
|
||||
return Index(
|
||||
second: base2.index(base2.startIndex, offsetBy: n - d))
|
||||
}
|
||||
// the offset overflows the bounds of `base1` by `n - d`
|
||||
let d = base1.distance(from: i, to: base1.endIndex)
|
||||
return Index(second: base2.index(base2.startIndex, offsetBy: n - d))
|
||||
}
|
||||
|
||||
case let (.first(i), .second(limit)):
|
||||
let d = base1.distance(from: i, to: base1.endIndex)
|
||||
if n < d {
|
||||
return Index(first: base1.index(i, offsetBy: n))
|
||||
if let j = base1.index(i, offsetBy: n, limitedBy: base1.endIndex) {
|
||||
// the offset stays within the bounds of `base1`
|
||||
return convertIndex(j)
|
||||
} else {
|
||||
return base2.index(
|
||||
base2.startIndex, offsetBy: n - d, limitedBy: limit)
|
||||
// the offset overflows the bounds of `base1` by `n - d`
|
||||
let d = base1.distance(from: i, to: base1.endIndex)
|
||||
return base2.index(base2.startIndex, offsetBy: n - d, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
}
|
||||
|
||||
@@ -176,7 +196,8 @@ extension Chain: Collection where Base1: Collection, Base2: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
private func offsetBackward(
|
||||
@usableFromInline
|
||||
internal func offsetBackward(
|
||||
_ i: Index, by n: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
switch (i.position, limit.position) {
|
||||
@@ -189,32 +210,53 @@ extension Chain: Collection where Base1: Collection, Base2: Collection {
|
||||
return Index(first: base1.index(i, offsetBy: -n))
|
||||
|
||||
case let (.second(i), .first(limit)):
|
||||
let d = base2.distance(from: base2.startIndex, to: i)
|
||||
if n <= d {
|
||||
return Index(second: base2.index(i, offsetBy: -n))
|
||||
if let j = base2.index(i, offsetBy: -n, limitedBy: base2.startIndex) {
|
||||
// the offset stays within the bounds of `base2`
|
||||
return Index(second: j)
|
||||
} else {
|
||||
return base1.index(base1.endIndex, offsetBy: -n - d, limitedBy: limit)
|
||||
// the offset overflows the bounds of `base2` by `n - d`
|
||||
let d = base2.distance(from: base2.startIndex, to: i)
|
||||
return base1.index(base1.endIndex, offsetBy: -(n - d), limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
}
|
||||
|
||||
case let (.second(i), .second(limit)):
|
||||
let d = base2.distance(from: base2.startIndex, to: i)
|
||||
if n <= d {
|
||||
if limit <= i {
|
||||
// `limit` is relevant, so `base1` cannot be reached
|
||||
return base2.index(i, offsetBy: -n, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
} else if let j = base2.index(i, offsetBy: -n, limitedBy: base2.startIndex) {
|
||||
// the offset stays within the bounds of `base2`
|
||||
return Index(second: j)
|
||||
} else {
|
||||
return Index(
|
||||
first: base1.index(base1.endIndex, offsetBy: -n - d))
|
||||
// the offset overflows the bounds of `base2` by `n - d`
|
||||
let d = base2.distance(from: base2.startIndex, to: i)
|
||||
return Index(first: base1.index(base1.endIndex, offsetBy: -(n - d)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Add distance(from:to:)
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (start.position, end.position) {
|
||||
case let (.first(i), .first(j)):
|
||||
return base1.distance(from: i, to: j)
|
||||
case let (.second(i), .second(j)):
|
||||
return base2.distance(from: i, to: j)
|
||||
case let (.first(i), .second(j)):
|
||||
return base1.distance(from: i, to: base1.endIndex)
|
||||
+ base2.distance(from: base2.startIndex, to: j)
|
||||
case let (.second(i), .first(j)):
|
||||
return base2.distance(from: i, to: base2.startIndex)
|
||||
+ base1.distance(from: base1.endIndex, to: j)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Chain: BidirectionalCollection
|
||||
extension Chain2: BidirectionalCollection
|
||||
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
assert(i != startIndex, "Can't advance before startIndex")
|
||||
switch i.position {
|
||||
@@ -228,44 +270,56 @@ extension Chain: BidirectionalCollection
|
||||
}
|
||||
}
|
||||
|
||||
extension Chain: RandomAccessCollection
|
||||
extension Chain2: RandomAccessCollection
|
||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||
|
||||
extension Chain: Equatable where Base1: Equatable, Base2: Equatable {}
|
||||
extension Chain: Hashable where Base1: Hashable, Base2: Hashable {}
|
||||
extension Chain2: Equatable where Base1: Equatable, Base2: Equatable {}
|
||||
extension Chain2: Hashable where Base1: Hashable, Base2: Hashable {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// chained(with:)
|
||||
// chain(_:_:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Returns a new sequence that iterates over the two given sequences, one
|
||||
/// followed by the other.
|
||||
///
|
||||
/// You can pass any two sequences or collections that have the same element
|
||||
/// type as this sequence. This example chains a closed range of `Int` with an
|
||||
/// array of `Int`:
|
||||
///
|
||||
/// let small = 1...3
|
||||
/// let big = [100, 200, 300]
|
||||
/// for num in chain(small, big) {
|
||||
/// print(num)
|
||||
/// }
|
||||
/// // 1
|
||||
/// // 2
|
||||
/// // 3
|
||||
/// // 100
|
||||
/// // 200
|
||||
/// // 300
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - s1: The first sequence.
|
||||
/// - s2: The second sequence.
|
||||
/// - Returns: A sequence that iterates first over the elements of `s1`, and
|
||||
/// then over the elements of `s2`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2<S1, S2> {
|
||||
Chain2(base1: s1, base2: s2)
|
||||
}
|
||||
|
||||
// MARK: - Deprecations
|
||||
|
||||
@available(*, deprecated, renamed: "Chain2")
|
||||
public typealias Chain = Chain2
|
||||
|
||||
extension Sequence {
|
||||
/// Returns a new sequence that iterates over this sequence, followed by the
|
||||
/// given sequence.
|
||||
///
|
||||
/// You can pass a sequence or collection of any type that has the same
|
||||
/// element type as this sequence. This example chains a closed range of `Int`
|
||||
/// with an array of `Int`:
|
||||
///
|
||||
/// let small = 1...3
|
||||
/// let big = [100, 200, 300]
|
||||
/// for num in small.chained(with: big) {
|
||||
/// print(num)
|
||||
/// }
|
||||
/// // 1
|
||||
/// // 2
|
||||
/// // 3
|
||||
/// // 100
|
||||
/// // 200
|
||||
/// // 300
|
||||
///
|
||||
/// - Parameter other: The sequence to iterate over after this sequence.
|
||||
/// - Returns: A sequences that follows iteration of this sequence with
|
||||
/// `other`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
public func chained<S: Sequence>(with other: S) -> Chain<Self, S>
|
||||
@available(*, deprecated, message: "Use the chain(_:_:) function, instead.")
|
||||
public func chained<S: Sequence>(with other: S) -> Chain2<Self, S>
|
||||
where Element == S.Element
|
||||
{
|
||||
Chain(base1: self, base2: other)
|
||||
Chain2(base1: self, base2: other)
|
||||
}
|
||||
}
|
||||
@@ -14,13 +14,21 @@ public struct LazyChunked<Base: Collection> {
|
||||
public let base: Base
|
||||
|
||||
/// The projection function.
|
||||
@usableFromInline
|
||||
internal var belongInSameGroup: (Base.Element, Base.Element) -> Bool
|
||||
|
||||
@usableFromInline
|
||||
internal init(base: Base, belongInSameGroup: @escaping (Base.Element, Base.Element) -> Bool) {
|
||||
self.base = base
|
||||
self.belongInSameGroup = belongInSameGroup
|
||||
}
|
||||
}
|
||||
|
||||
extension LazyChunked: LazyCollectionProtocol {
|
||||
/// A position in a chunked collection.
|
||||
public struct Index: Comparable {
|
||||
/// The lower bound of the chunk at this position.
|
||||
@usableFromInline
|
||||
internal var lowerBound: Base.Index
|
||||
|
||||
/// The upper bound of the chunk at this position.
|
||||
@@ -28,8 +36,16 @@ extension LazyChunked: LazyCollectionProtocol {
|
||||
/// `upperBound` is optional so that computing `startIndex` can be an O(1)
|
||||
/// operation. When `upperBound` is `nil`, the actual upper bound is found
|
||||
/// when subscripting or calling `index(after:)`.
|
||||
@usableFromInline
|
||||
internal var upperBound: Base.Index?
|
||||
|
||||
@usableFromInline
|
||||
internal init(lowerBound: Base.Index, upperBound: Base.Index? = nil) {
|
||||
self.lowerBound = lowerBound
|
||||
self.upperBound = upperBound
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||
// Only use the lower bound to test for equality, since sometimes the
|
||||
// `startIndex` will have an upper bound of `nil` and sometimes it won't,
|
||||
@@ -41,6 +57,7 @@ extension LazyChunked: LazyCollectionProtocol {
|
||||
lhs.lowerBound == rhs.lowerBound
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
// Only use the lower bound to test for ordering, as above.
|
||||
lhs.lowerBound < rhs.lowerBound
|
||||
@@ -49,26 +66,31 @@ extension LazyChunked: LazyCollectionProtocol {
|
||||
|
||||
/// Returns the index in the base collection for the first element that
|
||||
/// doesn't match the current chunk.
|
||||
@usableFromInline
|
||||
internal func endOfChunk(from i: Base.Index) -> Base.Index {
|
||||
guard i != base.endIndex else { return base.endIndex }
|
||||
return base[base.index(after: i)...]
|
||||
.firstIndex(where: { !belongInSameGroup($0, base[i]) }) ?? base.endIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(lowerBound: base.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(lowerBound: base.endIndex, upperBound: base.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
let upperBound = i.upperBound ?? endOfChunk(from: i.lowerBound)
|
||||
let end = endOfChunk(from: upperBound)
|
||||
return Index(lowerBound: upperBound, upperBound: end)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Base.SubSequence {
|
||||
let upperBound = position.upperBound
|
||||
?? endOfChunk(from: position.lowerBound)
|
||||
@@ -83,6 +105,7 @@ extension LazyChunked: BidirectionalCollection
|
||||
{
|
||||
/// Returns the index in the base collection for the element that starts
|
||||
/// the chunk ending at the given index.
|
||||
@usableFromInline
|
||||
internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
|
||||
// Get the projected value of the last element in the range ending at `end`.
|
||||
let lastOfPreviousChunk = base[base.index(before: end)]
|
||||
@@ -102,6 +125,7 @@ extension LazyChunked: BidirectionalCollection
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
let start = startOfChunk(endingAt: i.lowerBound)
|
||||
return Index(lowerBound: start, upperBound: i.lowerBound)
|
||||
@@ -119,6 +143,7 @@ extension LazyCollectionProtocol {
|
||||
/// - Complexity: O(1). When iterating over the resulting collection,
|
||||
/// accessing each successive chunk has a complexity of O(*m*), where *m*
|
||||
/// is the length of the chunk.
|
||||
@inlinable
|
||||
public func chunked(
|
||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||
) -> LazyChunked<Elements> {
|
||||
@@ -131,6 +156,7 @@ extension LazyCollectionProtocol {
|
||||
/// - Complexity: O(1). When iterating over the resulting collection,
|
||||
/// accessing each successive chunk has a complexity of O(*m*), where *m*
|
||||
/// is the length of the chunk.
|
||||
@inlinable
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: @escaping (Element) -> Subject
|
||||
) -> LazyChunked<Elements> {
|
||||
@@ -149,6 +175,7 @@ extension Collection {
|
||||
/// the given predicate.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public func chunked(
|
||||
by belongInSameGroup: (Element, Element) -> Bool
|
||||
) -> [SubSequence] {
|
||||
@@ -179,6 +206,7 @@ extension Collection {
|
||||
/// grouping elements that project to the same value.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: (Element) -> Subject
|
||||
) -> [SubSequence] {
|
||||
|
||||
@@ -12,13 +12,17 @@
|
||||
public struct Combinations<Base: Collection> {
|
||||
/// The collection to iterate over for combinations.
|
||||
public let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal var k: Int
|
||||
|
||||
@usableFromInline
|
||||
internal init(_ base: Base, k: Int) {
|
||||
self.base = base
|
||||
self.k = base.count < k ? -1 : k
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
func binomial(n: Int, k: Int) -> Int {
|
||||
switch k {
|
||||
@@ -37,8 +41,13 @@ public struct Combinations<Base: Collection> {
|
||||
|
||||
extension Combinations: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
|
||||
@usableFromInline
|
||||
internal var finished: Bool
|
||||
|
||||
internal init(_ combinations: Combinations) {
|
||||
@@ -67,6 +76,7 @@ extension Combinations: Sequence {
|
||||
/// [2, 3, 4] *
|
||||
/// // Can't advance without needing to go past `base.endIndex`,
|
||||
/// // so the iteration is finished.
|
||||
@usableFromInline
|
||||
internal mutating func advance() {
|
||||
guard !indexes.isEmpty else {
|
||||
// Initial state for combinations of 0 elements is an empty array with
|
||||
@@ -99,6 +109,7 @@ extension Combinations: Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> [Base.Element]? {
|
||||
if finished { return nil }
|
||||
defer { advance() }
|
||||
@@ -111,6 +122,7 @@ extension Combinations: Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension Combinations: Equatable where Base: Equatable {}
|
||||
extension Combinations: Hashable where Base: Hashable {}
|
||||
|
||||
@@ -146,6 +158,7 @@ extension Collection {
|
||||
/// - Parameter k: The number of elements to include in each combination.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func combinations(ofCount k: Int) -> Combinations<Self> {
|
||||
assert(k >= 0, "Can't have combinations with a negative number of elements.")
|
||||
return Combinations(self, k: k)
|
||||
|
||||
@@ -18,9 +18,19 @@ public struct Cycle<Base: Collection> {
|
||||
extension Cycle: Sequence {
|
||||
/// The iterator for a `Cycle` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
let base: Base
|
||||
|
||||
@usableFromInline
|
||||
var current: Base.Index
|
||||
|
||||
@usableFromInline
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
self.current = base.startIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element? {
|
||||
guard !base.isEmpty else { return nil }
|
||||
|
||||
@@ -34,10 +44,12 @@ extension Cycle: Sequence {
|
||||
}
|
||||
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(base: base, current: base.startIndex)
|
||||
Iterator(base: base)
|
||||
}
|
||||
}
|
||||
|
||||
extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// cycled()
|
||||
//===----------------------------------------------------------------------===//
|
||||
@@ -71,13 +83,7 @@ extension Collection {
|
||||
public func cycled() -> Cycle<Self> {
|
||||
Cycle(base: self)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// repeated(count:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection {
|
||||
|
||||
/// Returns a sequence that repeats the elements of this collection the
|
||||
/// specified number of times.
|
||||
///
|
||||
|
||||
@@ -17,48 +17,66 @@ public struct Indexed<Base: Collection> {
|
||||
|
||||
/// The base collection.
|
||||
public let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
}
|
||||
|
||||
extension Indexed: Collection {
|
||||
@inlinable
|
||||
public var startIndex: Base.Index {
|
||||
base.startIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Base.Index {
|
||||
base.endIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Base.Index) -> Element {
|
||||
(index: position, element: base[position])
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Base.Index) -> Base.Index {
|
||||
base.index(after: i)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index {
|
||||
base.index(i, offsetBy: distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index) -> Base.Index? {
|
||||
base.index(i, offsetBy: distance, limitedBy: limit)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Base.Index, to end: Base.Index) -> Int {
|
||||
base.distance(from: start, to: end)
|
||||
}
|
||||
}
|
||||
|
||||
extension Indexed: BidirectionalCollection where Base: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before i: Base.Index) -> Base.Index {
|
||||
base.index(before: i)
|
||||
}
|
||||
}
|
||||
|
||||
extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
extension Indexed: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension Indexed: Equatable where Base: Equatable {}
|
||||
extension Indexed: Hashable where Base: Hashable {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// indexed()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection {
|
||||
/// Returns a collection of pairs *(i, x)*, where *i* represents an index of
|
||||
/// the collection, and *x* represents an element.
|
||||
@@ -68,13 +86,14 @@ extension Collection {
|
||||
///
|
||||
/// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
|
||||
/// var shorterIndices: [Set<String>.Index] = []
|
||||
/// for (i, name) in zip(names.indices, names) {
|
||||
/// for (i, name) in names.indexed() {
|
||||
/// if name.count <= 5 {
|
||||
/// shorterIndices.append(i)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// Returns: A collection of paired indices and elements of this collection.
|
||||
@inlinable
|
||||
public func indexed() -> Indexed<Self> {
|
||||
Indexed(base: self)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ extension MutableCollection {
|
||||
/// - Complexity: O(*n* log *n*), where *n* is the number of elements.
|
||||
/// - Precondition:
|
||||
/// `n == distance(from: range.lowerBound, to: range.upperBound)`
|
||||
@usableFromInline
|
||||
internal mutating func stablePartition(
|
||||
count n: Int,
|
||||
subrange: Range<Index>,
|
||||
@@ -42,7 +43,7 @@ extension MutableCollection {
|
||||
count: n - h,
|
||||
subrange: i..<subrange.upperBound,
|
||||
by: belongsInSecondPartition)
|
||||
return rotate(subrange: j..<k, at: i)
|
||||
return rotate(subrange: j..<k, toStartAt: i)
|
||||
}
|
||||
|
||||
/// Moves all elements satisfying the given predicate into a suffix of the
|
||||
@@ -56,12 +57,13 @@ extension MutableCollection {
|
||||
/// all elements not satisfying it.
|
||||
///
|
||||
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public mutating func stablePartition(
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws-> Bool
|
||||
) rethrows -> Index {
|
||||
try stablePartition(
|
||||
count: count,
|
||||
count: distance(from: subrange.lowerBound, to: subrange.upperBound),
|
||||
subrange: subrange,
|
||||
by: belongsInSecondPartition)
|
||||
}
|
||||
@@ -75,6 +77,7 @@ extension MutableCollection {
|
||||
/// all elements not satisfying it.
|
||||
///
|
||||
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public mutating func stablePartition(
|
||||
by belongsInSecondPartition: (Element) throws-> Bool
|
||||
) rethrows -> Index {
|
||||
@@ -93,6 +96,7 @@ extension MutableCollection {
|
||||
/// collection, returning the start position of the resulting suffix.
|
||||
///
|
||||
/// - Complexity: O(*n*) where n is the length of the collection.
|
||||
@inlinable
|
||||
public mutating func partition(
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
@@ -120,6 +124,7 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
/// collection, returning the start position of the resulting suffix.
|
||||
///
|
||||
/// - Complexity: O(*n*) where n is the length of the collection.
|
||||
@inlinable
|
||||
public mutating func partition(
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
@@ -178,6 +183,7 @@ extension Collection {
|
||||
///
|
||||
/// - Complexity: O(log *n*), where *n* is the length of this collection if
|
||||
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
|
||||
@inlinable
|
||||
public func partitioningIndex(
|
||||
where belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
|
||||
@@ -33,16 +33,22 @@ public struct Permutations<Base: Collection> {
|
||||
|
||||
extension Permutations: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var base: Base
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
@usableFromInline
|
||||
internal var hasMorePermutations: Bool
|
||||
@usableFromInline
|
||||
internal var countToChoose: Int = 0
|
||||
|
||||
/// `true` if we're generating permutations of the full collection.
|
||||
@usableFromInline
|
||||
internal var permutesFullCollection: Bool {
|
||||
countToChoose == indexes.count
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal init(_ base: Base) {
|
||||
self.base = base
|
||||
self.indexes = Array(base.indices)
|
||||
@@ -50,6 +56,7 @@ extension Permutations: Sequence {
|
||||
self.hasMorePermutations = true
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal init(_ base: Base, count: Int) {
|
||||
self.base = base
|
||||
self.countToChoose = count
|
||||
@@ -72,6 +79,7 @@ extension Permutations: Sequence {
|
||||
/// is in ascending order.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@usableFromInline
|
||||
internal mutating func nextState() -> Bool {
|
||||
let edge = countToChoose - 1
|
||||
|
||||
@@ -101,6 +109,7 @@ extension Permutations: Sequence {
|
||||
return true
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> [Base.Element]? {
|
||||
if !hasMorePermutations { return nil }
|
||||
|
||||
@@ -118,6 +127,7 @@ extension Permutations: Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal var permutesFullCollection: Bool {
|
||||
baseCount == countToChoose
|
||||
}
|
||||
@@ -129,6 +139,8 @@ extension Permutations: Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
extension Permutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// nextPermutation(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
@@ -148,6 +160,7 @@ extension MutableCollection
|
||||
/// is in ascending order according to `areInIncreasingOrder`.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@usableFromInline
|
||||
internal mutating func nextPermutation() -> Bool {
|
||||
// ensure we have > 1 element in the collection
|
||||
if isEmpty { return false }
|
||||
@@ -177,7 +190,7 @@ extension MutableCollection
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// permutations(count:)
|
||||
// permutations(ofCount:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection {
|
||||
|
||||
@@ -25,18 +25,24 @@ public struct Product2<Base1: Sequence, Base2: Collection> {
|
||||
extension Product2: Sequence {
|
||||
/// The iterator for a `Product2` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
var i1: Base1.Iterator
|
||||
var i2: Base2.Iterator
|
||||
var element1: Base1.Element?
|
||||
let base2: Base2
|
||||
@usableFromInline
|
||||
internal var i1: Base1.Iterator
|
||||
@usableFromInline
|
||||
internal var i2: Base2.Iterator
|
||||
@usableFromInline
|
||||
internal var element1: Base1.Element?
|
||||
@usableFromInline
|
||||
internal let base2: Base2
|
||||
|
||||
init(_ c: Product2) {
|
||||
@usableFromInline
|
||||
internal init(_ c: Product2) {
|
||||
self.base2 = c.base2
|
||||
self.i1 = c.base1.makeIterator()
|
||||
self.i2 = c.base2.makeIterator()
|
||||
self.element1 = nil
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> (Base1.Element, Base2.Element)? {
|
||||
// This is the initial state, where i1.next() has never
|
||||
// been called, or the final state, where i1.next() has
|
||||
@@ -78,44 +84,53 @@ extension Product2: Sequence {
|
||||
extension Product2: Collection where Base1: Collection {
|
||||
/// The index type for a `Product2` collection.
|
||||
public struct Index: Comparable {
|
||||
var i1: Base1.Index
|
||||
var i2: Base2.Index
|
||||
@usableFromInline
|
||||
internal var i1: Base1.Index
|
||||
@usableFromInline
|
||||
internal var i2: Base2.Index
|
||||
|
||||
@usableFromInline
|
||||
internal init(i1: Base1.Index, i2: Base2.Index) {
|
||||
self.i1 = i1
|
||||
self.i2 = i2
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
(lhs.i1, lhs.i2) < (rhs.i1, rhs.i2)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
base1.count * base2.count
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
base1.isEmpty || base2.isEmpty
|
||||
? endIndex
|
||||
: Index(i1: base1.startIndex, i2: base2.startIndex)
|
||||
Index(
|
||||
i1: base2.isEmpty ? base1.endIndex : base1.startIndex,
|
||||
i2: base2.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(i1: base1.endIndex, i2: base2.endIndex)
|
||||
// `base2.startIndex` simplifies index calculations.
|
||||
Index(i1: base1.endIndex, i2: base2.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i.i1 != base1.endIndex && i.i2 != base2.endIndex,
|
||||
"Can't advance past endIndex")
|
||||
precondition(i.i1 != base1.endIndex, "Can't advance past endIndex")
|
||||
let newIndex2 = base2.index(after: i.i2)
|
||||
if newIndex2 < base2.endIndex {
|
||||
return Index(i1: i.i1, i2: newIndex2)
|
||||
}
|
||||
|
||||
let newIndex1 = base1.index(after: i.i1)
|
||||
return newIndex1 == base1.endIndex
|
||||
? endIndex
|
||||
: Index(i1: newIndex1, i2: base2.startIndex)
|
||||
return newIndex2 == base2.endIndex
|
||||
? Index(i1: base1.index(after: i.i1), i2: base2.startIndex)
|
||||
: Index(i1: i.i1, i2: newIndex2)
|
||||
}
|
||||
|
||||
// TODO: Implement index(_:offsetBy:) and index(_:offsetBy:limitedBy:)
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
if start > end {
|
||||
return -distance(from: end, to: start)
|
||||
@@ -125,9 +140,10 @@ extension Product2: Collection where Base1: Collection {
|
||||
}
|
||||
|
||||
return base2[start.i2...].count + base2[..<end.i2].count
|
||||
+ base2.count * (base1.distance(from: start.i1, to: end.i1))
|
||||
+ base2.count * (base1.distance(from: start.i1, to: end.i1) - 1)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> (Base1.Element, Base2.Element) {
|
||||
return (base1[position.i1], base2[position.i2])
|
||||
}
|
||||
@@ -136,16 +152,17 @@ extension Product2: Collection where Base1: Collection {
|
||||
extension Product2: BidirectionalCollection
|
||||
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(i != startIndex,
|
||||
"Can't move before startIndex")
|
||||
if i.i2 == base2.startIndex {
|
||||
return Index(
|
||||
i1: base1.index(before: i.i1),
|
||||
i2: base2.index(before: base2.endIndex))
|
||||
} else {
|
||||
return Index(i1: i.i1, i2: base2.index(before: i.i2))
|
||||
}
|
||||
|
||||
return Index(
|
||||
i1: base1.index(before: i.i1),
|
||||
i2: base2.index(before: base2.endIndex))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,14 +9,9 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// For log(_:) and exp(_:)
|
||||
#if canImport(Glibc)
|
||||
// For log(_:) and root(_:_:)
|
||||
@_implementationOnly
|
||||
import Glibc
|
||||
#elseif canImport(Darwin)
|
||||
@_implementationOnly
|
||||
import Darwin
|
||||
#endif
|
||||
import RealModule
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// randomStableSample(count:)
|
||||
@@ -33,6 +28,7 @@ extension Collection {
|
||||
/// collection's count, then this method returns the full collection.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func randomStableSample<G: RandomNumberGenerator>(
|
||||
count k: Int, using rng: inout G
|
||||
) -> [Element] {
|
||||
@@ -72,6 +68,7 @@ extension Collection {
|
||||
/// collection's count, then this method returns the full collection.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func randomStableSample(count k: Int) -> [Element] {
|
||||
var g = SystemRandomNumberGenerator()
|
||||
return randomStableSample(count: k, using: &g)
|
||||
@@ -86,16 +83,18 @@ extension Collection {
|
||||
// Algorithms of Time Complexity O(n(1 + log(N/n)))":
|
||||
// https://dl.acm.org/doi/pdf/10.1145/198429.198435
|
||||
|
||||
fileprivate func nextW<G: RandomNumberGenerator>(
|
||||
k: Double, using rng: inout G
|
||||
@usableFromInline
|
||||
internal func nextW<G: RandomNumberGenerator>(
|
||||
k: Int, using rng: inout G
|
||||
) -> Double {
|
||||
exp(log(Double.random(in: 0..<1, using: &rng)) / k)
|
||||
Double.root(.random(in: 0..<1, using: &rng), k)
|
||||
}
|
||||
|
||||
fileprivate func nextOffset<G: RandomNumberGenerator>(
|
||||
@usableFromInline
|
||||
internal func nextOffset<G: RandomNumberGenerator>(
|
||||
w: Double, using rng: inout G
|
||||
) -> Int {
|
||||
Int(log(Double.random(in: 0..<1, using: &rng)) / log(1 - w))
|
||||
Int(Double.log(.random(in: 0..<1, using: &rng)) / .log(1 - w))
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
@@ -111,6 +110,7 @@ extension Collection {
|
||||
/// - Complexity: O(*k*), where *k* is the number of elements to select, if
|
||||
/// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),
|
||||
/// where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func randomSample<G: RandomNumberGenerator>(
|
||||
count k: Int, using rng: inout G
|
||||
) -> [Element] {
|
||||
@@ -126,11 +126,10 @@ extension Collection {
|
||||
result.append(self[i])
|
||||
formIndex(after: &i)
|
||||
}
|
||||
|
||||
let dk = Double(k)
|
||||
|
||||
while i < endIndex {
|
||||
// Calculate the next value of w.
|
||||
w *= nextW(k: dk, using: &rng)
|
||||
w *= nextW(k: k, using: &rng)
|
||||
|
||||
// Find index of the next element to swap into the reservoir.
|
||||
let offset = nextOffset(w: w, using: &rng)
|
||||
@@ -163,6 +162,7 @@ extension Collection {
|
||||
/// - Complexity: O(*k*), where *k* is the number of elements to select, if
|
||||
/// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),
|
||||
/// where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func randomSample(count k: Int) -> [Element] {
|
||||
var g = SystemRandomNumberGenerator()
|
||||
return randomSample(count: k, using: &g)
|
||||
@@ -180,6 +180,7 @@ extension Sequence {
|
||||
/// method returns the full sequence.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func randomSample<G: RandomNumberGenerator>(
|
||||
count k: Int, using rng: inout G
|
||||
) -> [Element] {
|
||||
@@ -195,10 +196,9 @@ extension Sequence {
|
||||
result.append(el)
|
||||
}
|
||||
|
||||
let dk = Double(k)
|
||||
while true {
|
||||
// Calculate the next value of w.
|
||||
w *= nextW(k: dk, using: &rng)
|
||||
w *= nextW(k: k, using: &rng)
|
||||
|
||||
// Find the offset of the next element to swap into the reservoir.
|
||||
var offset = nextOffset(w: w, using: &rng) + 1
|
||||
@@ -231,6 +231,7 @@ extension Sequence {
|
||||
/// method returns the full sequence.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func randomSample(count k: Int) -> [Element] {
|
||||
var g = SystemRandomNumberGenerator()
|
||||
return randomSample(count: k, using: &g)
|
||||
|
||||
@@ -29,6 +29,7 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
///
|
||||
/// - Postcondition: For returned indices `(f, l)`:
|
||||
/// `f == limit || l == limit`
|
||||
@usableFromInline
|
||||
@discardableResult
|
||||
internal mutating func _reverse(
|
||||
subrange: Range<Index>, until limit: Index
|
||||
@@ -43,6 +44,19 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
return (f, l)
|
||||
}
|
||||
|
||||
/// Reverses the elements within the given subrange.
|
||||
///
|
||||
/// This example reverses the numbers within the subrange at the start of the
|
||||
/// `numbers` array:
|
||||
///
|
||||
/// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
/// numbers.reverse(subrange: 0..<4)
|
||||
/// // numbers == [40, 30, 20, 10, 50, 60, 70, 80]
|
||||
///
|
||||
/// - Parameter subrange: The subrange of this collection to reverse.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of `subrange`.
|
||||
@inlinable
|
||||
public mutating func reverse(subrange: Range<Index>) {
|
||||
if subrange.isEmpty { return }
|
||||
var lo = subrange.lowerBound
|
||||
@@ -57,7 +71,7 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// rotate(at:) / rotate(subrange:at:)
|
||||
// rotate(toStartAt:) / rotate(subrange:toStartAt:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension MutableCollection {
|
||||
@@ -81,6 +95,7 @@ extension MutableCollection {
|
||||
/// - distance(from: lhs.lowerBound, to: p) == distance(from:
|
||||
/// rhs.lowerBound, to: q)
|
||||
/// - p == lhs.upperBound || q == rhs.upperBound
|
||||
@usableFromInline
|
||||
internal mutating func _swapNonemptySubrangePrefixes(
|
||||
_ lhs: Range<Index>, _ rhs: Range<Index>
|
||||
) -> (Index, Index) {
|
||||
@@ -98,10 +113,32 @@ extension MutableCollection {
|
||||
return (p, q)
|
||||
}
|
||||
|
||||
/// Rotates the elements within the given subrange so that the element
|
||||
/// at the specified index becomes the start of the subrange.
|
||||
///
|
||||
/// Rotating a collection is equivalent to breaking the collection into two
|
||||
/// sections at the index `newStart`, and then swapping those two sections.
|
||||
/// In this example, the `numbers` array is rotated so that the element at
|
||||
/// index `3` (`40`) is first:
|
||||
///
|
||||
/// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
/// let oldStart = numbers.rotate(subrange: 0..<4, toStartAt: 2)
|
||||
/// // numbers == [30, 40, 10, 20, 50, 60, 70, 80]
|
||||
/// // numbers[oldStart] == 10
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - subrange: The subrange of this collection to rotate.
|
||||
/// - newStart: The index of the element that should be at the start of
|
||||
/// `subrange` after rotating.
|
||||
/// - Returns: The new index of the element that was at the start of
|
||||
/// `subrange` pre-rotation.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of `subrange`.
|
||||
@inlinable
|
||||
@discardableResult
|
||||
public mutating func rotate(
|
||||
subrange: Range<Index>,
|
||||
at newStart: Index
|
||||
toStartAt newStart: Index
|
||||
) -> Index {
|
||||
var m = newStart, s = subrange.lowerBound
|
||||
let e = subrange.upperBound
|
||||
@@ -159,17 +196,58 @@ extension MutableCollection {
|
||||
return ret
|
||||
}
|
||||
|
||||
/// Rotates the elements of this collection so that the element
|
||||
/// at the specified index becomes the start of the collection.
|
||||
///
|
||||
/// Rotating a collection is equivalent to breaking the collection into two
|
||||
/// sections at the index `newStart`, and then swapping those two sections.
|
||||
/// In this example, the `numbers` array is rotated so that the element at
|
||||
/// index `3` (`40`) is first:
|
||||
///
|
||||
/// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
/// let oldStart = numbers.rotate(toStartAt: 3)
|
||||
/// // numbers == [40, 50, 60, 70, 80, 10, 20, 30]
|
||||
/// // numbers[oldStart] == 10
|
||||
///
|
||||
/// - Parameter newStart: The index of the element that should be first after
|
||||
/// rotating.
|
||||
/// - Returns: The new index of the element that was first pre-rotation.
|
||||
///
|
||||
/// - Complexity: O(*n*)
|
||||
@inlinable
|
||||
@discardableResult
|
||||
public mutating func rotate(at newStart: Index) -> Index {
|
||||
rotate(subrange: startIndex..<endIndex, at: newStart)
|
||||
public mutating func rotate(toStartAt newStart: Index) -> Index {
|
||||
rotate(subrange: startIndex..<endIndex, toStartAt: newStart)
|
||||
}
|
||||
}
|
||||
|
||||
extension MutableCollection where Self: BidirectionalCollection {
|
||||
/// Rotates the elements within the given subrange so that the element
|
||||
/// at the specified index becomes the start of the subrange.
|
||||
///
|
||||
/// Rotating a collection is equivalent to breaking the collection into two
|
||||
/// sections at the index `newStart`, and then swapping those two sections.
|
||||
/// In this example, the `numbers` array is rotated so that the element at
|
||||
/// index `3` (`40`) is first:
|
||||
///
|
||||
/// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
/// let oldStart = numbers.rotate(subrange: 0..<4, toStartAt: 2)
|
||||
/// // numbers == [30, 40, 10, 20, 50, 60, 70, 80]
|
||||
/// // numbers[oldStart] == 10
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - subrange: The subrange of this collection to rotate.
|
||||
/// - newStart: The index of the element that should be at the start of
|
||||
/// `subrange` after rotating.
|
||||
/// - Returns: The new index of the element that was at the start of
|
||||
/// `subrange` pre-rotation.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of `subrange`.
|
||||
@inlinable
|
||||
@discardableResult
|
||||
public mutating func rotate(
|
||||
subrange: Range<Index>,
|
||||
at newStart: Index
|
||||
toStartAt newStart: Index
|
||||
) -> Index {
|
||||
reverse(subrange: subrange.lowerBound..<newStart)
|
||||
reverse(subrange: newStart..<subrange.upperBound)
|
||||
@@ -179,7 +257,7 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
}
|
||||
|
||||
/// Rotates the elements of this collection so that the element
|
||||
/// at the specified index moves to the front of the collection.
|
||||
/// at the specified index becomes the start of the collection.
|
||||
///
|
||||
/// Rotating a collection is equivalent to breaking the collection into two
|
||||
/// sections at the index `newStart`, and then swapping those two sections.
|
||||
@@ -187,7 +265,7 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
/// index `3` (`40`) is first:
|
||||
///
|
||||
/// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
/// let oldStart = numbers.rotate(at: 3)
|
||||
/// let oldStart = numbers.rotate(toStartAt: 3)
|
||||
/// // numbers == [40, 50, 60, 70, 80, 10, 20, 30]
|
||||
/// // numbers[oldStart] == 10
|
||||
///
|
||||
@@ -196,8 +274,28 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
/// - Returns: The new index of the element that was first pre-rotation.
|
||||
///
|
||||
/// - Complexity: O(*n*)
|
||||
@inlinable
|
||||
@discardableResult
|
||||
public mutating func rotate(at newStart: Index) -> Index {
|
||||
rotate(subrange: startIndex..<endIndex, at: newStart)
|
||||
public mutating func rotate(toStartAt newStart: Index) -> Index {
|
||||
rotate(subrange: startIndex..<endIndex, toStartAt: newStart)
|
||||
}
|
||||
}
|
||||
|
||||
// Deprecations
|
||||
|
||||
extension MutableCollection {
|
||||
@available(*, deprecated, renamed: "rotate(subrange:toStartAt:)")
|
||||
@discardableResult
|
||||
public mutating func rotate(
|
||||
subrange: Range<Index>,
|
||||
at newStart: Index) -> Index
|
||||
{
|
||||
rotate(subrange: subrange, toStartAt: newStart)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "rotate(toStartAt:)")
|
||||
@discardableResult
|
||||
public mutating func rotate(at newStart: Index) -> Index {
|
||||
rotate(toStartAt: newStart)
|
||||
}
|
||||
}
|
||||
@@ -16,15 +16,9 @@
|
||||
extension Sequence where Element: Hashable {
|
||||
/// Returns an array with only the unique elements of this sequence, in the
|
||||
/// order of the first occurence of each unique element.
|
||||
@inlinable
|
||||
public func uniqued() -> [Element] {
|
||||
var seen: Set<Element> = []
|
||||
var result: [Element] = []
|
||||
for element in self {
|
||||
if seen.insert(element).inserted {
|
||||
result.append(element)
|
||||
}
|
||||
}
|
||||
return result
|
||||
uniqued(on: { $0 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +26,7 @@ extension Sequence {
|
||||
/// Returns an array with the unique elements of this sequence (as determined
|
||||
/// by the given projection), in the order of the first occurence of each
|
||||
/// unique element.
|
||||
@inlinable
|
||||
public func uniqued<Subject: Hashable>(
|
||||
on projection: (Element) throws -> Subject
|
||||
) rethrows -> [Element] {
|
||||
|
||||
@@ -10,30 +10,130 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
@testable import Algorithms
|
||||
|
||||
final class ChainTests: XCTestCase {
|
||||
// intentionally does not depend on `Chain.index(_:offsetBy:)` in order to
|
||||
// avoid making assumptions about the code being tested
|
||||
func index<A, B>(atOffset offset: Int, in chain: Chain2<A, B>) -> Chain2<A, B>.Index {
|
||||
offset < chain.base1.count
|
||||
? .init(first: chain.base1.index(chain.base1.startIndex, offsetBy: offset))
|
||||
: .init(second: chain.base2.index(chain.base2.startIndex, offsetBy: offset - chain.base1.count))
|
||||
}
|
||||
|
||||
func testChainSequences() {
|
||||
let run = (1...).prefix(10).chained(with: 20...)
|
||||
let run = chain((1...).prefix(10), 20...)
|
||||
XCTAssertEqualSequences(run.prefix(20), Array(1...10) + (20..<30))
|
||||
}
|
||||
|
||||
func testChainForwardCollection() {
|
||||
let s1 = Set(0...10)
|
||||
let s2 = Set(20...30)
|
||||
let c = s1.chained(with: s2)
|
||||
let c = chain(s1, s2)
|
||||
XCTAssertEqualSequences(c, Array(s1) + Array(s2))
|
||||
}
|
||||
|
||||
func testChainBidirectionalCollection() {
|
||||
let s1 = "ABCDEFGHIJ"
|
||||
let s2 = "klmnopqrstuv"
|
||||
let c = s1.chained(with: s2)
|
||||
let c = chain(s1, s2)
|
||||
|
||||
XCTAssertEqualSequences(c, "ABCDEFGHIJklmnopqrstuv")
|
||||
XCTAssertEqualSequences(c.reversed(), "ABCDEFGHIJklmnopqrstuv".reversed())
|
||||
XCTAssertEqualSequences(s1.reversed().chained(with: s2), "JIHGFEDCBAklmnopqrstuv")
|
||||
XCTAssertEqualSequences(chain(s1.reversed(), s2), "JIHGFEDCBAklmnopqrstuv")
|
||||
}
|
||||
|
||||
// TODO: Add tests that check distance and index(offsetBy:)
|
||||
func testChainIndexOffsetBy() {
|
||||
let s1 = "abcde"
|
||||
let s2 = "VWXYZ"
|
||||
let c = chain(s1, s2)
|
||||
|
||||
for (startOffset, endOffset) in product(0...c.count, 0...c.count) {
|
||||
let start = index(atOffset: startOffset, in: c)
|
||||
let end = index(atOffset: endOffset, in: c)
|
||||
let distance = endOffset - startOffset
|
||||
XCTAssertEqual(c.index(start, offsetBy: distance), end)
|
||||
}
|
||||
}
|
||||
|
||||
func testChainIndexOffsetByLimitedBy() {
|
||||
let s1 = "abcd"
|
||||
let s2 = "XYZ"
|
||||
let c = chain(s1, s2)
|
||||
|
||||
for (startOffset, limitOffset) in product(0...c.count, 0...c.count) {
|
||||
let start = index(atOffset: startOffset, in: c)
|
||||
let limit = index(atOffset: limitOffset, in: c)
|
||||
|
||||
// verifies that the target index corresponding to each offset in `range`
|
||||
// can or cannot be reached from `start` using
|
||||
// `c.index(start, offsetBy: _, limitedBy: limit)`, depending on the
|
||||
// value of `beyondLimit`
|
||||
func checkTargetRange(_ range: ClosedRange<Int>, beyondLimit: Bool) {
|
||||
for targetOffset in range {
|
||||
let distance = targetOffset - startOffset
|
||||
|
||||
XCTAssertEqual(
|
||||
c.index(start, offsetBy: distance, limitedBy: limit),
|
||||
beyondLimit ? nil : index(atOffset: targetOffset, in: c))
|
||||
}
|
||||
}
|
||||
|
||||
// forward
|
||||
if limit >= start {
|
||||
// the limit has an effect
|
||||
checkTargetRange(startOffset...limitOffset, beyondLimit: false)
|
||||
checkTargetRange((limitOffset + 1)...(c.count + 1), beyondLimit: true)
|
||||
} else {
|
||||
// the limit has no effect
|
||||
checkTargetRange(startOffset...c.count, beyondLimit: false)
|
||||
}
|
||||
|
||||
// backward
|
||||
if limit <= start {
|
||||
// the limit has an effect
|
||||
checkTargetRange(limitOffset...startOffset, beyondLimit: false)
|
||||
checkTargetRange(-1...(limitOffset - 1), beyondLimit: true)
|
||||
} else {
|
||||
// the limit has no effect
|
||||
checkTargetRange(0...startOffset, beyondLimit: false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testChainIndexOffsetAcrossBoundary() {
|
||||
let c = chain("abc", "XYZ")
|
||||
|
||||
do {
|
||||
let i = c.index(c.startIndex, offsetBy: 3, limitedBy: c.startIndex)
|
||||
XCTAssertNil(i)
|
||||
}
|
||||
|
||||
do {
|
||||
let i = c.index(c.startIndex, offsetBy: 4)
|
||||
let j = c.index(i, offsetBy: -2)
|
||||
XCTAssertEqual(c[j], "c")
|
||||
}
|
||||
|
||||
do {
|
||||
let i = c.index(c.startIndex, offsetBy: 3)
|
||||
let j = c.index(i, offsetBy: -1, limitedBy: i)
|
||||
XCTAssertNil(j)
|
||||
}
|
||||
}
|
||||
|
||||
func testChainDistanceFromTo() {
|
||||
let s1 = "abcde"
|
||||
let s2 = "VWXYZ"
|
||||
let c = chain(s1, s2)
|
||||
|
||||
XCTAssertEqual(c.count, s1.count + s2.count)
|
||||
|
||||
for (startOffset, endOffset) in product(0...c.count, 0...c.count) {
|
||||
let start = index(atOffset: startOffset, in: c)
|
||||
let end = index(atOffset: endOffset, in: c)
|
||||
let distance = endOffset - startOffset
|
||||
XCTAssertEqual(c.distance(from: start, to: end), distance)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,4 +71,9 @@ final class ChunkedTests: XCTestCase {
|
||||
let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first })
|
||||
validateFruitChunks(lazyChunks)
|
||||
}
|
||||
|
||||
func testChunkedLazy() {
|
||||
XCTAssertLazy(fruits.lazy.chunked(by: { $0.first == $1.first }))
|
||||
XCTAssertLazy(fruits.lazy.chunked(on: { $0.first }))
|
||||
}
|
||||
}
|
||||
@@ -38,4 +38,8 @@ final class CombinationsTests: XCTestCase {
|
||||
XCTAssertEqualSequences([], "".combinations(ofCount: 5))
|
||||
XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5))
|
||||
}
|
||||
|
||||
func testCombinationsLazy() {
|
||||
XCTAssertLazy("ABC".lazy.combinations(ofCount: 1))
|
||||
}
|
||||
}
|
||||
@@ -39,4 +39,8 @@ final class CycleTests: XCTestCase {
|
||||
let empty2 = Array("Hello".cycled(times: 0))
|
||||
XCTAssert(empty2.isEmpty)
|
||||
}
|
||||
|
||||
func testCycleLazy() {
|
||||
XCTAssertLazy((1...4).lazy.cycled())
|
||||
}
|
||||
}
|
||||
@@ -27,4 +27,8 @@ final class IndexedTests: XCTestCase {
|
||||
let indexOfI = si.last(where: { $0.element == "I" })!.index
|
||||
XCTAssertEqual("I", s[indexOfI])
|
||||
}
|
||||
|
||||
func testIndexedLazy() {
|
||||
XCTAssertLazy("ABCD".lazy.indexed())
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,21 @@ final class PartitionTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testStablePartitionWithSubrange() {
|
||||
for length in 10...20 {
|
||||
let a = Array(0..<length)
|
||||
for j in 0..<length {
|
||||
var b = a
|
||||
let partitionRange = 0..<j
|
||||
let condition = { $0 < j - 1 }
|
||||
let p = b.stablePartition(subrange: partitionRange, by: condition)
|
||||
XCTAssertEqual(p, partitionRange.count > 0 ? 1 : 0)
|
||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
||||
XCTAssertEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testPartitioningIndex() {
|
||||
for i in 0..<7 {
|
||||
for j in i..<11 {
|
||||
|
||||
@@ -69,4 +69,8 @@ final class PermutationsTests: XCTestCase {
|
||||
while numbers.nextPermutation() {}
|
||||
XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], numbers)
|
||||
}
|
||||
|
||||
func testPermutationsLazy() {
|
||||
XCTAssertLazy("ABCD".lazy.permutations(ofCount: 2))
|
||||
}
|
||||
}
|
||||
@@ -22,4 +22,19 @@ final class ProductTests: XCTestCase {
|
||||
XCTAssertEqualSequences(product(1...10, ""), [], by: ==)
|
||||
XCTAssertEqualSequences(product("", 1...10), [], by: ==)
|
||||
}
|
||||
|
||||
func testProductReversed() {
|
||||
XCTAssertEqualSequences(
|
||||
[(2, "B" as Character), (2, "A"), (1, "B"), (1, "A")],
|
||||
product(1...2, "AB").reversed(),
|
||||
by: ==)
|
||||
|
||||
XCTAssertEqualSequences(product(1...10, "").reversed(), [], by: ==)
|
||||
XCTAssertEqualSequences(product("", 1...10).reversed(), [], by: ==)
|
||||
}
|
||||
|
||||
func testProductDistanceFromTo() {
|
||||
let p = product([1, 2], "abc")
|
||||
XCTAssertEqual(p.distance(from: p.startIndex, to: p.endIndex), 6)
|
||||
}
|
||||
}
|
||||
@@ -18,9 +18,9 @@ final class RotateTests: XCTestCase {
|
||||
let a = Array(0..<length)
|
||||
var b = a
|
||||
for j in 0..<length {
|
||||
let i = b.rotate(at: j)
|
||||
let i = b.rotate(toStartAt: j)
|
||||
XCTAssertEqualSequences(a[j...] + a[..<j], b)
|
||||
b.rotate(at: i)
|
||||
b.rotate(toStartAt: i)
|
||||
XCTAssertEqual(a, b)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,3 +65,4 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
|
||||
try XCTAssert(expression1().elementsEqual(expression2(), by: areEquivalent), message(), file: file, line: line)
|
||||
}
|
||||
|
||||
func XCTAssertLazy<S: LazySequenceProtocol>(_: S) {}
|
||||
Reference in new issue
Block a user