Compare commits

..
15 Commits
Author SHA1 Message Date
Kyle Macomber f0df883f88 Remove the inout on reductions(into:_:) to be consistent with the stdlib reduce(into:_) 2021-03-26 17:09:17 -07:00
Daniel Tull 5cde0b1b67 Inline all the reductions things! (#114) 2021-03-25 16:54:54 +01:00
Matt Zanchelli 220649e999 Correct typos (#113)
largets -> largest
2021-03-25 00:05:49 -07:00
Daniel Tull b171b81577 Add reductions(_:_:) (#46)
* Add scan function

* Add initial conditional conformances to Collection and BidirectionalCollection

* Rename scan to reductions

* Add information to the readme about the reductions name

* Add eager API

* Remove Reductions' conformance to BidirectionalCollection

* Implement Reductions subscript such that it occurs in constant time

* Add a variant which includes the given initial result

* Add a variant which takes no initial result value

* Add excluding label to show the initial result is not included

* Test lazy implementations

* Remove reductions(including:_:)

* Add conformance to LazySequenceProtocol and LazyCollectionProtocol when the base sequence conforms

* Fix implementation of lazy reductions

* Add test cases for sequences with one element

* Tidy up tests

* Improve ergonomics of no initial value eager reductions call and provide it as an extension on Sequence

* Add lazy InclusiveReductions sequence

* Rename Reductions to ExclusiveReductions

* Add Collection implementation for InclusiveReductions

* Update guide

* Add links for C++ implementations

* Add conformance to Collection for ExclusiveReductions

* Improve ergonomics of ExclusiveReductions' index representation

* Improve ergonomics of InclusiveReductions' index representation by sharing the Index implementation

* Tidy up internal function

* Add exclusive eager version of reductions(into:_:)

* Use new lazy assertion functions

* Correct the complexity claims for reductions

* Separate the index types

This will allow for future changes to either implementation without causing a breakage for the other.

* Update guide to reflect that arrays are returned directly

* Add scan as deprecated methods

* Add lazy overload of reductions(into:_:)

* Add the reductions(into:_:) functions

* More succinctly introduce reductions

* Add a note about the deprecated scan functions

* Update documentation

* Add @inlinable and @usableFromInline

* Copy documentation to all variants of reductions

* Test the value after the function is complete

* Just use the += operator

* Add an example for reductions(into:_:)

* Improve the documentation of the return value

* Update complexity note

* Use the reduce documentation for inspiration for the discussion of reductions
2021-03-24 17:10:09 +01:00
Nate CookandTim Vermeulen e652f01949 Add uniquePermutations as wrapper for nextPermutation (#91)
* Add uniquePermutations as wrapper for nextPermutation

* Implement uniquePermutations(ofCount:) variants

* Simplify UniquePermutations.Iterator.next()

* Add tests for uniquePermutations

* Move to a predicate-based uniquePermutations

* Add method documentation

* Convert to Hashable-based uniquing instead of Comparable

* Streamline tests, cover uniqueness

* Use optional count to collapse no-count method

* Update API documentation

* Remove leftover version of nextPermutation()

* Remove Hashable requirement from the UniquePermutations type

* Update documentation

* Apply Tim's great revisions

Co-authored-by: Tim Vermeulen <tvermeulen@apple.com>

* Add lazy conformance to UniquePermutations

Co-authored-by: Tim Vermeulen <tvermeulen@apple.com>
2021-03-24 15:17:27 +01:00
Karl 9783c1be91 Inline all the things! 🎨 (#109)
* Make suffix functions inlinable

* Inline all the things!
2021-03-23 15:00:09 -05:00
Charles Maria TorandXiaodi Wu e64cff7e1d Add Sequence.firstNonNil(_:) (#31)
* Add Sequence.firstNonNil(of:) and associated tests

* Rename First.swift to FirstTests.swift

* Address PR comments by adding guide and changing naming

* Address PR comments by changing name

* Update Guides/FirstNonNil.md

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

* Update Sources/Algorithms/FirstNonNil.swift

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

Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
2021-03-23 19:55:33 +01:00
Kyle Macomber 98b6e26d8d Remove .xcodesamplecode.plist, which prevents editing markdown from Xcode (#111) 2021-03-23 13:20:39 -05:00
Luciano Almeida ca8af77420 [test] Adding missing BidirectionalCollection::partition(subrange:) and MutableCollection::partition(subrange:) unit tests (#95) 2021-03-23 13:20:21 -05:00
Ahmad Alhashemi e077f67639 Improve XCTAssertEqualSequences to log difference (#105) 2021-03-23 07:52:56 -07:00
BJ Homer ed38a2dac4 Fix a broken link (#98) 2021-03-11 20:57:54 +01:00
Oliver AtkinsonandTim Vermeulen 18ec8500b7 Improve the performance of Stride when Base isa Collection (#88)
* Implement StrideSequence so that the default implementation for collection uses IndexingIterator

* Update Sources/Algorithms/Stride.swift

Co-authored-by: Tim Vermeulen <tvermeulen@apple.com>

* reinstate documentation for Sequence and remove explicit Sequence conformance on Stride

* documentation

* rename Stride to StrideCollection

Co-authored-by: Tim Vermeulen <tvermeulen@apple.com>
2021-03-10 18:20:00 +01:00
Tim Vermeulen ab0ec2adf4 Internally add Collection.endOfPrefix(while:) and BidirectionalCollection.startOfSuffix(while:) (#92)
* Add endOfPrefix(while:) and startOfSuffix(while:) internally

* Add tests

* Use these methods throughout the package
2021-03-09 20:03:55 +01:00
Todd Thomas e7c6716499 Add lazy split implementation. (#78)
`split(maxSplits:omittingEmptySubsequences:whereSeparator:)`

and

`split(separator:maxSplits:omittingEmptySubsequences:)`

now operate lazily when called on `LazySequenceProtocol`- or
`LazyCollectionProtocol`-conforming values. In the latter case,
no additional storage is allocated on the heap.
2021-03-09 01:48:58 -06:00
Matt Zanchelli d2546b8740 Correct link to Windows.md (#87) 2021-03-04 09:39:04 -06:00
32 changed files with 3450 additions and 224 deletions

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
<?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>
+43
View File
@@ -0,0 +1,43 @@
# First Non-Nil
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/FirstNonNil.swift) |
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/FirstNonNilTests.swift)]
Retrieves the first `.some` encountered while applying the given transform.
This operation is available through the `firstNonNil(_:)` method on any sequence.
```swift
let value = ["A", "B", "10"].firstNonNil { Int($0) }
// value == .some(10)
//
let noValue = ["A", "B", "C"].firstNonNil { Int($0) }
// noValue == .none
```
This method is analogous to `first(where:)` in how it only consumes values until
a `.some` is found, unlike using lazy operators, which will load any sequence into a collection
before evaluating its transforms lazily.
## Detailed Design
The `firstNonNil(_:)` method is added as an extension method on the `Sequence`
protocol:
```swift
public extension Sequence {
func firstNonNil<Result>(_ transform: (Element) throws -> Result?)
rethrows -> Result?
}
```
### Naming
This method’s name was selected for its comprehensibility.
### Comparison with other languages
**Scala**: Scala provides a `collectFirst` function that finds the first element
in a collection for which a partial function is defined.
+80
View File
@@ -0,0 +1,80 @@
# LazySplit
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/LazySplit.swift) |
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/LazySplitTests.swift)]
Lazily-evaluating versions of
[`split(maxSplits:omittingEmptySubsequences:whereSeparator:)`](https://developer.apple.com/documentation/swift/sequence/3128814-split)
and [`split(separator:maxSplits:omittingEmptySubsequences:)`](https://developer.apple.com/documentation/swift/sequence/3128818-split),
performing the same operation as their counterparts defined on
`Sequence` and `Collection`, are added to `LazySequence` and
`LazyCollection`. The `LazyCollection` methods allow splitting a
collection without allocating additional storage on the heap.
```swift
// Splitting a lazy sequence.
let numbers = stride(from: 1, through: 16, by: 1)
for subsequence in numbers.lazy.split(
whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 }
) {
print(subsequence)
}
/* Prints:
[1, 2]
[4]
[7, 8]
[11]
[13, 14]
[16]
*/
// Splitting a lazy collection.
let line = "BLANCHE: I don't want realism. I want magic!"
for subsequence in line.lazy.split(separator: " ") {
print(subsequence)
}
/* Prints
BLANCHE:
I
don't
want
realism.
I
want
magic!
*/
```
## Detailed Design
`LazySequence` and `LazyCollection` are each extended with
`split(maxSplits:omittingEmptySubsequences:whereSeparator:)` and
`split(separator:maxSplits:omittingEmptySubsequences:)`.
The `LazySequence` versions of those methods return an instance of
`LazySplitSequence`. The `LazyCollection` versions return an instance of
`LazySplitCollection`.
`LazySplitSequence` wraps the sequence to be split, and provides an
iterator whose `next` method returns a newly-allocated array containing
the elements of each subsequence in the split sequence in turn.
`LazySplitCollection` wraps the collection to be split. Its `Index`
wraps a range of base collection indices. `startIndex` is computed at
initialization. Subscripting a `LazySplitCollection` instance returns
the slice of the original collection which is the subsequence of the
split collection at the given index's position.
### Complexity
Iterating a `LazySplitSequence` instance is O(_n_) in time and space,
since each subsequence returned is a newly-allocated array.
Iterating a `LazySplitCollection` instance is O(_n_) in time and O(1) in
space, since each subsequence returned is a slice of the base
collection. Since `startIndex` is computed at initialization, some or
all of the time cost may be paid at initialization. For example, if the
base collection contains no elements determined to be separators, it
will be iterated entirely on initialization of the split collection, and
all subsequent operations on the split collection, such as
`index(after:)`, will have complexity O(1).
+35 -13
View File
@@ -3,7 +3,7 @@
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Permutations.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
Methods that compute permutations of a collection’s elements, or of a subset of
those elements.
The `permutations(ofCount:)` method, when called without the `ofCount`
@@ -60,7 +60,18 @@ for perm in numbers2.permutations() {
// [10, 10, 20]
```
Given a range, the `permutations(ofCount:)` method returns a sequence of all the different permutations of the given sizes of a collection’s elements in increasing order of size.
To generate only unique permutations, use the `uniquePermutations(ofCount:)` method:
```swift
for perm in numbers2.uniquePermutations() {
print(perm)
}
// [20, 10, 10]
// [10, 20, 10]
// [10, 10, 20]
```
Given a range, the methods return a sequence of all the different permutations of the given sizes of a collection’s elements in increasing order of size.
```swift
let numbers = [10, 20, 30]
@@ -87,21 +98,29 @@ for perm in numbers.permutations(ofCount: 0...) {
## Detailed Design
The `permutations(ofCount:)` method is declared as a `Collection` extension,
and returns a `Permutations` type:
The `permutations(ofCount:)` and `uniquePermutations(ofCount:)` methods are declared as `Collection` extensions,
and return `Permutations` and `UniquePermutations` instances, respectively:
```swift
extension Collection {
public func permutations(ofCount k: Int? = nil) -> Permutations<Self>
public func permutations<R>(ofCount kRange: R) -> Permutations<Self>
where R: RangeExpression, R.Bound == Int
}
extension Collection where Element: Hashable {
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self>
public func uniquePermutations<R>(ofCount kRange: R) -> UniquePermutations<Self>
where R: RangeExpression, R.Bound == Int
}
```
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
Since both result types need to store an array of the collection’s
indices and mutate the array to generate each permutation, they only
have `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. `Combinations` does conform to
`LazySequenceProtocol` when the base type conforms.
array at every index advancement. The `Permutations` type
conforms to `LazySequenceProtocol` when its base type conforms.
### Complexity
@@ -109,6 +128,10 @@ Calling `permutations()` is an O(1) operation. Creating the iterator for a
`Permutations` instance and each call to `Permutations.Iterator.next()` is an
O(_n_) operation.
Calling `uniquePermutations()` is an O(_n_) operation, because it preprocesses the
collection to find duplicate elements. Creating the iterator for and each call to
`next()` is also an O(_n_) operation.
### Naming
See the ["Naming" section for `combinations(ofCount:)`](Combinations.md#naming) for detail.
@@ -117,9 +140,8 @@ See the ["Naming" section for `combinations(ofCount:)`](Combinations.md#naming)
**C++:** The `<algorithm>` library defines a `next_permutation` function that
advances an array of comparable values through their lexicographic orderings.
This function is tricky to use and understand, so while it’s included in
`swift-algorithms` as an implementation detail of the `Permutations` type, it
isn’t public.
This function is very similar to the `uniquePermutations(ofCount:)` method.
**Rust/Ruby/Python:** Rust, Ruby, and Python all define functions with
essentially the same semantics as the method described here.
essentially the same semantics as the `permutations(ofCount:)` method
described here.
+136
View File
@@ -0,0 +1,136 @@
# Reductions
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Reductions.swift) |
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ReductionsTests.swift)]
Produces a sequence of values.
This has the behaviour of reduce, but also returns all intermediate results.
```swift
let exclusiveRunningTotal = (1...5).reductions(0, +)
print(exclusiveRunningTotal)
// prints [0, 1, 3, 6, 10, 15]
let intoRunningTotal = (1...5).reductions(into: 0, +=)
print(intoRunningTotal)
// prints [0, 1, 3, 6, 10, 15]
let inclusiveRunningTotal = (1...5).reductions(+)
print(inclusiveRunningTotal)
// prints [1, 3, 6, 10, 15]
```
## Detailed Design
One trio of methods are added to `LazySequenceProtocol` for a lazily evaluated
sequence and another trio are added to `Sequence` which are eagerly evaluated.
```swift
extension LazySequenceProtocol {
public func reductions<Result>(
_ initial: Result,
_ transform: @escaping (Result, Element) -> Result
) -> ExclusiveReductions<Result, Self>
public func reductions<Result>(
into initial: Result,
_ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductions<Result, Self>
public func reductions(
_ transform: @escaping (Element, Element) -> Element
) -> InclusiveReductions<Self>
}
```
```swift
extension Sequence {
public func reductions<Result>(
_ initial: Result,
_ transform: (Result, Element) throws -> Result
) rethrows -> [Result]
public func reductions<Result>(
into initial: Result,
_ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result]
public func reductions(
_ transform: (Element, Element) throws -> Element
) rethrows -> [Element]
}
```
### Complexity
Calling the lazy methods, those defined on `LazySequenceProtocol`, is O(_1_).
Calling the eager methods, those returning an array, is O(_n_).
### Naming
While the name `scan` is the term of art for this function, it has been
discussed that `reductions` aligns better with the existing `reduce` function
and will aid newcomers that might not know the existing `scan` term.
Deprecated `scan` methods have been added for people who are familiar with the
term, so they can easily discover the `reductions` methods via compiler
deprecation warnings.
Below are two quotes from the Swift forum [discussion about SE-0045][SE-0045]
which proposed adding `scan` to the standard library and one from
[issue #25][Issue 25] on the swift-algorithms GitHub project. These provide
the reasoning to use the name `reductions`.
[Brent Royal-Gordon][Brent_Royal-Gordon]:
> I really like the `reduce`/`reductions` pairing instead of `reduce`/`scan`;
it does a really good job of explaining the relationship between the two
functions.
[David Rönnqvist][David Rönnqvist]:
> As other have already pointed out, I also feel that `scan` is the least
intuitive name among these and that the `reduce`/`reductions` pairing would do
a good job at explaining the relation between the two.
[Kyle Macomber][Kyle Macomber]:
> As someone unfamiliar with the prior art, `reductions` strikes me as very
approachable—I feel like I can extrapolate the expected behavior purely from my
familiarity with `reduce`.
As part of early discussions, it was decided to have two variants, one which
takes an initial value to use for the first element in the returned sequence,
and another which uses the first value of the base sequence as the initial
value. C++ calls these variants exclusive and inclusive respectively and so
these terms carry through as the name for the lazy sequences;
`ExclusiveReductions` and `InclusiveReductions`.
[SE-0045]: https://forums.swift.org/t/review-se-0045-add-scan-prefix-while-drop-while-and-iterate-to-the-stdlib/2382
[Issue 25]: https://github.com/apple/swift-algorithms/issues/25
[Brent_Royal-Gordon]: https://forums.swift.org/t/review-se-0045-add-scan-prefix-while-drop-while-and-iterate-to-the-stdlib/2382/6
[David Rönnqvist]: https://forums.swift.org/t/review-se-0045-add-scan-prefix-while-drop-while-and-iterate-to-the-stdlib/2382/8
[Kyle Macomber]: https://github.com/apple/swift-algorithms/issues/25#issuecomment-709317894
### Comparison with other langauges
**C++:** As of C++17, the `<algorithm>` library includes both
[`exclusive_scan`][C++ Exclusive] and [`inclusive_scan`][C++ Inclusive]
functions.
**[Clojure][Clojure]:** Clojure 1.2 added a `reductions` function.
**[Haskell][Haskell]:** Haskell includes a `scan` function for its
`Traversable` type, which is akin to Swift's `Sequence`.
**Python:** Python’s `itertools` includes an `accumulate` method. In version
3.3, a function paramenter was added. Version 3.8 added the optional initial
parameter.
**[Rust][Rust]:** Rust provides a `scan` function.
[C++ Exclusive]: https://en.cppreference.com/w/cpp/algorithm/exclusive_scan
[C++ Inclusive]: https://en.cppreference.com/w/cpp/algorithm/inclusive_scan
[Clojure]: http://clojure.github.io/clojure/clojure.core-api.html#clojure.core/reductions
[Haskell]: http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:scanl
[Rust]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.scan
+4 -2
View File
@@ -10,6 +10,7 @@ Read more about the package, and the intent behind it, in the [announcement on s
- [`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
@@ -37,10 +38,11 @@ Read more about the package, and the intent behind it, in the [announcement on s
- [`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.
- [`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/Interspersed.md): Place a value between every two elements of a sequence.
- [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence.
- [`trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start and end.
- [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/SlidingWindows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection.
- [`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.
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/LazySplit.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element.
## Adding Swift Algorithms as a Dependency
+7 -7
View File
@@ -19,7 +19,7 @@ public struct Chain2<Base1: Sequence, Base2: Sequence>
/// The second sequence in this chain.
public let base2: Base2
@usableFromInline
@inlinable
internal init(base1: Base1, base2: Base2) {
self.base1 = base1
self.base2 = base2
@@ -35,7 +35,7 @@ extension Chain2: Sequence {
@usableFromInline
internal var iterator2: Base2.Iterator
@usableFromInline
@inlinable
internal init(_ concatenation: Chain2) {
iterator1 = concatenation.base1.makeIterator()
iterator2 = concatenation.base2.makeIterator()
@@ -71,13 +71,13 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
internal let position: Representation
/// Creates a new index into the first underlying collection.
@usableFromInline
@inlinable
internal init(first i: Base1.Index) {
position = .first(i)
}
/// Creates a new index into the second underlying collection.
@usableFromInline
@inlinable
internal init(second i: Base2.Index) {
position = .second(i)
}
@@ -99,7 +99,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
/// Converts an index of `Base1` to the corresponding `Index` by mapping
/// `base1.endIndex` to `base2.startIndex`.
@usableFromInline
@inlinable
internal func convertIndex(_ i: Base1.Index) -> Index {
i == base1.endIndex ? Index(second: base2.startIndex) : Index(first: i)
}
@@ -157,7 +157,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
: offsetBackward(i, by: -n, limitedBy: limit)
}
@usableFromInline
@inlinable
internal func offsetForward(
_ i: Index, by n: Int, limitedBy limit: Index
) -> Index? {
@@ -197,7 +197,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
}
}
@usableFromInline
@inlinable
internal func offsetBackward(
_ i: Index, by n: Int, limitedBy limit: Index
) -> Index? {
+16 -28
View File
@@ -27,7 +27,7 @@ public struct LazyChunked<Base: Collection, Subject> {
@usableFromInline
internal var firstUpperBound: Base.Index
@usableFromInline
@inlinable
internal init(
base: Base,
projection: @escaping (Base.Element) -> Subject,
@@ -51,7 +51,7 @@ extension LazyChunked: LazyCollectionProtocol {
@usableFromInline
internal var baseRange: Range<Base.Index>
@usableFromInline
@inlinable
internal init(_ baseRange: Range<Base.Index>) {
self.baseRange = baseRange
}
@@ -72,12 +72,11 @@ extension LazyChunked: LazyCollectionProtocol {
/// Returns the index in the base collection of the end of the chunk starting
/// at the given index.
@usableFromInline
@inlinable
internal func endOfChunk(startingAt start: Base.Index) -> Base.Index {
let subject = projection(base[start])
return base[base.index(after: start)...]
.firstIndex(where: { !belongInSameGroup(subject, projection($0)) })
?? base.endIndex
.endOfPrefix(while: { belongInSameGroup(subject, projection($0)) })
}
@inlinable
@@ -113,26 +112,14 @@ extension LazyChunked: BidirectionalCollection
{
/// Returns the index in the base collection of the start of the chunk ending
/// at the given index.
@usableFromInline
@inlinable
internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
let indexBeforeEnd = base.index(before: end)
// Get the projected value of the last element in the range ending at `end`.
let subject = projection(base[indexBeforeEnd])
// Search backward from `end` for the first element whose projection isn't
// equal to `subject`.
if let firstMismatch = base[..<indexBeforeEnd]
.lastIndex(where: { !belongInSameGroup(projection($0), subject) })
{
// If we found one, that's the last element of the _next_ previous chunk,
// and therefore one position _before_ the start of this chunk.
return base.index(after: firstMismatch)
} else {
// If we didn't find such an element, this chunk extends back to the start
// of the collection.
return base.startIndex
}
return base[..<indexBeforeEnd]
.startOfSuffix(while: { belongInSameGroup(projection($0), subject) })
}
@inlinable
@@ -187,7 +174,7 @@ extension Collection {
/// predicate.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
@usableFromInline
@inlinable
internal func chunked<Subject>(
on projection: (Element) throws -> Subject,
by belongInSameGroup: (Subject, Subject) throws -> Bool
@@ -286,7 +273,7 @@ extension ChunkedByCount: Collection {
@usableFromInline
internal let baseRange: Range<Base.Index>
@usableFromInline
@inlinable
internal init(_baseRange: Range<Base.Index>) {
self.baseRange = _baseRange
}
@@ -303,6 +290,7 @@ extension ChunkedByCount: Collection {
}
/// - Complexity: O(1)
@inlinable
public subscript(i: Index) -> Element {
precondition(i < endIndex, "Index out of range")
return base[i.baseRange]
@@ -405,7 +393,7 @@ extension ChunkedByCount {
return index
}
@usableFromInline
@inlinable
internal func offsetForward(
_ i: Index, offsetBy distance: Int, limit: Index? = nil
) -> Index? {
@@ -419,8 +407,8 @@ extension ChunkedByCount {
}
// Convenience to compute offset backward base distance.
@inline(__always)
private func computeOffsetBackwardBaseDistance(
@inlinable
internal func computeOffsetBackwardBaseDistance(
_ i: Index, _ distance: Int
) -> Int {
if i == endIndex {
@@ -436,7 +424,7 @@ extension ChunkedByCount {
return distance * chunkCount
}
@usableFromInline
@inlinable
internal func offsetBackward(
_ i: Index, offsetBy distance: Int, limit: Index? = nil
) -> Index? {
@@ -451,8 +439,8 @@ extension ChunkedByCount {
}
// Helper to compute index(offsetBy:) index.
@inline(__always)
private func makeOffsetIndex(
@inlinable
internal func makeOffsetIndex(
from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int,
limit: Index?, by limitFn: (Base.Index, Base.Index) -> Bool
) -> Index? {
+5 -4
View File
@@ -27,7 +27,7 @@ public struct Combinations<Base: Collection> {
/// - Parameters:
/// - base: The collection to iterate over for combinations.
/// - k: The expected size of each combination.
@usableFromInline
@inlinable
internal init(_ base: Base, k: Int) {
self.init(base, kRange: k...k)
}
@@ -37,7 +37,7 @@ public struct Combinations<Base: Collection> {
/// - Parameters:
/// - base: The collection to iterate over for combinations.
/// - kRange: The range of accepted sizes of combinations.
@usableFromInline
@inlinable
internal init<R: RangeExpression>(
_ base: Base, kRange: R
) where R.Bound == Int {
@@ -89,7 +89,7 @@ extension Combinations: Sequence {
internal var kRange: Range<Int>
/// Whether or not iteration is finished (`kRange` is empty)
@usableFromInline
@inlinable
internal var isFinished: Bool {
return kRange.isEmpty
}
@@ -97,6 +97,7 @@ extension Combinations: Sequence {
@usableFromInline
internal var indexes: [Base.Index]
@inlinable
internal init(_ combinations: Combinations) {
self.base = combinations.base
self.kRange = combinations.kRange ?? 0..<0
@@ -121,7 +122,7 @@ extension Combinations: Sequence {
/// [2, 3, 4] *
/// // Can't advance without needing to go past `base.endIndex`,
/// // so the iteration is finished.
@usableFromInline
@inlinable
internal mutating func advance() {
/// Advances `kRange` by incrementing its `lowerBound` until the range is
/// empty, when iteration is finished.
+2 -2
View File
@@ -14,7 +14,7 @@ public struct Cycle<Base: Collection> {
/// The collection to repeat.
public let base: Base
@usableFromInline
@inlinable
internal init(base: Base) {
self.base = base
}
@@ -29,7 +29,7 @@ extension Cycle: Sequence {
@usableFromInline
var current: Base.Index
@usableFromInline
@inlinable
internal init(base: Base) {
self.base = base
self.current = base.startIndex
+28
View File
@@ -0,0 +1,28 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// firstNonNil(_:)
//===----------------------------------------------------------------------===//
public extension Sequence {
/// Returns the first element in `self` that `transform` maps to a `.some`.
func firstNonNil<Result>(
_ transform: (Element) throws -> Result?
) rethrows -> Result? {
for value in self {
if let value = try transform(value) {
return value
}
}
return nil
}
}
+1 -1
View File
@@ -18,7 +18,7 @@ public struct Indexed<Base: Collection> {
/// The base collection.
public let base: Base
@usableFromInline
@inlinable
internal init(base: Base) {
self.base = base
}
+9 -4
View File
@@ -18,7 +18,7 @@ public struct Intersperse<Base: Sequence> {
@usableFromInline
internal let separator: Base.Element
@usableFromInline
@inlinable
internal init(base: Base, separator: Base.Element) {
self.base = base
self.separator = separator
@@ -37,7 +37,7 @@ extension Intersperse: Sequence {
@usableFromInline
internal var state = State.start
@usableFromInline
@inlinable
internal init(iterator: Base.Iterator, separator: Base.Element) {
self.iterator = iterator
self.separator = separator
@@ -89,6 +89,11 @@ extension Intersperse: Collection where Base: Collection {
@usableFromInline
internal let representation: Representation
@inlinable
init(representation: Representation) {
self.representation = representation
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs.representation, rhs.representation) {
@@ -101,12 +106,12 @@ extension Intersperse: Collection where Base: Collection {
}
}
@usableFromInline
@inlinable
static func element(_ index: Base.Index) -> Self {
Self(representation: .element(index))
}
@usableFromInline
@inlinable
static func separator(next: Base.Index) -> Self {
Self(representation: .separator(next: next))
}
+750
View File
@@ -0,0 +1,750 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// LazySplitSequence
//===----------------------------------------------------------------------===//
/// A sequence that lazily splits a base sequence into subsequences separated by
/// elements that satisfy the given `whereSeparator` predicate.
///
/// - Note: This type is the result of
///
/// x.split(maxSplits:omittingEmptySubsequences:whereSeparator)
/// x.split(separator:maxSplits:omittingEmptySubsequences)
///
/// where `x` conforms to `LazySequenceProtocol`.
public struct LazySplitSequence<Base: Sequence> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let isSeparator: (Base.Element) -> Bool
@usableFromInline
internal let maxSplits: Int
@usableFromInline
internal let omittingEmptySubsequences: Bool
@inlinable
internal init(
base: Base,
isSeparator: @escaping (Base.Element) -> Bool,
maxSplits: Int,
omittingEmptySubsequences: Bool
) {
self.base = base
self.isSeparator = isSeparator
self.maxSplits = maxSplits
self.omittingEmptySubsequences = omittingEmptySubsequences
}
}
extension LazySplitSequence {
public struct Iterator {
public typealias Element = [Base.Element]
@usableFromInline
internal var base: Base.Iterator
@usableFromInline
internal let isSeparator: (Base.Element) -> Bool
@usableFromInline
internal let maxSplits: Int
@usableFromInline
internal let omittingEmptySubsequences: Bool
/// The number of splits performed.
@usableFromInline
internal var splitCount = 0
/// The number of subsequences returned.
@usableFromInline
internal var sequenceLength = 0
@inlinable
internal init(
base: Base.Iterator,
whereSeparator: @escaping (Base.Element) -> Bool,
maxSplits: Int,
omittingEmptySubsequences: Bool
) {
self.base = base
self.isSeparator = whereSeparator
self.maxSplits = maxSplits
self.omittingEmptySubsequences = omittingEmptySubsequences
}
}
}
extension LazySplitSequence.Iterator: IteratorProtocol {
@inlinable
public mutating func next() -> Element? {
var currentElement = base.next()
var subsequence: Element = []
// Add the next elements of the base sequence to this subsequence, until we
// reach a separator, unless we've already split the maximum number of
// times. In all cases, stop at the end of the base sequence.
while currentElement != nil {
if splitCount < maxSplits && isSeparator(currentElement!) {
if omittingEmptySubsequences && subsequence.isEmpty {
// Keep going if we don't want to return an empty subsequence.
currentElement = base.next()
continue
} else {
splitCount += 1
break
}
} else {
subsequence.append(currentElement!)
currentElement = base.next()
}
}
// We're done iterating when we've reached the end of the base sequence,
// and we've either returned the maximum number of subsequences (one more
// than the number of separators), or the only subsequence left to return is
// empty and we're omitting those.
if currentElement == nil
&& (sequenceLength == splitCount + 1
|| omittingEmptySubsequences && subsequence.isEmpty)
{
return nil
} else {
sequenceLength += 1
return subsequence
}
}
}
extension LazySplitSequence: LazySequenceProtocol {
@inlinable
public func makeIterator() -> Iterator {
return Iterator(
base: base.makeIterator(),
whereSeparator: self.isSeparator,
maxSplits: self.maxSplits,
omittingEmptySubsequences: self.omittingEmptySubsequences
)
}
}
extension LazySequenceProtocol {
/// Lazily returns the longest possible subsequences of the sequence, in
/// order, that don't contain elements satisfying the given predicate.
///
/// The resulting lazy sequence consists of at most `maxSplits + 1`
/// subsequences. Elements that are used to split the sequence are not
/// returned as part of any subsequence (except possibly the last one, in the
/// case where `maxSplits` is less than the number of separators in the
/// sequence).
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when lazily splitting a sequence of
/// integers using a closure that matches numbers evenly divisible by 3 or 5.
/// The first use of `split` returns each subsequence that was originally
/// separated by one or more such numbers.
///
/// let numbers = stride(from: 1, through: 16, by: 1)
/// for subsequence in numbers.lazy.split(
/// whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 }
/// ) {
/// print(subsequence)
/// }
/// /* Prints:
/// [1, 2]
/// [4]
/// [7, 8]
/// [11]
/// [13, 14]
/// [16]
/// */
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original sequence is split just once, into two subsequences.
///
/// for subsequence in numbers.lazy.split(
/// maxSplits: 1,
/// whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 }
/// ) {
/// print(subsequence)
/// }
/// /* Prints:
/// [1, 2]
/// [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
/// */
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the sequence of returned subsequences contains empty
/// subsequences where numbers evenly divisible by 3 or 5 were repeated.
///
/// for subsequence in numbers.lazy.split(
/// omittingEmptySubsequences: false,
/// whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 }
/// ) {
/// print(subsequence)
/// }
/// /* Prints:
/// [1, 2]
/// [4]
/// []
/// [7, 8]
/// []
/// [11]
/// [13, 14]
/// [16]
/// */
///
/// - Parameters:
/// - maxSplits: The maximum number of times to split the sequence, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original sequence containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each pair of consecutive elements
/// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the sequence satisfying the `isSeparator`
/// predicate. The default value is `true`.
/// - whereSeparator: A closure that takes an element as an argument and
/// returns a Boolean value indicating whether the sequence should be
/// split at that element.
/// - Returns: A lazy sequence of subsequences, split from this sequence's
/// elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: @escaping (Element) -> Bool
) -> LazySplitSequence<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitSequence(
base: elements,
isSeparator: isSeparator,
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences
)
}
}
extension LazySequenceProtocol where Element: Equatable {
/// Lazily returns the longest possible subsequences of the sequence, in
/// order, around elements equal to the given element.
///
/// The resulting lazy sequence consists of at most `maxSplits + 1`
/// subsequences. Elements that are used to split the sequence are not
/// returned as part of any subsequence (except possibly the last one, in the
/// case where `maxSplits` is less than the number of separators in the
/// sequence).
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a sequence of
/// integers at each zero (`0`). The first use of `split` returns each
/// subsequence that was originally separated by one or more zeros.
///
/// let numbers = AnySequence([1, 2, 0, 3, 4, 0, 0, 5])
/// for subsequence in numbers.lazy.split(separator: 0) {
/// print(subsequence)
/// }
/// /* Prints:
/// [1, 2]
/// [3, 4]
/// [5]
/// */
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original sequence is split just once, into two subsequences.
///
/// for subsequence in numbers.lazy.split(
/// separator: 0,
/// maxSplits: 1
/// ) {
/// print(subsequence)
/// }
/// /* Prints:
/// [1, 2]
/// [3, 4, 0, 0, 5]
/// */
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the sequence of returned subsequences contains empty
/// subsequences where zeros were repeated.
///
/// for subsequence in numbers.lazy.split(
/// separator: 0,
/// omittingEmptySubsequences: false
/// ) {
/// print(subsequence)
/// }
/// /* Prints:
/// [1, 2]
/// [3, 4]
/// []
/// [5]
/// */
///
/// - Parameters:
/// - separator: The element that should be split upon.
/// - maxSplits: The maximum number of times to split the sequence, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original sequence containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each consecutive pair of `separator`
/// elements in the sequence and for each instance of `separator` at
/// the start or end of the sequence. If `true`, only nonempty
/// subsequences are returned. The default value is `true`.
/// - Returns: A lazy sequence of subsequences, split from this sequence's
/// elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func split(
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> LazySplitSequence<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitSequence(
base: elements,
isSeparator: { $0 == separator },
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences
)
}
}
//===----------------------------------------------------------------------===//
// LazySplitCollection
//===----------------------------------------------------------------------===//
/// A collection that lazily splits a base collection into subsequences
/// separated by elements that satisfy the given `whereSeparator` predicate.
///
/// - Note: This type is the result of
///
/// x.split(maxSplits:omittingEmptySubsequences:whereSeparator)
/// x.split(separator:maxSplits:omittingEmptySubsequences)
///
/// where `x` conforms to `LazyCollectionProtocol`.
public struct LazySplitCollection<Base: Collection> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let isSeparator: (Base.Element) -> Bool
@usableFromInline
internal let maxSplits: Int
@usableFromInline
internal let omittingEmptySubsequences: Bool
@usableFromInline
internal var _startIndex: Index
@inlinable
internal init(
base: Base,
isSeparator: @escaping (Base.Element) -> Bool,
maxSplits: Int,
omittingEmptySubsequences: Bool
) {
self.base = base
self.isSeparator = isSeparator
self.maxSplits = maxSplits
self.omittingEmptySubsequences = omittingEmptySubsequences
// We precalculate `startIndex`. There are three possibilities:
// 1. `base` is empty and we're _not_ omitting empty subsequences, in which
// case the following index describes the sole element of this collection;
self._startIndex = Index(
baseRange: base.startIndex..<base.startIndex,
sequenceLength: 1,
splitCount: 0
)
if base.isEmpty {
if omittingEmptySubsequences {
// 2. `base` is empty and we _are_ omitting empty subsequences, so this
// collection has no elements;
_startIndex = endIndex
}
} else {
// 3. `base` isn't empty, so we must iterate it to determine the start
// index.
_startIndex = indexForSubsequence(
atOrAfter: base.startIndex,
sequenceLength: 0,
splitCount: 0
)
}
}
}
extension LazySplitCollection: LazyCollectionProtocol {
/// Position of a subsequence in a split collection.
public struct Index: Comparable {
/// The range corresponding to the subsequence at this position.
@usableFromInline
internal let baseRange: Range<Base.Index>
/// The number of subsequences up to and including this position in the
/// collection.
@usableFromInline
internal let sequenceLength: Int
/// The number splits performed up to and including this position in the
/// collection.
@usableFromInline
internal let splitCount: Int
@inlinable
internal init(
baseRange: Range<Base.Index>,
sequenceLength: Int,
splitCount: Int
) {
self.baseRange = baseRange
self.sequenceLength = sequenceLength
self.splitCount = splitCount
}
@inlinable
public static func == (lhs: Index, rhs: Index) -> Bool {
// `sequenceLength` is equivalent to the index's 1-based position in the
// collection of indices.
lhs.sequenceLength == rhs.sequenceLength
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.sequenceLength < rhs.sequenceLength
}
}
/// Returns the index of the subsequence starting at or after the given base
/// collection index.
@inlinable
internal func indexForSubsequence(
atOrAfter lowerBound: Base.Index,
sequenceLength: Int,
splitCount: Int
) -> Index {
var start = lowerBound
// If we don't have any more splits to do (which we'll determine shortly),
// the end of this subsequence will be the end of the base collection.
var end = base.endIndex
if splitCount < maxSplits {
// The non-inclusive end of this subsequence is marked by the next
// separator, or the end of the base collection.
end =
base[start...].firstIndex(where: isSeparator)
?? base.endIndex
if base[start..<end].isEmpty {
if omittingEmptySubsequences {
// Find the next subsequence of non-separators.
start =
base[end...].firstIndex(where: { !isSeparator($0) })
?? base.endIndex
if start == base.endIndex {
// No non-separators left in the base collection. We're done.
return endIndex
}
end = base[start...].firstIndex(where: isSeparator) ?? base.endIndex
}
}
}
var updatedSplitCount = splitCount
if end < base.endIndex {
// This subsequence ends on a separator (and perhaps includes other
// separators, if we're omitting empty subsequences), so we've performed
// another split.
updatedSplitCount += 1
}
return Index(
baseRange: start..<end,
sequenceLength: sequenceLength + 1,
splitCount: updatedSplitCount
)
}
@inlinable
public var startIndex: Index {
_startIndex
}
@inlinable
public var endIndex: Index {
Index(
baseRange: base.endIndex..<base.endIndex,
sequenceLength: Int.max,
splitCount: Int.max
)
}
@inlinable
public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance past endIndex")
var subsequenceStart = i.baseRange.upperBound
if subsequenceStart < base.endIndex {
// If we're not already at the end of the base collection, the previous
// susequence ended with a separator. Start searching for the next
// subsequence at the following element.
subsequenceStart = base.index(after: i.baseRange.upperBound)
}
guard subsequenceStart != base.endIndex else {
if !omittingEmptySubsequences
&& i.sequenceLength < i.splitCount + 1
{
// The base collection ended with a separator, so we need to emit one
// more empty subsequence. This one differs from `endIndex` in its
// `sequenceLength` (except in an extreme edge case!), which is the
// sole property tested for equality and comparison.
return Index(
baseRange: base.endIndex..<base.endIndex,
sequenceLength: i.sequenceLength + 1,
splitCount: i.splitCount
)
} else {
return endIndex
}
}
return indexForSubsequence(
atOrAfter: subsequenceStart,
sequenceLength: i.sequenceLength,
splitCount: i.splitCount
)
}
@inlinable
public subscript(position: Index) -> Base.SubSequence {
precondition(position != endIndex, "Can't subscript using endIndex")
return base[position.baseRange]
}
}
extension LazySplitCollection.Index: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(sequenceLength)
}
}
extension LazyCollectionProtocol {
/// Lazily returns the longest possible subsequences of the collection, in
/// order, that don't contain elements satisfying the given predicate.
///
/// The resulting lazy collection consists of at most `maxSplits + 1`
/// subsequences. Elements that are used to split the collection are not
/// returned as part of any subsequence (except possibly the last one, in the
/// case where `maxSplits` is less than the number of separators in the
/// collection).
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when lazily splitting a string
/// using a closure that matches spaces. The first use of `split` returns each
/// word that was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// for spaceless in line.lazy.split(whereSeparator: { $0 == " " }) {
/// print(spaceless)
/// }
/// // Prints
/// // BLANCHE:
/// // I
/// // don't
/// // want
/// // realism.
/// // I
/// // want
/// // magic!
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// for spaceless in line.lazy.split(
/// maxSplits: 1,
/// whereSeparator: { $0 == " " }
/// ) {
/// print(spaceless)
/// }
/// // Prints
/// // BLANCHE:
/// // I don't want realism. I want magic!
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// for spaceless in line.lazy.split(
/// omittingEmptySubsequences: false,
/// whereSeparator: { $0 == " " }
/// ) {
/// print(spaceless)
/// }
/// // Prints
/// // BLANCHE:
/// //
/// //
/// // I
/// // don't
/// // want
/// // realism.
/// // I
/// // want
/// // magic!
///
/// - Parameters:
/// - maxSplits: The maximum number of times to split the collection, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original collection containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each pair of consecutive elements
/// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the collection satisfying the `isSeparator`
/// predicate. The default value is `true`.
/// - whereSeparator: A closure that takes an element as an argument and
/// returns a Boolean value indicating whether the collection should be
/// split at that element.
/// - Returns: A lazy collection of subsequences, split from this collection's
/// elements.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: @escaping (Element) -> Bool
) -> LazySplitCollection<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitCollection(
base: elements,
isSeparator: isSeparator,
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences
)
}
}
extension LazyCollectionProtocol
where Element: Equatable {
/// Lazily returns the longest possible subsequences of the collection, in
/// order, around elements equal to the given element.
///
/// The resulting lazy collection consists of at most `maxSplits + 1`
/// subsequences. Elements that are used to split the collection are not
/// returned as part of any subsequence (except possibly the last one, in the
/// case where `maxSplits` is less than the number of separators in the
/// collection).
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string at each
/// space character (" "). The first use of `split` returns each word that
/// was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// for spaceless in line.lazy.split(separator: " ") {
/// print(spaceless)
/// }
/// // Prints
/// // BLANCHE:
/// // I
/// // don't
/// // want
/// // realism.
/// // I
/// // want
/// // magic!
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// for spaceless in line.lazy.split(separator: " ", maxSplits: 1) {
/// print(spaceless)
/// }
/// // Prints
/// // BLANCHE:
/// // I don't want realism. I want magic!
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// for spaceless in line.lazy.split(
/// separator: " ",
/// omittingEmptySubsequences: false
/// ) {
/// print(spaceless)
/// }
/// // Prints
/// // BLANCHE:
/// //
/// //
/// // I
/// // don't
/// // want
/// // realism.
/// // I
/// // want
/// // magic!
///
/// - Parameters:
/// - separator: The element that should be split upon.
/// - maxSplits: The maximum number of times to split the collection, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original collection containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each consecutive pair of `separator`
/// elements in the collection and for each instance of `separator` at
/// the start or end of the collection. If `true`, only nonempty
/// subsequences are returned. The default value is `true`.
/// - Returns: A lazy collection of subsequences split from this collection's
/// elements.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func split(
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> LazySplitCollection<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitCollection(
base: elements,
isSeparator: { $0 == separator },
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences
)
}
}
+2 -2
View File
@@ -120,7 +120,7 @@ extension Sequence {
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
}
/// Returns the largets elements of this sequence, as sorted by the given
/// Returns the largest elements of this sequence, as sorted by the given
/// predicate.
///
/// This example partially sorts an array of integers to retrieve its three
@@ -275,7 +275,7 @@ extension Collection {
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
}
/// Returns the largets elements of this collection, as sorted by the given
/// Returns the largest elements of this collection, as sorted by the given
/// predicate.
///
/// This example partially sorts an array of integers to retrieve its three
+1 -1
View File
@@ -21,7 +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
@inlinable
internal mutating func stablePartition(
count n: Int,
subrange: Range<Index>,
+298 -79
View File
@@ -9,6 +9,72 @@
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// nextPermutation()
//===----------------------------------------------------------------------===//
extension MutableCollection
where Self: BidirectionalCollection, Element: Comparable
{
/// Permutes this collection's elements through all the lexical orderings.
///
/// Call `nextPermutation()` repeatedly starting with the collection in
/// sorted order. When the full cycle of all permutations has been completed,
/// the collection will be back in sorted order and this method will return
/// `false`.
///
/// - Returns: A Boolean value indicating whether the collection still has
/// remaining permutations. When this method returns `false`, the collection
/// is in ascending order according to `areInIncreasingOrder`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
internal mutating func nextPermutation(upperBound: Index? = nil) -> Bool {
// Ensure we have > 1 element in the collection.
guard !isEmpty else { return false }
var i = index(before: endIndex)
if i == startIndex { return false }
let upperBound = upperBound ?? endIndex
while true {
let ip1 = i
formIndex(before: &i)
// Find the last ascending pair (ie. ..., a, b, ... where a < b)
if self[i] < self[ip1] {
// Find the last element greater than self[i]
// This is _always_ at most `ip1` due to if statement above
let j = lastIndex(where: { self[i] < $0 })!
// At this point we have something like this:
// 0, 1, 4, 3, 2
// ^ ^
// i j
swapAt(i, j)
self.reverse(subrange: ip1 ..< endIndex)
// Only return if we've made a change within ..<upperBound region
if i < upperBound {
return true
} else {
i = index(before: endIndex)
continue
}
}
if i == startIndex {
self.reverse()
return false
}
}
}
}
//===----------------------------------------------------------------------===//
// struct Permutations<Base>
//===----------------------------------------------------------------------===//
/// A sequence of all the permutations of a collection's elements.
public struct Permutations<Base: Collection> {
/// The base collection to iterate over for permutations.
@@ -28,7 +94,7 @@ public struct Permutations<Base: Collection> {
/// - base: The collection to iterate over for permutations
/// - k: The expected size of each permutation, or `nil` (default) to
/// iterate over all permutations of the same size as the base collection.
@usableFromInline
@inlinable
internal init(_ base: Base, k: Int? = nil) {
let kRange: ClosedRange<Int>?
if let countToChoose = k {
@@ -45,7 +111,7 @@ public struct Permutations<Base: Collection> {
/// - base: The collection to iterate over for permutations.
/// - kRange: The range of accepted sizes of permutations, or `nil` to
/// iterate over all permutations of the same size as the base collection.
@usableFromInline
@inlinable
internal init<R: RangeExpression>(
_ base: Base, kRange: R?
) where R.Bound == Int {
@@ -84,7 +150,7 @@ extension Permutations: Sequence {
internal var kRange: Range<Int>
/// Whether or not iteration is finished (`kRange` is empty)
@usableFromInline
@inlinable
internal var isFinished: Bool {
return kRange.isEmpty
}
@@ -92,7 +158,7 @@ extension Permutations: Sequence {
@usableFromInline
internal var indexes: [Base.Index]
@usableFromInline
@inlinable
internal init(_ permutations: Permutations) {
self.base = permutations.base
self.baseCount = permutations.baseCount
@@ -111,7 +177,7 @@ extension Permutations: Sequence {
/// is in ascending order.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@usableFromInline
@inlinable
internal mutating func nextState() -> Bool {
let countToChoose = self.kRange.lowerBound
let edge = countToChoose - 1
@@ -194,54 +260,6 @@ extension Permutations: Sequence {
extension Permutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===//
// nextPermutation()
//===----------------------------------------------------------------------===//
extension MutableCollection
where Self: BidirectionalCollection, Element: Comparable
{
/// Permutes this collection's elements through all the lexical orderings.
///
/// Call `nextPermutation()` repeatedly starting with the collection in
/// sorted order. When the full cycle of all permutations has been completed,
/// the collection will be back in sorted order and this method will return
/// `false`.
///
/// - Returns: A Boolean value indicating whether the collection still has
/// remaining permutations. When this method returns `false`, the collection
/// 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.
guard !isEmpty else { return false }
var i = index(before: endIndex)
if i == startIndex { return false }
while true {
let ip1 = i
formIndex(before: &i)
if self[i] < self[ip1] {
var j = index(before: endIndex)
while self[i] >= self[j] {
formIndex(before: &j)
}
swapAt(i, j)
self.reverse(subrange: ip1 ..< endIndex)
return true
}
if i == startIndex {
self.reverse()
return false
}
}
}
}
//===----------------------------------------------------------------------===//
// permutations(ofCount:)
//===----------------------------------------------------------------------===//
@@ -268,34 +286,41 @@ extension Collection {
/// // Davide, Celeste
///
/// This example prints _all_ the permutations (including an empty array) from
/// the an array of numbers:
/// an array of numbers:
///
/// let numbers = [10, 20, 30]
/// for perm in numbers.permutations(ofCount: 0...) {
/// print(perm)
/// }
/// // []
/// // [10]
/// // [20]
/// // [30]
/// // [10, 20]
/// // [10, 30]
/// // [20, 10]
/// // [20, 30]
/// // [30, 10]
/// // [30, 20]
/// // [10, 20, 30]
/// // [10, 30, 20]
/// // [20, 10, 30]
/// // [20, 30, 10]
/// // [30, 10, 20]
/// // [30, 20, 10]
/// for perm in numbers.permutations(ofCount: 0...) {
/// print(perm)
/// }
/// // []
/// // [10]
/// // [20]
/// // [30]
/// // [10, 20]
/// // [10, 30]
/// // [20, 10]
/// // [20, 30]
/// // [30, 10]
/// // [30, 20]
/// // [10, 20, 30]
/// // [10, 30, 20]
/// // [20, 10, 30]
/// // [20, 30, 10]
/// // [30, 10, 20]
/// // [30, 20, 10]
///
/// - Parameter kRange: The number of elements to include in each permutation.
/// The returned permutations are in ascending order by length, and then
/// lexicographically within each group of the same length.
///
/// - Parameter kRange: A range of the number of elements to include in each
/// permutation. `kRange` can be any integer range expression, and is
/// clamped to the number of elements in this collection. Passing a range
/// covering sizes greater than the number of elements in this collection
/// results in an empty sequence.
///
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Permutations`
/// accesses the `count` of the base collection.
/// is the number of elements in the base collection, since `Permutations`
/// accesses the `count` of the base collection.
@inlinable
public func permutations<R: RangeExpression>(
ofCount kRange: R
@@ -346,11 +371,12 @@ extension Collection {
///
/// - Parameter k: The number of elements to include in each permutation.
/// If `k` is `nil`, the resulting sequence represents permutations of this
/// entire collection.
/// entire collection. If `k` is greater than the number of elements in
/// this collection, the resulting sequence is empty.
///
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Permutations`
/// accesses the `count` of the base collection.
/// is the number of elements in the base collection, since `Permutations`
/// accesses the `count` of the base collection.
@inlinable
public func permutations(ofCount k: Int? = nil) -> Permutations<Self> {
precondition(
@@ -359,3 +385,196 @@ extension Collection {
return Permutations(self, k: k)
}
}
//===----------------------------------------------------------------------===//
// uniquePermutations()
//===----------------------------------------------------------------------===//
/// A sequence of the unique permutations of the elements of a sequence or
/// collection.
///
/// To create a `UniquePermutations` instance, call one of the
/// `uniquePermutations` methods on your collection.
public struct UniquePermutations<Base: Collection> {
/// The base collection to iterate over for permutations.
public let base: Base
@usableFromInline
internal var indexes: [Base.Index]
@usableFromInline
internal let kRange: Range<Int>
}
extension UniquePermutations where Base.Element: Hashable {
@inlinable
internal static func _indexes(_ base: Base) -> [Base.Index] {
let firstIndexesAndCountsByElement = Dictionary(
base.indices.lazy.map { (base[$0], ($0, 1)) },
uniquingKeysWith: { indexAndCount, _ in (indexAndCount.0, indexAndCount.1 + 1) })
return firstIndexesAndCountsByElement
.values.sorted(by: { $0.0 < $1.0 })
.flatMap { index, count in repeatElement(index, count: count) }
}
@inlinable
internal init(_ elements: Base) {
self.indexes = Self._indexes(elements)
self.base = elements
self.kRange = self.indexes.count ..< (self.indexes.count + 1)
}
@inlinable
internal init<R: RangeExpression>(_ base: Base, _ range: R)
where R.Bound == Int
{
self.indexes = Self._indexes(base)
self.base = base
let upperBound = self.indexes.count + 1
self.kRange = range.relative(to: 0 ..< .max)
.clamped(to: 0 ..< upperBound)
}
}
extension UniquePermutations: Sequence {
/// The iterator for a `UniquePermutations` instance.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
@usableFromInline
internal var indexes: [Base.Index]
@usableFromInline
internal var lengths: Range<Int>
@usableFromInline
internal var initial = true
@inlinable
internal init(_ elements: Base, indexes: [Base.Index], lengths: Range<Int>) {
self.base = elements
self.indexes = indexes
self.lengths = lengths
}
@inlinable
public mutating func next() -> [Base.Element]? {
// In the end case, `lengths` is an empty range.
if lengths.isEmpty {
return nil
}
// The first iteration must produce the original sorted array, before any
// permutations. We skip the permutation the first time so that we can
// always mutate the array _before_ returning a slice, which avoids
// copying when possible.
if initial {
initial = false
return indexes[..<lengths.lowerBound].map { base[$0] }
}
if !indexes.nextPermutation(upperBound: lengths.lowerBound) {
lengths.removeFirst()
if lengths.isEmpty {
return nil
}
}
return indexes[..<lengths.lowerBound].map { base[$0] }
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(base, indexes: indexes, lengths: kRange)
}
}
extension UniquePermutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension Collection where Element: Hashable {
/// Returns a sequence of the unique permutations of this sequence of the
/// specified length.
///
/// Use this method to iterate over the unique permutations of a sequence
/// with repeating elements. This example prints every unique two-element
/// permutation of an array of numbers:
///
/// let numbers = [1, 1, 2]
/// for perm in numbers.uniquePermutations(ofCount: 2) {
/// print(perm)
/// }
/// // [1, 1]
/// // [1, 2]
/// // [2, 1]
///
/// By contrast, the `permutations(ofCount:)` method permutes a collection's
/// elements by position, and can include permutations with equal elements
/// in each permutation:
///
/// for perm in numbers.permutations(ofCount: 2)
/// print(perm)
/// }
/// // [1, 1]
/// // [1, 1]
/// // [1, 2]
/// // [1, 2]
/// // [2, 1]
/// // [2, 1]
///
/// The returned permutations are in lexicographically sorted order.
///
/// - Parameter k: The number of elements to include in each permutation.
/// If `k` is `nil`, the resulting sequence represents permutations of this
/// entire collection. If `k` is greater than the number of elements in
/// this collection, the resulting sequence is empty.
///
/// - Complexity: O(*n*), where *n* is the number of elements in this
/// collection.
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self> {
if let k = k {
return UniquePermutations(self, k ..< (k + 1))
} else {
return UniquePermutations(self)
}
}
/// Returns a collection of the unique permutations of this sequence with
/// lengths in the specified range.
///
/// Use this method to iterate over the unique permutations of a sequence
/// with repeating elements. This example prints every unique permutation
/// of an array of numbers with lengths through 2 elements:
///
/// let numbers = [1, 1, 2]
/// for perm in numbers.uniquePermutations(ofCount: ...2) {
/// print(perm)
/// }
/// // []
/// // [1]
/// // [2]
/// // [1, 1]
/// // [1, 2]
/// // [2, 1]
///
/// The returned permutations are in ascending order by length, and then
/// lexicographically within each group of the same length.
///
/// - Parameter kRange: A range of the number of elements to include in each
/// permutation. `kRange` can be any integer range expression, and is
/// clamped to the number of elements in this collection. Passing a range
/// covering sizes greater than the number of elements in this collection
/// results in an empty sequence.
///
/// - Complexity: O(*n*), where *n* is the number of elements in this
/// collection.
public func uniquePermutations<R: RangeExpression>(ofCount kRange: R) -> UniquePermutations<Self>
where R.Bound == Int
{
UniquePermutations(self, kRange)
}
}
+10 -8
View File
@@ -16,7 +16,7 @@ public struct Product2<Base1: Sequence, Base2: Collection> {
/// The inner sequence in the product.
public let base2: Base2
@usableFromInline
@inlinable
internal init(_ base1: Base1, _ base2: Base2) {
self.base1 = base1
self.base2 = base2
@@ -35,7 +35,7 @@ extension Product2: Sequence {
@usableFromInline
internal let base2: Base2
@usableFromInline
@inlinable
internal init(_ c: Product2) {
self.base2 = c.base2
self.i1 = c.base1.makeIterator()
@@ -90,7 +90,7 @@ extension Product2: Collection where Base1: Collection {
@usableFromInline
internal var i2: Base2.Index
@usableFromInline
@inlinable
internal init(i1: Base1.Index, i2: Base2.Index) {
self.i1 = i1
self.i2 = i2
@@ -128,7 +128,7 @@ extension Product2: Collection where Base1: Collection {
/// Forms an index from a pair of base indices, normalizing
/// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if
/// necessary.
@usableFromInline
@inlinable
internal func normalizeIndex(_ i1: Base1.Index, _ i2: Base2.Index) -> Index {
i2 == base2.endIndex
? Index(i1: base1.index(after: i1), i2: base2.startIndex)
@@ -195,6 +195,7 @@ extension Product2: Collection where Base1: Collection {
}
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i }
@@ -203,6 +204,7 @@ extension Product2: Collection where Base1: Collection {
: offsetBackward(i, by: -distance)
}
@inlinable
public func index(
_ i: Index,
offsetBy distance: Int,
@@ -219,21 +221,21 @@ extension Product2: Collection where Base1: Collection {
}
}
@usableFromInline
@inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") }
return index
}
@usableFromInline
@inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") }
return index
}
@usableFromInline
@inlinable
internal func offsetForward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
@@ -311,7 +313,7 @@ extension Product2: Collection where Base1: Collection {
.map { i2 in Index(i1: i1, i2: i2) }
}
@usableFromInline
@inlinable
internal func offsetBackward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
+643
View File
@@ -0,0 +1,643 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// MARK: - Exclusive Reductions
extension LazySequenceProtocol {
/// Returns a sequence containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as a sequence.
///
/// ```
/// let runningTotal = [1, 2, 3, 4].lazy.reductions(0, +)
/// print(Array(runningTotal))
///
/// // prints [0, 1, 3, 6, 10]
/// ```
///
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// - Returns: A sequence of the initial value followed by the reduced
/// elements.
///
/// - Complexity: O(1)
@inlinable
public func reductions<Result>(
_ initial: Result,
_ transform: @escaping (Result, Element) -> Result
) -> ExclusiveReductions<Result, Self> {
return reductions(into: initial) { result, element in
result = transform(result, element)
}
}
/// Returns a sequence containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as a sequence.
///
/// ```
/// let runningTotal = [1, 2, 3, 4].lazy.reductions(into: 0, +)
/// print(Array(runningTotal))
///
/// // prints [0, 1, 3, 6, 10]
/// ```
///
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// - Returns: A sequence of the initial value followed by the reduced
/// elements.
///
/// - Complexity: O(1)
@inlinable
public func reductions<Result>(
into initial: Result,
_ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductions<Result, Self> {
ExclusiveReductions(base: self, initial: initial, transform: transform)
}
}
extension Sequence {
/// Returns an array containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as a sequence.
///
/// ```
/// let runningTotal = [1, 2, 3, 4].reductions(0, +)
/// print(runningTotal)
///
/// // prints [0, 1, 3, 6, 10]
/// ```
///
/// When `reductions(_:_:)` is called, the following steps occur:
///
/// 1. The `initial` result is added to an array of results.
/// 2. The `transform` closure is called with the `initial` result and the
/// first element of the sequence, appending the result to the array.
/// 3. The closure is called again repeatedly with the updated accumulating
/// result and each element of the sequence, adding each result to the
/// array.
/// 4. When the sequence is exhausted, the results array is returned to the
/// caller.
///
/// If the sequence has no elements, `transform` is never executed and
/// an array containing only the `initial` result is returned.
///
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// - Returns: An array of the initial value followed by the reduced elements.
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable
public func reductions<Result>(
_ initial: Result,
_ transform: (Result, Element) throws -> Result
) rethrows -> [Result] {
return try reductions(into: initial) { result, element in
result = try transform(result, element)
}
}
/// Returns an array containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as a sequence.
///
/// ```
/// let runningTotal = [1, 2, 3, 4].reductions(into: 0, +)
/// print(runningTotal)
///
/// // prints [0, 1, 3, 6, 10]
/// ```
///
/// When `reductions(into:_:_)` is called, the following steps occur:
///
/// 1. The `initial` result is added to an array of results.
/// 2. The `transform` closure is called with the `initial` result and the
/// first element of the sequence, appending the result to the array.
/// 3. The closure is called again repeatedly with the updated accumulating
/// result and each element of the sequence, adding each result to the
/// array.
/// 4. When the sequence is exhausted, the results array is returned to the
/// caller.
///
/// If the sequence has no elements, `transform` is never executed and
/// an array containing only the `initial` result is returned.
///
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// - Returns: An array of the initial value followed by the reduced elements.
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable
public func reductions<Result>(
into initial: Result,
_ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result] {
var output = [Result]()
output.reserveCapacity(underestimatedCount + 1)
output.append(initial)
var initial = initial
for element in self {
try transform(&initial, element)
output.append(initial)
}
return output
}
}
/// A sequence of applying a transform to the element of a sequence and the
/// previously transformed result.
public struct ExclusiveReductions<Result, Base: Sequence> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let initial: Result
@usableFromInline
internal let transform: (inout Result, Base.Element) -> Void
@inlinable
internal init(
base: Base,
initial: Result,
transform: @escaping (inout Result, Base.Element) -> Void
) {
self.base = base
self.initial = initial
self.transform = transform
}
}
extension ExclusiveReductions: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator: Base.Iterator
@usableFromInline
internal var current: Result?
@usableFromInline
internal let transform: (inout Result, Base.Element) -> Void
@inlinable
internal init(
iterator: Base.Iterator,
current: Result? = nil,
transform: @escaping (inout Result, Base.Element) -> Void
) {
self.iterator = iterator
self.current = current
self.transform = transform
}
@inlinable
public mutating func next() -> Result? {
guard let result = current else { return nil }
current = iterator.next().map { element in
var result = result
transform(&result, element)
return result
}
return result
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(),
current: initial,
transform: transform)
}
}
extension ExclusiveReductions: Collection where Base: Collection {
public struct Index: Comparable {
@usableFromInline
internal let representation: ReductionsIndexRepresentation<Base.Index, Result>
@inlinable
internal init(
_ representation: ReductionsIndexRepresentation<Base.Index, Result>
) {
self.representation = representation
}
@inlinable
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.representation < rhs.representation
}
}
@inlinable
public var startIndex: Index { Index(.start) }
@inlinable
public var endIndex: Index { Index(.end) }
@inlinable
public subscript(position: Index) -> Result {
switch position.representation {
case .start: return initial
case .base(_, let result): return result
case .end: fatalError("Cannot get element of end index.")
}
}
@inlinable
public func index(after i: Index) -> Index {
func index(base index: Base.Index, previous: Result) -> Index {
guard index != base.endIndex else { return endIndex }
var previous = previous
transform(&previous, base[index])
return Index(.base(index: index, result: previous))
}
switch i.representation {
case .start:
return index(base: base.startIndex, previous: initial)
case let .base(i, result):
return index(base: base.index(after: i), previous: result)
case .end:
fatalError("Cannot get index after end index.")
}
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) {
case (.start, .start):
return 0
case let (.start, .base(index, _)):
return base.distance(from: base.startIndex, to: index) + 1
case (.start, .end):
return base.distance(from: base.startIndex, to: base.endIndex) + 1
case let (.base(index, _), .start):
return base.distance(from: index, to: base.startIndex) - 1
case let (.base(start, _), .base(end, _)):
return base.distance(from: start, to: end)
case let (.base(index, _), .end):
return base.distance(from: index, to: base.endIndex)
case (.end, .start):
return base.distance(from: base.endIndex, to: base.startIndex) - 1
case let (.end, .base(index, _)):
return base.distance(from: base.endIndex, to: index)
case (.end, .end):
return 0
}
}
}
extension ExclusiveReductions: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension ExclusiveReductions: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
// MARK: - Inclusive Reductions
extension LazySequenceProtocol {
/// Returns a sequence containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as a sequence.
///
/// ```
/// let runningTotal = [1, 2, 3, 4].lazy.reductions(+)
/// print(Array(runningTotal))
///
/// // prints [1, 3, 6, 10]
/// ```
///
/// - Parameters:
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// - Returns: A sequence of the reduced elements.
///
/// - Complexity: O(1)
@inlinable
public func reductions(
_ transform: @escaping (Element, Element) -> Element
) -> InclusiveReductions<Self> {
InclusiveReductions(base: self, transform: transform)
}
}
extension Sequence {
/// Returns an array containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as a sequence.
///
/// ```
/// let runningTotal = [1, 2, 3, 4].reductions(+)
/// print(runningTotal)
///
/// // prints [1, 3, 6, 10]
/// ```
///
/// When `reductions(_:)` is called, the following steps occur:
///
/// 1. The `transform` closure is called with the first and second elements
/// of the sequence, appending the result to an array of results.
/// 2. The closure is called again repeatedly with the updated accumulating
/// result and the next element of the sequence, adding each result to the
/// array.
/// 3. When the sequence is exhausted, the results array is returned to the
/// caller.
///
/// If the sequence has no elements, `transform` is never executed and
/// an empty array is returned.
///
/// If the sequence has one element, `transform` is never executed and
/// an array containing only that first element is returned.
///
/// - Parameters:
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// - Returns: An array of the reduced elements.
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable
public func reductions(
_ transform: (Element, Element) throws -> Element
) rethrows -> [Element] {
var iterator = makeIterator()
guard let initial = iterator.next() else { return [] }
return try IteratorSequence(iterator).reductions(initial, transform)
}
}
public struct InclusiveReductions<Base: Sequence> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let transform: (Base.Element, Base.Element) -> Base.Element
@inlinable
internal init(
base: Base,
transform: @escaping (Base.Element, Base.Element) -> Base.Element
) {
self.base = base
self.transform = transform
}
}
extension InclusiveReductions: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator: Base.Iterator
@usableFromInline
internal var element: Base.Element?
@usableFromInline
internal let transform: (Base.Element, Base.Element) -> Base.Element
@inlinable
internal init(
iterator: Base.Iterator,
element: Base.Element? = nil,
transform: @escaping (Base.Element, Base.Element) -> Base.Element
) {
self.iterator = iterator
self.element = element
self.transform = transform
}
@inlinable
public mutating func next() -> Base.Element? {
guard let previous = element else {
element = iterator.next()
return element
}
guard let next = iterator.next() else { return nil }
element = transform(previous, next)
return element
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(),
transform: transform)
}
}
extension InclusiveReductions: Collection where Base: Collection {
public struct Index: Comparable {
@usableFromInline
internal let representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
@inlinable
internal init(
_ representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
) {
self.representation = representation
}
@inlinable
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.representation < rhs.representation
}
}
@inlinable
public var startIndex: Index {
guard base.startIndex != base.endIndex else { return endIndex }
return Index(.start)
}
@inlinable
public var endIndex: Index { Index(.end) }
@inlinable
public subscript(position: Index) -> Base.Element {
switch position.representation {
case .start: return base[base.startIndex]
case .base(_, let result): return result
case .end: fatalError("Cannot get element of end index.")
}
}
@inlinable
public func index(after i: Index) -> Index {
func index(after i: Base.Index, previous: Base.Element) -> Index {
let index = base.index(after: i)
guard index != base.endIndex else { return endIndex }
return Index(.base(index: index, result: transform(previous, base[index])))
}
switch i.representation {
case .start:
return index(after: base.startIndex, previous: base[base.startIndex])
case let .base(i, element):
return index(after: i, previous: element)
case .end:
fatalError("Cannot get index after end index.")
}
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) {
case (.start, .start):
return 0
case let (.start, .base(index, _)):
return base.distance(from: base.startIndex, to: index)
case (.start, .end):
return base.distance(from: base.startIndex, to: base.endIndex)
case let (.base(index, _), .start):
return base.distance(from: index, to: base.startIndex)
case let (.base(start, _), .base(end, _)):
return base.distance(from: start, to: end)
case let (.base(index, _), .end):
return base.distance(from: index, to: base.endIndex)
case (.end, .start):
return base.distance(from: base.endIndex, to: base.startIndex)
case let (.end, .base(index, _)):
return base.distance(from: base.endIndex, to: index)
case (.end, .end):
return 0
}
}
}
extension InclusiveReductions: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension InclusiveReductions: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
// MARK: - ReductionsIndexRepresentation
@usableFromInline
enum ReductionsIndexRepresentation<BaseIndex: Comparable, Result> {
case start
case base(index: BaseIndex, result: Result)
case end
}
extension ReductionsIndexRepresentation: Equatable {
@inlinable
static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case (.start, .start): return true
case (.end, .end): return true
case let (.base(lhs, _), .base(rhs, _)): return lhs == rhs
default: return false
}
}
}
extension ReductionsIndexRepresentation: Comparable {
@inlinable
static func < (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case (_, .start): return false
case (.start, _): return true
case (.end, _): return false
case (_, .end): return true
case let (.base(lhs, _), .base(rhs, _)): return lhs < rhs
}
}
}
// MARK: - Scan
extension LazySequenceProtocol {
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
@inlinable
public func scan<Result>(
_ initial: Result,
_ transform: @escaping (Result, Element) -> Result
) -> ExclusiveReductions<Result, Self> {
reductions(initial, transform)
}
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
@inlinable
public func scan<Result>(
into initial: Result,
_ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductions<Result, Self> {
reductions(into: initial, transform)
}
}
extension Sequence {
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
@inlinable
public func scan<Result>(
_ initial: Result,
_ transform: (Result, Element) throws -> Result
) rethrows -> [Result] {
try reductions(initial, transform)
}
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
@inlinable
public func scan<Result>(
into initial: Result,
_ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result] {
try reductions(into: initial, transform)
}
}
extension LazySequenceProtocol {
@available(*, deprecated, message: "Use reductions(_:) instead.")
@inlinable
public func scan(
_ transform: @escaping (Element, Element) -> Element
) -> InclusiveReductions<Self> {
reductions(transform)
}
}
extension Sequence {
@available(*, deprecated, message: "Use reductions(_:) instead.")
@inlinable
public func scan(
_ transform: (Element, Element) throws -> Element
) rethrows -> [Element] {
try reductions(transform)
}
}
+2 -2
View File
@@ -29,7 +29,7 @@ extension MutableCollection where Self: BidirectionalCollection {
///
/// - Postcondition: For returned indices `(lower, upper)`:
/// `lower == limit || upper == limit`
@usableFromInline
@inlinable
@discardableResult
internal mutating func _reverse(
subrange: Range<Index>, until limit: Index
@@ -94,7 +94,7 @@ extension MutableCollection {
/// - distance(from: lhs.lowerBound, to: p) == distance(from:
/// rhs.lowerBound, to: q)
/// - p == lhs.upperBound || q == rhs.upperBound
@usableFromInline
@inlinable
internal mutating func _swapNonemptySubrangePrefixes(
_ lhs: Range<Index>, _ rhs: Range<Index>
) -> (Index, Index) {
+70 -25
View File
@@ -14,6 +14,25 @@
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a sequence stepping through the elements every `step` starting
/// at the first value. Any remainders of the stride will be trimmed.
///
/// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]
/// (0...10).striding(by: 3) // == [0, 3, 6, 9]
///
/// - Complexity: O(1). Access to successive values is O(k) where
/// _k_ is the striding `step`.
///
/// - Parameter step: The amount to step with each iteration.
/// - Returns: Returns a sequence for stepping through the
/// elements by the specified amount.
@inlinable
public func striding(by step: Int) -> StrideSequence<Self> {
StrideSequence(base: self, stride: step)
}
}
extension Collection {
/// Returns a sequence stepping through the elements every `step` starting
/// at the first value. Any remainders of the stride will be trimmed.
///
@@ -25,23 +44,24 @@ extension Sequence {
/// O(_k_), where _k_ is the striding `step`.
///
/// - Parameter step: The amount to step with each iteration.
/// - Returns: Returns a sequence or collection for stepping through the
/// - Returns: Returns a collection for stepping through the
/// elements by the specified amount.
@inlinable
public func striding(by step: Int) -> Stride<Self> {
Stride(base: self, stride: step)
public func striding(by step: Int) -> StrideCollection<Self> {
StrideCollection(base: self, stride: step)
}
}
/// A wrapper that strides over a base sequence or collection.
public struct Stride<Base: Sequence> {
/// A wrapper that strides over a base sequence.
public struct StrideSequence<Base: Sequence>: Sequence {
@usableFromInline
internal let base: Base
@usableFromInline
internal let stride: Int
@usableFromInline
@inlinable
internal init(base: Base, stride: Int) {
precondition(stride > 0, "striding must be greater than zero")
self.base = base
@@ -49,14 +69,8 @@ public struct Stride<Base: Sequence> {
}
}
extension Stride {
@inlinable
public func striding(by step: Int) -> Self {
Stride(base: base, stride: stride * step)
}
}
extension Stride: Sequence {
extension StrideSequence {
/// An iterator over a `Stride` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
@@ -68,7 +82,7 @@ extension Stride: Sequence {
@usableFromInline
internal var striding: Bool = false
@usableFromInline
@inlinable
internal init(iterator: Base.Iterator, stride: Int) {
self.iterator = iterator
self.stride = stride
@@ -88,12 +102,43 @@ extension Stride: Sequence {
}
@inlinable
public func makeIterator() -> Stride<Base>.Iterator {
public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(), stride: stride)
}
}
extension Stride: Collection where Base: Collection {
extension StrideSequence {
@inlinable
public func striding(by step: Int) -> Self {
Self(base: base, stride: stride * step)
}
}
/// A wrapper that strides over a base collection.
public struct StrideCollection<Base: Collection> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let stride: Int
@inlinable
internal init(base: Base, stride: Int) {
precondition(stride > 0, "striding must be greater than zero")
self.base = base
self.stride = stride
}
}
extension StrideCollection {
@inlinable
public func striding(by step: Int) -> Self {
Self(base: base, stride: stride * step)
}
}
extension StrideCollection: Collection {
/// A position in a `Stride` collection.
public struct Index: Comparable {
@usableFromInline
@@ -145,7 +190,7 @@ extension Stride: Collection where Base: Collection {
: offsetBackward(i, offsetBy: -n, limitedBy: limit)
}
@usableFromInline
@inlinable
internal func offsetForward(
_ i: Index,
offsetBy n: Int,
@@ -175,7 +220,7 @@ extension Stride: Collection where Base: Collection {
}
}
@usableFromInline
@inlinable
internal func offsetBackward(
_ i: Index,
offsetBy n: Int,
@@ -213,7 +258,7 @@ extension Stride: Collection where Base: Collection {
}
}
extension Stride: BidirectionalCollection
extension StrideCollection: BidirectionalCollection
where Base: RandomAccessCollection {
@inlinable
@@ -223,16 +268,16 @@ extension Stride: BidirectionalCollection
}
}
extension Stride: RandomAccessCollection where Base: RandomAccessCollection {}
extension StrideCollection: RandomAccessCollection where Base: RandomAccessCollection {}
extension Stride: Equatable where Base.Element: Equatable {
extension StrideCollection: Equatable where Base.Element: Equatable {
@inlinable
public static func == (lhs: Stride, rhs: Stride) -> Bool {
public static func == (lhs: StrideCollection, rhs: StrideCollection) -> Bool {
lhs.elementsEqual(rhs, by: ==)
}
}
extension Stride: Hashable where Base.Element: Hashable {
extension StrideCollection: Hashable where Base.Element: Hashable {
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(stride)
@@ -242,4 +287,4 @@ extension Stride: Hashable where Base.Element: Hashable {
}
}
extension Stride.Index: Hashable where Base.Index: Hashable {}
extension StrideCollection.Index: Hashable where Base.Index: Hashable {}
+57 -8
View File
@@ -27,13 +27,62 @@ extension BidirectionalCollection {
public func suffix(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
let start = startIndex
var result = endIndex
while result != start {
let previous = index(before: result)
guard try predicate(self[previous]) else { break }
result = previous
}
return self[result...]
try self[startOfSuffix(while: predicate)...]
}
}
//===----------------------------------------------------------------------===//
// endOfPrefix(while:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns the exclusive upper bound of the prefix of elements that satisfy
/// the predicate.
///
/// - Parameter predicate: A closure that takes an element of the collection
/// as its argument and returns `true` if the element is part of the prefix
/// or `false` if it is not. Once the predicate returns `false` it will not
/// be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
internal func endOfPrefix(
while predicate: (Element) throws -> Bool
) rethrows -> Index {
var index = startIndex
while try index != endIndex && predicate(self[index]) {
formIndex(after: &index)
}
return index
}
}
//===----------------------------------------------------------------------===//
// startOfSuffix(while:)
//===----------------------------------------------------------------------===//
extension BidirectionalCollection {
/// Returns the inclusive lower bound of the suffix of elements that satisfy
/// the predicate.
///
/// - Parameter predicate: A closure that takes an element of the collection
/// as its argument and returns `true` if the element is part of the suffix
/// or `false` if it is not. Once the predicate returns `false` it will not
/// be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
internal func startOfSuffix(
while predicate: (Element) throws -> Bool
) rethrows -> Index {
var index = endIndex
while index != startIndex {
let after = index
formIndex(before: &index)
if try !predicate(self[index]) {
return after
}
}
return index
}
}
+3 -15
View File
@@ -29,20 +29,8 @@ extension BidirectionalCollection {
public func trimming(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
// Consume elements from the front.
let sliceStart = try firstIndex { try predicate($0) == false } ?? endIndex
// sliceEnd is the index _after_ the last index to match the predicate.
var sliceEnd = endIndex
while sliceStart != sliceEnd {
let idxBeforeSliceEnd = index(before: sliceEnd)
guard try predicate(self[idxBeforeSliceEnd]) else {
return self[sliceStart..<sliceEnd]
}
sliceEnd = idxBeforeSliceEnd
}
// Trimmed everything.
return self[Range(uncheckedBounds: (sliceStart, sliceStart))]
let start = try endOfPrefix(while: predicate)
let end = try self[start...].startOfSuffix(while: predicate)
return self[start..<end]
}
}
+6 -6
View File
@@ -53,7 +53,7 @@ public struct Windows<Base: Collection> {
@usableFromInline
internal var firstUpperBound: Base.Index?
@usableFromInline
@inlinable
internal init(base: Base, size: Int) {
precondition(size > 0, "Windows size must be greater than zero")
self.base = base
@@ -72,7 +72,7 @@ extension Windows: Collection {
@usableFromInline
internal var upperBound: Base.Index
@usableFromInline
@inlinable
internal init(lowerBound: Base.Index, upperBound: Base.Index) {
self.lowerBound = lowerBound
self.upperBound = upperBound
@@ -150,21 +150,21 @@ extension Windows: Collection {
}
}
@usableFromInline
@inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") }
return index
}
@usableFromInline
@inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") }
return index
}
@usableFromInline
@inlinable
internal func offsetForward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
@@ -235,7 +235,7 @@ extension Windows: Collection {
}
}
@usableFromInline
@inlinable
internal func offsetBackward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
@@ -0,0 +1,23 @@
//===----------------------------------------------------------------------===//
//
// 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 FirstNonNilTests: XCTestCase {
func testFirstNonNil() {
XCTAssertNil([].firstNonNil { $0 })
XCTAssertNil(["A", "B", "C"].firstNonNil { Int($0) })
XCTAssertNil(["A", "B", "C"].firstNonNil { _ in nil })
XCTAssertEqual(["A", "B", "10"].firstNonNil { Int($0) }, 10)
XCTAssertEqual(["20", "B", "10"].firstNonNil { Int($0) }, 20)
}
}
@@ -0,0 +1,840 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import Algorithms
import XCTest
//===----------------------------------------------------------------------===//
// Tests for `LazySplitSequence` and `LazySplitCollection`
//===----------------------------------------------------------------------===//
final class LazySplitTests: XCTestCase {
func testEmpty() {
Validator(
subject: [],
separator: .element(0),
maxSplits: 1
).validate()
}
// The following test names indicate the sequence being split, using the
// notation
// S: Separator
// E: Element
//
// Values of `maxSplit` are interesting when they're less than the number of
// splits that would occur with the default. That varies depending on whether
// empty subsequences are omitted or included. `Validator` tests both the
// default and the value provided, but there are cases below where the
// provided `maxSplit` isn't less than the number of splits when empty
// subsequences are omitted.
//===--------------------------------------------------------------------===//
// Length 1
//===--------------------------------------------------------------------===//
func testE() {
Validator(subject: [1], separator: .element(0), maxSplits: 0).validate()
}
func testS() {
Validator(subject: [0], separator: .element(0), maxSplits: 0).validate()
}
//===--------------------------------------------------------------------===//
// Length 2
//===--------------------------------------------------------------------===//
func testEE() {
Validator(subject: [1, 1], separator: .element(0), maxSplits: 0).validate()
}
func testSS() {
Validator(subject: [0, 0], separator: .element(0), maxSplits: 1).validate()
}
func testES() {
Validator(subject: [1, 0], separator: .element(0), maxSplits: 0).validate()
}
func testSE() {
Validator(subject: [0, 1], separator: .element(0), maxSplits: 0).validate()
}
//===--------------------------------------------------------------------===//
// Length 3
//===--------------------------------------------------------------------===//
func testEEE() {
Validator(subject: [1, 1, 1], separator: .element(0), maxSplits: 0)
.validate()
}
func testSSS() {
Validator(subject: [0, 0, 0], separator: .element(0), maxSplits: 1)
.validate()
}
func testAllEES() {
let permutations = [[1, 1, 0], [1, 0, 1], [0, 1, 1]]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 0)
.validate()
}
}
func testAllESS() {
let permutations = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
}
}
//===--------------------------------------------------------------------===//
// Length 4 with less than two separators.
//===--------------------------------------------------------------------===//
func testEEEE() {
Validator(subject: [1, 1, 1, 1], separator: .element(0), maxSplits: 0)
.validate()
}
func testAllEEES() {
let permutations = [
[1, 1, 1, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1]
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 0)
.validate()
}
}
//===--------------------------------------------------------------------===//
// Unique permutations of sequences with at least two separators, so there can
// be multiple adjacent separators at the beginning, middle, or end.
//===--------------------------------------------------------------------===//
// All separators.
func testSSSS() {
Validator(subject: [0, 0, 0, 0], separator: .element(0), maxSplits: 1)
.validate()
}
// Equal numbers of elements and separators.
func testAllEESS() {
let permutations = [
[1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1],
[0, 1, 1, 0], [0, 1, 0, 1], [0, 0, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
}
}
// More separators than elements.
func testAllEESSS() {
let permutations = [
[1, 1, 0, 0, 0], [1, 0, 1, 0, 0], [1, 0, 0, 1, 0], [1, 0, 0, 0, 1],
[0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 1], [0, 0, 1, 1, 0],
[0, 0, 1, 0, 1], [0, 0, 0, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
}
}
// More elements than separators.
func testAllEEESS() {
let permutations = [
[1, 1, 1, 0, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 1], [1, 0, 1, 1, 0],
[1, 0, 1, 0, 1], [1, 0, 0, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1],
[0, 1, 0, 1, 1], [0, 0, 1, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
}
}
//===--------------------------------------------------------------------===//
// Unique permutations of sequences with at least three separators.
//===--------------------------------------------------------------------===//
func testAllESSS() {
let permutations = [
[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
}
}
func testAllEEEESSS() {
let permutations = [
[1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0], [1, 1, 1, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 0, 1], [1, 1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1, 0],
[1, 1, 0, 1, 0, 0, 1], [1, 1, 0, 0, 1, 1, 0], [1, 1, 0, 0, 1, 0, 1],
[1, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0],
[1, 0, 1, 1, 0, 0, 1], [1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 0, 1, 1], [1, 0, 0, 1, 1, 1, 0], [1, 0, 0, 1, 1, 0, 1],
[1, 0, 0, 1, 0, 1, 1], [1, 0, 0, 0, 1, 1, 1], [0, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0],
[0, 1, 1, 0, 1, 0, 1], [0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 1, 1, 0],
[0, 1, 0, 1, 1, 0, 1], [0, 1, 0, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 1], [0, 0, 1, 1, 0, 1, 1],
[0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
}
}
//===--------------------------------------------------------------------===//
// Unique permutations of sequences with at least four separators, so there
// can be two runs of multiple adjacent separators: beginning and end,
// beginning and middle, or end and middle.
//===--------------------------------------------------------------------===//
// Equal numbers of separators and elements.
func testAllEEEESSSS() {
let permutations = [
[1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0, 0],
[1, 1, 1, 0, 0, 1, 0, 0], [1, 1, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 0, 1, 1, 0, 0, 0],
[1, 1, 0, 1, 0, 1, 0, 0], [1, 1, 0, 1, 0, 0, 1, 0],
[1, 1, 0, 1, 0, 0, 0, 1], [1, 1, 0, 0, 1, 1, 0, 0],
[1, 1, 0, 0, 1, 0, 1, 0], [1, 1, 0, 0, 1, 0, 0, 1],
[1, 1, 0, 0, 0, 1, 1, 0], [1, 1, 0, 0, 0, 1, 0, 1],
[1, 1, 0, 0, 0, 0, 1, 1], [1, 0, 1, 1, 1, 0, 0, 0],
[1, 0, 1, 1, 0, 1, 0, 0], [1, 0, 1, 1, 0, 0, 1, 0],
[1, 0, 1, 1, 0, 0, 0, 1], [1, 0, 1, 0, 1, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 1, 0], [1, 0, 1, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 0, 1],
[1, 0, 1, 0, 0, 0, 1, 1], [1, 0, 0, 1, 1, 1, 0, 0],
[1, 0, 0, 1, 1, 0, 1, 0], [1, 0, 0, 1, 1, 0, 0, 1],
[1, 0, 0, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 0, 1, 0, 0, 1, 1], [1, 0, 0, 0, 1, 1, 1, 0],
[1, 0, 0, 0, 1, 1, 0, 1], [1, 0, 0, 0, 1, 0, 1, 1],
[1, 0, 0, 0, 0, 1, 1, 1], [0, 1, 1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 1, 0, 0], [0, 1, 1, 1, 0, 0, 1, 0],
[0, 1, 1, 1, 0, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 1, 0, 1, 0], [0, 1, 1, 0, 1, 0, 0, 1],
[0, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 1],
[0, 1, 1, 0, 0, 0, 1, 1], [0, 1, 0, 1, 1, 1, 0, 0],
[0, 1, 0, 1, 1, 0, 1, 0], [0, 1, 0, 1, 1, 0, 0, 1],
[0, 1, 0, 1, 0, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 0, 1, 1], [0, 1, 0, 0, 1, 1, 1, 0],
[0, 1, 0, 0, 1, 1, 0, 1], [0, 1, 0, 0, 1, 0, 1, 1],
[0, 1, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 0, 1, 0, 1],
[0, 0, 1, 1, 0, 0, 1, 1], [0, 0, 1, 0, 1, 1, 1, 0],
[0, 0, 1, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1, 0, 1, 1],
[0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1, 0],
[0, 0, 0, 1, 1, 1, 0, 1], [0, 0, 0, 1, 1, 0, 1, 1],
[0, 0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
}
}
// More separators than elements.
func testAllEEESSSS() {
let permutations = [
[1, 1, 1, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0], [1, 1, 0, 0, 1, 0, 0],
[1, 1, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 0, 0],
[1, 0, 1, 0, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0], [1, 0, 1, 0, 0, 0, 1],
[1, 0, 0, 1, 1, 0, 0], [1, 0, 0, 1, 0, 1, 0], [1, 0, 0, 1, 0, 0, 1],
[1, 0, 0, 0, 1, 1, 0], [1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 1, 1],
[0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0], [0, 1, 1, 0, 0, 1, 0],
[0, 1, 1, 0, 0, 0, 1], [0, 1, 0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 0, 1], [0, 1, 0, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0, 1],
[0, 1, 0, 0, 0, 1, 1], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1, 0],
[0, 0, 1, 1, 0, 0, 1], [0, 0, 1, 0, 1, 1, 0], [0, 0, 1, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 1, 1, 0, 1],
[0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 1, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
}
}
// More elements than separators.
func testAllEEEEESSSS() {
let permutations = [
[1, 1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 0, 1, 0, 0, 0],
[1, 1, 1, 1, 0, 0, 1, 0, 0], [1, 1, 1, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 1, 0, 1, 1, 0, 0, 0],
[1, 1, 1, 0, 1, 0, 1, 0, 0], [1, 1, 1, 0, 1, 0, 0, 1, 0],
[1, 1, 1, 0, 1, 0, 0, 0, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 1, 0, 1, 0], [1, 1, 1, 0, 0, 1, 0, 0, 1],
[1, 1, 1, 0, 0, 0, 1, 1, 0], [1, 1, 1, 0, 0, 0, 1, 0, 1],
[1, 1, 1, 0, 0, 0, 0, 1, 1], [1, 1, 0, 1, 1, 1, 0, 0, 0],
[1, 1, 0, 1, 1, 0, 1, 0, 0], [1, 1, 0, 1, 1, 0, 0, 1, 0],
[1, 1, 0, 1, 1, 0, 0, 0, 1], [1, 1, 0, 1, 0, 1, 1, 0, 0],
[1, 1, 0, 1, 0, 1, 0, 1, 0], [1, 1, 0, 1, 0, 1, 0, 0, 1],
[1, 1, 0, 1, 0, 0, 1, 1, 0], [1, 1, 0, 1, 0, 0, 1, 0, 1],
[1, 1, 0, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 1, 1, 1, 0, 0],
[1, 1, 0, 0, 1, 1, 0, 1, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1],
[1, 1, 0, 0, 1, 0, 1, 1, 0], [1, 1, 0, 0, 1, 0, 1, 0, 1],
[1, 1, 0, 0, 1, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 1, 1, 0, 1], [1, 1, 0, 0, 0, 1, 0, 1, 1],
[1, 1, 0, 0, 0, 0, 1, 1, 1], [1, 0, 1, 1, 1, 1, 0, 0, 0],
[1, 0, 1, 1, 1, 0, 1, 0, 0], [1, 0, 1, 1, 1, 0, 0, 1, 0],
[1, 0, 1, 1, 1, 0, 0, 0, 1], [1, 0, 1, 1, 0, 1, 1, 0, 0],
[1, 0, 1, 1, 0, 1, 0, 1, 0], [1, 0, 1, 1, 0, 1, 0, 0, 1],
[1, 0, 1, 1, 0, 0, 1, 1, 0], [1, 0, 1, 1, 0, 0, 1, 0, 1],
[1, 0, 1, 1, 0, 0, 0, 1, 1], [1, 0, 1, 0, 1, 1, 1, 0, 0],
[1, 0, 1, 0, 1, 1, 0, 1, 0], [1, 0, 1, 0, 1, 1, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 1, 1], [1, 0, 1, 0, 0, 1, 1, 1, 0],
[1, 0, 1, 0, 0, 1, 1, 0, 1], [1, 0, 1, 0, 0, 1, 0, 1, 1],
[1, 0, 1, 0, 0, 0, 1, 1, 1], [1, 0, 0, 1, 1, 1, 1, 0, 0],
[1, 0, 0, 1, 1, 1, 0, 1, 0], [1, 0, 0, 1, 1, 1, 0, 0, 1],
[1, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 0, 1, 1, 0, 1, 0, 1],
[1, 0, 0, 1, 1, 0, 0, 1, 1], [1, 0, 0, 1, 0, 1, 1, 1, 0],
[1, 0, 0, 1, 0, 1, 1, 0, 1], [1, 0, 0, 1, 0, 1, 0, 1, 1],
[1, 0, 0, 1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 1, 1, 1, 1, 0],
[1, 0, 0, 0, 1, 1, 1, 0, 1], [1, 0, 0, 0, 1, 1, 0, 1, 1],
[1, 0, 0, 0, 1, 0, 1, 1, 1], [1, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 0, 1, 0, 0],
[0, 1, 1, 1, 1, 0, 0, 1, 0], [0, 1, 1, 1, 1, 0, 0, 0, 1],
[0, 1, 1, 1, 0, 1, 1, 0, 0], [0, 1, 1, 1, 0, 1, 0, 1, 0],
[0, 1, 1, 1, 0, 1, 0, 0, 1], [0, 1, 1, 1, 0, 0, 1, 1, 0],
[0, 1, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 1, 0, 0, 0, 1, 1],
[0, 1, 1, 0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0, 1, 0],
[0, 1, 1, 0, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 0, 1, 1, 0],
[0, 1, 1, 0, 1, 0, 1, 0, 1], [0, 1, 1, 0, 1, 0, 0, 1, 1],
[0, 1, 1, 0, 0, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0, 1],
[0, 1, 1, 0, 0, 1, 0, 1, 1], [0, 1, 1, 0, 0, 0, 1, 1, 1],
[0, 1, 0, 1, 1, 1, 1, 0, 0], [0, 1, 0, 1, 1, 1, 0, 1, 0],
[0, 1, 0, 1, 1, 1, 0, 0, 1], [0, 1, 0, 1, 1, 0, 1, 1, 0],
[0, 1, 0, 1, 1, 0, 1, 0, 1], [0, 1, 0, 1, 1, 0, 0, 1, 1],
[0, 1, 0, 1, 0, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 1, 0, 1],
[0, 1, 0, 1, 0, 1, 0, 1, 1], [0, 1, 0, 1, 0, 0, 1, 1, 1],
[0, 1, 0, 0, 1, 1, 1, 1, 0], [0, 1, 0, 0, 1, 1, 1, 0, 1],
[0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 1, 0, 0, 1, 0, 1, 1, 1],
[0, 1, 0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 1, 0, 1, 0, 1],
[0, 0, 1, 1, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 1, 1, 1, 0],
[0, 0, 1, 1, 0, 1, 1, 0, 1], [0, 0, 1, 1, 0, 1, 0, 1, 1],
[0, 0, 1, 1, 0, 0, 1, 1, 1], [0, 0, 1, 0, 1, 1, 1, 1, 0],
[0, 0, 1, 0, 1, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1, 0, 1, 1],
[0, 0, 1, 0, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 0, 1],
[0, 0, 0, 1, 1, 1, 0, 1, 1], [0, 0, 0, 1, 1, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
}
}
//===--------------------------------------------------------------------===//
// Permutations of a sequence with six separators, so there can be multiple
// adjacent separators at the beginning, middle, _and_ end.
//===--------------------------------------------------------------------===//
// More separators than elements.
func testAllEEESSSSSS() {
let permutations = [
[1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 0, 0, 1, 0],
[1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 1, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 0, 0, 1, 0],
[1, 0, 1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0, 0, 0],
[1, 0, 0, 1, 0, 1, 0, 0, 0], [1, 0, 0, 1, 0, 0, 1, 0, 0],
[1, 0, 0, 1, 0, 0, 0, 1, 0], [1, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 0, 1, 0, 0],
[1, 0, 0, 0, 1, 0, 0, 1, 0], [1, 0, 0, 0, 1, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1, 1, 0, 0], [1, 0, 0, 0, 0, 1, 0, 1, 0],
[1, 0, 0, 0, 0, 1, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 1, 0],
[1, 0, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1, 1],
[0, 1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 1, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 0, 1, 0], [0, 1, 1, 0, 0, 0, 0, 0, 1],
[0, 1, 0, 1, 1, 0, 0, 0, 0], [0, 1, 0, 1, 0, 1, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 1, 0, 0, 0, 0, 1], [0, 1, 0, 0, 1, 1, 0, 0, 0],
[0, 1, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0, 0, 1, 0],
[0, 1, 0, 0, 1, 0, 0, 0, 1], [0, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 0, 0, 0, 1, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0, 0, 1],
[0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0, 1],
[0, 1, 0, 0, 0, 0, 0, 1, 1], [0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 1, 0, 0, 0], [0, 0, 1, 1, 0, 0, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 0, 1, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 1, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 1, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 1, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 0, 1, 1, 0],
[0, 0, 1, 0, 0, 0, 1, 0, 1], [0, 0, 1, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 1, 0, 0, 1, 0], [0, 0, 0, 1, 1, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 1, 1, 0, 0], [0, 0, 0, 1, 0, 1, 0, 1, 0],
[0, 0, 0, 1, 0, 1, 0, 0, 1], [0, 0, 0, 1, 0, 0, 1, 1, 0],
[0, 0, 0, 1, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 1, 1, 0, 1],
[0, 0, 0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
}
}
//===--------------------------------------------------------------------===//
// Specific examples of interest.
//===--------------------------------------------------------------------===//
// The motivating example from
// https://github.com/apple/swift-algorithms/issues/59.
func testSplitFilenameComponents() {
Validator(
subject: "archive.tar.gz",
separator: .element("."),
maxSplits: 1
).validate()
}
// Examples from documentation.
func testSequenceDocExamples() {
// Closure version.
let numbers = stride(from: 1, through: 16, by: 1)
Validator(
subject: Array(numbers),
separator: .closure({ $0 % 3 == 0 || $0 % 5 == 0 }),
maxSplits: 1
).validate()
// Equatable element version.
let numbers2 = [1, 2, 0, 3, 4, 0, 0, 5]
Validator(subject: numbers2, separator: .element(0), maxSplits: 1)
.validate()
}
func testCollectionDocExample() {
let line = "BLANCHE: I don't want realism. I want magic!"
Validator(subject: line, separator: .element("."), maxSplits: 1).validate()
}
// Patterns tested in a previous version of this file which aren't tested
// above. Preserved to ensure we're not losing any test coverage.
func testVintagePatterns() {
let pattern1 = [1, 2, 42, 3, 4, 42, 5, 6, 42, 7]
Validator(subject: pattern1, separator: .element(42), maxSplits: 2)
.validate()
Validator(subject: pattern1, separator: .element(42), maxSplits: 0)
.validate()
let pattern2 = [42, 1, 2, 42, 3, 4, 42, 5, 6, 42, 7]
Validator(subject: pattern2, separator: .element(42), maxSplits: 2)
.validate()
let pattern3 = [1, 2, 42, 3, 4, 42, 42, 5, 6, 42, 7]
Validator(subject: pattern3, separator: .element(42), maxSplits: 2)
.validate()
let pattern4 = [1, 2, 42, 3, 4, 42, 42, 5, 6, 42, 7, 42, 42, 42]
Validator(subject: pattern4, separator: .element(42), maxSplits: 1)
.validate()
}
//===--------------------------------------------------------------------===//
// Protocol conformance.
//===--------------------------------------------------------------------===//
func testLaziness() {
let splitSequence = AnySequence([1, 2, 42, 3]).lazy.split(separator: 42)
XCTAssertLazySequence(splitSequence)
let splitCollection = "foo.bar".lazy.split(separator: ".")
XCTAssertLazySequence(splitCollection)
XCTAssertLazyCollection(splitCollection)
}
// TODO: Need a version of `validateIndexTraversals` that doesn't require
// `BidirectionalCollection` conformance.
//===--------------------------------------------------------------------===//
// Validator
//===--------------------------------------------------------------------===//
/// Splits a collection as both a lazy sequence and a lazy collection, using
/// the provided separator, and compares the results to those of the Standard
/// Library's eager splits, which are assumed to be correct.
///
/// Tests all combinations of default and provided `maxSplit` arguments and
/// default (true) and explicit false for `omittingEmptySubsequences`.
///
/// - Parameters:
/// - subject: The collection whose splits will be validated.
/// - separator: The element of the collection--or a predicate function to
/// determine the element--on which to split.
/// - maxSplits: The value to pass for `maxSplits` during validation. The
/// default value is also validated.
fileprivate struct Validator<C: Collection>
where C.Element: Equatable, C.SubSequence: Equatable {
enum Separator {
case element(C.Element)
case closure((C.Element) -> Bool)
}
let subject: C
let separator: Separator
let maxSplits: Int
func validate() {
_validateAsSequence(AnySequence(subject))
_validateAsCollection(subject)
}
private enum MaxSplits: CustomStringConvertible {
case provided(Int)
case defaultValue
var description: String {
switch self {
case .provided(let value):
return "maxSplits: \(value)"
case .defaultValue:
return "maxSplits: default"
}
}
}
private enum OmittingEmptySubsequences: CustomStringConvertible {
case provided(Bool)
case defaultValue
var description: String {
switch self {
case .provided(let value):
return "omittingEmptySubsequences: \(value)"
case .defaultValue:
return "omittingEmptySubsequences: default"
}
}
}
private func failureMessage<L: LazySequenceProtocol, S: Sequence>(
actual: L,
expected: S,
maxSplits: MaxSplits,
omittingEmptySubsequences: OmittingEmptySubsequences
) -> String {
"for \(Array(subject).debugDescription), \(maxSplits), \(omittingEmptySubsequences): \(Array(actual).debugDescription) != \(Array(expected).debugDescription)"
}
private func _validateAsSequence<T: Sequence>(_ s: T)
where T.Element == C.Element {
// Default max splits, omitting empty sequences
switch separator {
case let .element(element):
let expected = s.split(separator: element).map { Array($0) }
let actual = s.lazy.split(separator: element)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue)
)
case let .closure(closure):
let expected = s.split(whereSeparator: closure).map { Array($0) }
let actual = s.lazy.split(whereSeparator: closure)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue)
)
}
// Provided max splits, omitting empty sequences
switch separator {
case let .element(element):
let expected = s.split(
separator: element,
maxSplits: maxSplits
).map { Array($0) }
let actual = s.lazy.split(
separator: element,
maxSplits: maxSplits
)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue)
)
case let .closure(closure):
let expected = s.split(
maxSplits: maxSplits,
whereSeparator: closure
).map { Array($0) }
let actual = s.lazy.split(
maxSplits: maxSplits,
whereSeparator: closure
)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue)
)
}
// Default max splits, including empty sequences
switch separator {
case let .element(element):
let expected = s.split(
separator: element,
omittingEmptySubsequences: false
).map { Array($0) }
let actual = s.lazy.split(
separator: element,
omittingEmptySubsequences: false
)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false))
)
case let .closure(closure):
let expected = s.split(
omittingEmptySubsequences: false,
whereSeparator: closure
).map { Array($0) }
let actual = s.lazy.split(
omittingEmptySubsequences: false,
whereSeparator: closure
)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false))
)
}
// Provided max splits, including empty sequences
switch separator {
case let .element(element):
let expected = s.split(
separator: element,
maxSplits: maxSplits,
omittingEmptySubsequences: false
).map { Array($0) }
let actual = s.lazy.split(
separator: element,
maxSplits: maxSplits,
omittingEmptySubsequences: false
)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false))
)
case let .closure(closure):
let expected = s.split(
maxSplits: maxSplits,
omittingEmptySubsequences: false,
whereSeparator: closure
).map { Array($0) }
let actual = s.lazy.split(
maxSplits: maxSplits,
omittingEmptySubsequences: false,
whereSeparator: closure
)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false))
)
}
}
private func _validateAsCollection(_ c: C) {
// Default max splits, omitting empty sequences
switch separator {
case let .element(element):
let expected = c.split(separator: element)
let actual = c.lazy.split(separator: element)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue)
)
case let .closure(closure):
let expected = c.split(whereSeparator: closure)
let actual = c.lazy.split(whereSeparator: closure)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue)
)
}
// Provided max splits, omitting empty sequences
switch separator {
case let .element(element):
let expected = c.split(
separator: element,
maxSplits: maxSplits
)
let actual = c.lazy.split(
separator: element,
maxSplits: maxSplits
)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue)
)
case let .closure(closure):
let expected = c.split(
maxSplits: maxSplits,
whereSeparator: closure
)
let actual = c.lazy.split(
maxSplits: maxSplits,
whereSeparator: closure
)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue)
)
}
// Default max splits, including empty sequences
switch separator {
case let .element(element):
let expected = c.split(
separator: element,
omittingEmptySubsequences: false
)
let actual = c.lazy.split(
separator: element,
omittingEmptySubsequences: false
)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false))
)
case let .closure(closure):
let expected = c.split(
omittingEmptySubsequences: false,
whereSeparator: closure
)
let actual = c.lazy.split(
omittingEmptySubsequences: false,
whereSeparator: closure
)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false))
)
}
// Provided max splits, including empty sequences
switch separator {
case let .element(element):
let expected = c.split(
separator: element,
maxSplits: maxSplits,
omittingEmptySubsequences: false
)
let actual = c.lazy.split(
separator: element,
maxSplits: maxSplits,
omittingEmptySubsequences: false
)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false))
)
case let .closure(closure):
let expected = c.split(
maxSplits: maxSplits,
omittingEmptySubsequences: false,
whereSeparator: closure
)
let actual = c.lazy.split(
maxSplits: maxSplits,
omittingEmptySubsequences: false,
whereSeparator: closure
)
XCTAssertEqualSequences(
expected,
actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false))
)
}
}
}
}
@@ -64,14 +64,17 @@ 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))
for i in 0..<length {
for j in 0...i {
var b = a
let partitionRange = j..<i
let condition = { $0 < i - 1 }
let p = b.stablePartition(subrange: partitionRange, by: condition)
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
XCTAssertEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
}
}
}
}
@@ -88,4 +91,46 @@ final class PartitionTests: XCTestCase {
}
}
}
func testPartitionWithSubrangeBidirectionalCollection() {
for length in 10...20 {
let a = Array(0..<length)
for i in 0..<length {
for j in 0...i {
var b = a
let partitionRange = j..<i
let condition = { $0 < i - 1 }
let p = b.partition(subrange: partitionRange, by: condition)
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
}
}
}
}
func testPartitionWithSubrangeMutableCollection() {
for length in 10...20 {
let a = Array(0..<length)
for i in 0..<length {
for j in 0...i {
var b = a.eraseToAnyMutableCollection()
var bdc = a
let partitionRange = j..<i
let condition = { $0 < i - 1 }
let p = b.partition(subrange: partitionRange, by: condition)
let bdcp = bdc.partition(subrange: partitionRange, by: condition)
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
// Must produce the same result as the `BidirectionalCollection` specialized overload.
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], bdc[partitionRange.lowerBound..<bdcp])
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], bdc[bdcp..<partitionRange.upperBound])
}
}
}
}
}
@@ -0,0 +1,81 @@
//===----------------------------------------------------------------------===//
//
// 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 ReductionsTests: XCTestCase {
struct TestError: Error {}
// MARK: - Exclusive Reductions
func testExclusiveLazy() {
XCTAssertEqualSequences((1...).prefix(4).lazy.reductions(0, +), [0, 1, 3, 6, 10])
XCTAssertEqualSequences((1...).prefix(1).lazy.reductions(0, +), [0, 1])
XCTAssertEqualSequences((1...).prefix(0).lazy.reductions(0, +), [0])
XCTAssertEqualCollections([1, 2, 3, 4].lazy.reductions(0, +), [0, 1, 3, 6, 10])
XCTAssertEqualCollections([1].lazy.reductions(0, +), [0, 1])
XCTAssertEqualCollections(EmptyCollection<Int>().lazy.reductions(0, +), [0])
XCTAssertEqual([1, 2, 3, 4].lazy.reductions(into: 0, +=), [0, 1, 3, 6, 10])
XCTAssertEqual([1].lazy.reductions(into: 0, +=), [0, 1])
XCTAssertEqual(EmptyCollection<Int>().lazy.reductions(into: 0, +=), [0])
XCTAssertLazySequence((1...).prefix(1).lazy.reductions(0, +))
XCTAssertLazySequence([1].lazy.reductions(0, +))
XCTAssertLazyCollection([1].lazy.reductions(0, +))
}
func testExclusiveEager() {
XCTAssertEqual([1, 2, 3, 4].reductions(0, +), [0, 1, 3, 6, 10])
XCTAssertEqual([1].reductions(0, +), [0, 1])
XCTAssertEqual(EmptyCollection<Int>().reductions(0, +), [0])
XCTAssertEqual([1, 2, 3, 4].reductions(into: 0, +=), [0, 1, 3, 6, 10])
XCTAssertEqual([1].reductions(into: 0, +=), [0, 1])
XCTAssertEqual(EmptyCollection<Int>().reductions(into: 0, +=), [0])
XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() })
XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() })
}
// MARK: - Inclusive Reductions
func testInclusiveLazy() {
XCTAssertEqualSequences((1...).prefix(4).lazy.reductions(+), [1, 3, 6, 10])
XCTAssertEqualSequences((1...).prefix(1).lazy.reductions(+), [1])
XCTAssertEqualSequences((1...).prefix(0).lazy.reductions(+), [])
XCTAssertEqualCollections([1, 2, 3, 4].lazy.reductions(+), [1, 3, 6, 10])
XCTAssertEqualCollections([1].lazy.reductions(+), [1])
XCTAssertEqualCollections(EmptyCollection<Int>().lazy.reductions(+), [])
XCTAssertLazySequence((1...).prefix(1).lazy.reductions(+))
XCTAssertLazySequence([1].lazy.reductions(+))
XCTAssertLazyCollection([1].lazy.reductions(+))
}
func testInclusiveEager() {
XCTAssertEqual([1, 2, 3, 4].reductions(+), [1, 3, 6, 10])
XCTAssertEqual([1].reductions(+), [1])
XCTAssertEqual(EmptyCollection<Int>().reductions(+), [])
XCTAssertNoThrow(try [].reductions { _, _ in throw TestError() })
XCTAssertNoThrow(try [1].reductions { _, _ in throw TestError() })
XCTAssertThrowsError(try [1, 1].reductions { _, _ in throw TestError() })
}
}
+1 -1
View File
@@ -68,7 +68,7 @@ final class StridingTests: XCTestCase {
let a = (0...10)
XCTAssertEqualSequences(a.striding(by: 6), a.striding(by: 2).striding(by: 3))
XCTAssertTrue(a.striding(by: 6) == a.striding(by: 2).striding(by: 3))
XCTAssert(type(of: a.striding(by: 2).striding(by: 3)) == Stride<ClosedRange<Int>>.self)
XCTAssert(type(of: a.striding(by: 2).striding(by: 3)) == StrideCollection<ClosedRange<Int>>.self)
}
func testEquality() {
+25 -1
View File
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
import XCTest
import Algorithms
@testable import Algorithms
final class SuffixTests: XCTestCase {
func testSuffix() {
@@ -23,4 +23,28 @@ final class SuffixTests: XCTestCase {
let empty: [Int] = []
XCTAssertEqualSequences(empty.suffix(while: { $0 > 10 }), [])
}
func testEndOfPrefix() {
let array = Array(0..<10)
XCTAssertEqual(array.endOfPrefix(while: { $0 < 3 }), 3)
XCTAssertEqual(array.endOfPrefix(while: { _ in false }), array.startIndex)
XCTAssertEqual(array.endOfPrefix(while: { _ in true }), array.endIndex)
let empty = [Int]()
XCTAssertEqual(empty.endOfPrefix(while: { $0 < 3 }), 0)
XCTAssertEqual(empty.endOfPrefix(while: { _ in false }), empty.startIndex)
XCTAssertEqual(empty.endOfPrefix(while: { _ in true }), empty.endIndex)
}
func testStartOfSuffix() {
let array = Array(0..<10)
XCTAssertEqual(array.startOfSuffix(while: { $0 >= 3 }), 3)
XCTAssertEqual(array.startOfSuffix(while: { _ in false }), array.endIndex)
XCTAssertEqual(array.startOfSuffix(while: { _ in true }), array.startIndex)
let empty = [Int]()
XCTAssertEqual(empty.startOfSuffix(while: { $0 < 3 }), 0)
XCTAssertEqual(empty.startOfSuffix(while: { _ in false }), empty.endIndex)
XCTAssertEqual(empty.startOfSuffix(while: { _ in true }), empty.startIndex)
}
}
+97 -2
View File
@@ -46,13 +46,69 @@ struct SplitMix64: RandomNumberGenerator {
}
}
// An eraser helper to any mutable collection
struct AnyMutableCollection<Base> where Base: MutableCollection {
var base: Base
}
extension AnyMutableCollection: MutableCollection {
typealias Index = Base.Index
typealias Element = Base.Element
var startIndex: Base.Index { base.startIndex }
var endIndex: Base.Index { base.endIndex }
func index(after i: Index) -> Index {
return base.index(after: i)
}
subscript(position: Base.Index) -> Base.Element {
_read { yield base[position] }
set { base[position] = newValue }
}
}
extension MutableCollection {
func eraseToAnyMutableCollection() -> AnyMutableCollection<Self> {
AnyMutableCollection(base: self)
}
}
func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1,
_ expression2: @autoclosure () throws -> S2,
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
try XCTAssert(expression1().elementsEqual(expression2()), message(), file: file, line: line)
try XCTAssertEqualSequences(expression1(), expression2(), by: ==,
message(), file: file, line: line)
}
// Two sequences contains exactly the same element but not necessarily in the same order.
func XCTAssertUnorderedEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1,
_ expression2: @autoclosure () throws -> S2,
file: StaticString = #file, line: UInt = #line
) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
var s1 = Array(try expression1())
var missing: [S1.Element] = []
for elt in try expression2() {
guard let idx = s1.firstIndex(of: elt) else {
missing.append(elt)
continue
}
s1.remove(at: idx)
}
XCTAssertTrue(
missing.isEmpty, "first sequence missing '\(missing)' elements from second sequence",
file: file, line: line
)
XCTAssertTrue(
s1.isEmpty, "first sequence contains \(s1) missing from second sequence",
file: file, line: line
)
}
func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
@@ -62,12 +118,51 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
) rethrows where S1.Element == S2.Element {
try XCTAssert(expression1().elementsEqual(expression2(), by: areEquivalent), message(), file: file, line: line)
func fail(_ reason: String) {
let message = message()
XCTFail(message.isEmpty ? reason : "\(message) - \(reason)",
file: file, line: line)
}
var iter1 = try expression1().makeIterator()
var iter2 = try expression2().makeIterator()
var idx = 0
while true {
switch (iter1.next(), iter2.next()) {
case let (e1?, e2?) where areEquivalent(e1, e2):
idx += 1
continue
case let (e1?, e2?):
fail("element \(e1) on first sequence does not match element \(e2) on second sequence at position \(idx)")
case (_?, nil):
fail("second sequence shorter than first")
case (nil, _?):
fail("first sequence shorter than second")
case (nil, nil): break
}
return
}
}
func XCTAssertLazySequence<S: LazySequenceProtocol>(_: S) {}
func XCTAssertLazyCollection<S: LazyCollectionProtocol>(_: S) {}
/// Asserts two collections are equal by using their indices to access elements.
func XCTAssertEqualCollections<C1: Collection, C2: Collection>(
_ expression1: @autoclosure () throws -> C1,
_ expression2: @autoclosure () throws -> C2,
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
) rethrows where C1.Element: Equatable, C1.Element == C2.Element {
let c1 = try expression1()
let c2 = try expression2()
XCTAssertEqual(c1.indices.count, c2.indices.count, message(), file: file, line: line)
for index in zip(c1.indices, c2.indices) {
XCTAssertEqual(c1[index.0], c2[index.1], message(), file: file, line: line)
}
}
/// Tests that all index traversal methods behave as expected.
///
/// Verifies the correctness of the implementations of `startIndex`, `endIndex`,
@@ -0,0 +1,122 @@
//===----------------------------------------------------------------------===//
//
// 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 UniquePermutationsTests: XCTestCase {
static let numbers = [1, 1, 1, 2, 3]
static let numbersPermutations: [[[Int]]] = [
// k = 0
[[]],
// 1
[[1], [2], [3]],
// 2
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]],
// 3
[[1, 1, 1], [1, 1, 2], [1, 1, 3],
[1, 2, 1], [1, 2, 3], [1, 3, 1], [1, 3, 2],
[2, 1, 1], [2, 1, 3], [2, 3, 1],
[3, 1, 1], [3, 1, 2], [3, 2, 1]],
// 4
[[1, 1, 1, 2], [1, 1, 1, 3],
[1, 1, 2, 1], [1, 1, 2, 3],
[1, 1, 3, 1], [1, 1, 3, 2],
[1, 2, 1, 1], [1, 2, 1, 3], [1, 2, 3, 1],
[1, 3, 1, 1], [1, 3, 1, 2], [1, 3, 2, 1],
[2, 1, 1, 1], [2, 1, 1, 3], [2, 1, 3, 1], [2, 3, 1, 1],
[3, 1, 1, 1], [3, 1, 1, 2], [3, 1, 2, 1], [3, 2, 1, 1]],
// 5
[[1, 1, 1, 2, 3], [1, 1, 1, 3, 2],
[1, 1, 2, 1, 3], [1, 1, 2, 3, 1],
[1, 1, 3, 1, 2], [1, 1, 3, 2, 1],
[1, 2, 1, 1, 3], [1, 2, 1, 3, 1], [1, 2, 3, 1, 1],
[1, 3, 1, 1, 2], [1, 3, 1, 2, 1], [1, 3, 2, 1, 1],
[2, 1, 1, 1, 3], [2, 1, 1, 3, 1], [2, 1, 3, 1, 1], [2, 3, 1, 1, 1],
[3, 1, 1, 1, 2], [3, 1, 1, 2, 1], [3, 1, 2, 1, 1], [3, 2, 1, 1, 1]]
]
}
extension UniquePermutationsTests {
func testEmpty() {
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(), [[]])
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 0), [[]])
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 1), [])
XCTAssertEqualSequences(
([] as [Int]).uniquePermutations(ofCount: 1...3), [])
}
func testSingleCounts() {
for (k, expectation) in Self.numbersPermutations.enumerated() {
XCTAssertEqualSequences(
expectation,
Self.numbers.uniquePermutations(ofCount: k))
}
XCTAssertEqualSequences(
Self.numbersPermutations[5],
Self.numbers.uniquePermutations())
}
func testRanges() {
for lower in Self.numbersPermutations.indices {
// upper bounded
XCTAssertEqualSequences(
Self.numbersPermutations[...lower].joined(),
Self.numbers.uniquePermutations(ofCount: ...lower))
// lower bounded
XCTAssertEqualSequences(
Self.numbersPermutations[lower...].joined(),
Self.numbers.uniquePermutations(ofCount: lower...))
for upper in lower..<Self.numbersPermutations.count {
XCTAssertEqualSequences(
Self.numbersPermutations[lower..<upper].joined(),
Self.numbers.uniquePermutations(ofCount: lower..<upper))
}
}
}
}
extension UniquePermutationsTests {
private final class IntBox: Hashable {
var value: Int
init(_ value: Int) {
self.value = value
}
static func == (lhs: IntBox, rhs: IntBox) -> Bool {
lhs.value == rhs.value
}
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
func testFirstUnique() {
// When duplicate elements are encountered, all permutations use the first
// instance of the duplicated elements.
let numbers = Self.numbers.map(IntBox.init)
for k in 0...numbers.count {
for p in numbers.uniquePermutations(ofCount: k) {
XCTAssertTrue(p.filter { $0.value == 1 }.allSatisfy { $0 === numbers[0] })
}
}
}
func testLaziness() {
XCTAssertLazySequence("ABCD".lazy.uniquePermutations())
}
}