mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-24 04:17:48 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
993b950250 |
No files matched your search
@@ -16,7 +16,7 @@ about: Something isn't working as expected
|
|||||||
|
|
||||||
Replace this paragraph with a short description of the incorrect incorrect behavior. If this is a regression, please note the last version that the behavior was correct in addition to your current version.
|
Replace this paragraph with a short description of the incorrect incorrect behavior. If this is a regression, please note the last version that the behavior was correct in addition to your current version.
|
||||||
|
|
||||||
**Swift Algorithms version:** `1.0.0` or the `main` branch, for example.
|
**Swift Algorithms version:** `0.0.1` or the `main` branch, for example.
|
||||||
**Swift version:** Paste the output of `swift --version` here.
|
**Swift version:** Paste the output of `swift --version` here.
|
||||||
|
|
||||||
### Checklist
|
### Checklist
|
||||||
|
|||||||
@@ -17,5 +17,5 @@ Replace this paragraph with a description of your changes and rationale. Provide
|
|||||||
### Checklist
|
### Checklist
|
||||||
- [ ] I've added at least one test that validates that my change is working, if appropriate
|
- [ ] I've added at least one test that validates that my change is working, if appropriate
|
||||||
- [ ] I've followed the code style of the rest of the project
|
- [ ] I've followed the code style of the rest of the project
|
||||||
- [ ] I've read the [Contribution Guidelines](../blob/main/CONTRIBUTING.md)
|
- [ ] I've read the [Contribution Guidelines](../CONTRIBUTING.md)
|
||||||
- [ ] I've updated the documentation if necessary
|
- [ ] I've updated the documentation if necessary
|
||||||
@@ -34,5 +34,5 @@ What is the impact of this change on existing users? Does it deprecate or remove
|
|||||||
### Checklist
|
### Checklist
|
||||||
- [ ] I've added at least one test that validates that my change is working, if appropriate
|
- [ ] I've added at least one test that validates that my change is working, if appropriate
|
||||||
- [ ] I've followed the code style of the rest of the project
|
- [ ] I've followed the code style of the rest of the project
|
||||||
- [ ] I've read the [Contribution Guidelines](../../blob/main/CONTRIBUTING.md)
|
- [ ] I've read the [Contribution Guidelines](../../CONTRIBUTING.md)
|
||||||
- [ ] I've updated the documentation if necessary
|
- [ ] I've updated the documentation if necessary
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
{
|
||||||
|
"fileScopedDeclarationPrivacy" : {
|
||||||
|
"accessLevel" : "private"
|
||||||
|
},
|
||||||
|
"indentation" : {
|
||||||
|
"spaces" : 2
|
||||||
|
},
|
||||||
|
"indentConditionalCompilationBlocks" : true,
|
||||||
|
"indentSwitchCaseLabels" : false,
|
||||||
|
"lineBreakAroundMultilineExpressionChainComponents" : false,
|
||||||
|
"lineBreakBeforeControlFlowKeywords" : false,
|
||||||
|
"lineBreakBeforeEachArgument" : false,
|
||||||
|
"lineBreakBeforeEachGenericRequirement" : false,
|
||||||
|
"lineLength" : 100,
|
||||||
|
"maximumBlankLines" : 1,
|
||||||
|
"prioritizeKeepingFunctionOutputTogether" : false,
|
||||||
|
"respectsExistingLineBreaks" : true,
|
||||||
|
"rules" : {
|
||||||
|
"AllPublicDeclarationsHaveDocumentation" : false,
|
||||||
|
"AlwaysUseLowerCamelCase" : true,
|
||||||
|
"AmbiguousTrailingClosureOverload" : true,
|
||||||
|
"BeginDocumentationCommentWithOneLineSummary" : true,
|
||||||
|
"DoNotUseSemicolons" : true,
|
||||||
|
"DontRepeatTypeInStaticProperties" : true,
|
||||||
|
"FileScopedDeclarationPrivacy" : true,
|
||||||
|
"FullyIndirectEnum" : true,
|
||||||
|
"GroupNumericLiterals" : true,
|
||||||
|
"IdentifiersMustBeASCII" : true,
|
||||||
|
"NeverForceUnwrap" : false,
|
||||||
|
"NeverUseForceTry" : false,
|
||||||
|
"NeverUseImplicitlyUnwrappedOptionals" : false,
|
||||||
|
"NoAccessLevelOnExtensionDeclaration" : true,
|
||||||
|
"NoBlockComments" : true,
|
||||||
|
"NoCasesWithOnlyFallthrough" : true,
|
||||||
|
"NoEmptyTrailingClosureParentheses" : true,
|
||||||
|
"NoLabelsInCasePatterns" : true,
|
||||||
|
"NoLeadingUnderscores" : false,
|
||||||
|
"NoParensAroundConditions" : true,
|
||||||
|
"NoVoidReturnOnFunctionSignature" : true,
|
||||||
|
"OneCasePerLine" : true,
|
||||||
|
"OneVariableDeclarationPerLine" : true,
|
||||||
|
"OnlyOneTrailingClosureArgument" : true,
|
||||||
|
"OrderedImports" : true,
|
||||||
|
"ReturnVoidInsteadOfEmptyTuple" : true,
|
||||||
|
"UseLetInEveryBoundCaseVariable" : true,
|
||||||
|
"UseShorthandTypeNames" : true,
|
||||||
|
"UseSingleLinePropertyGetter" : true,
|
||||||
|
"UseSynthesizedInitializer" : true,
|
||||||
|
"UseTripleSlashForDocumentationComments" : true,
|
||||||
|
"ValidateDocumentationComments" : false
|
||||||
|
},
|
||||||
|
"tabWidth" : 8,
|
||||||
|
"version" : 1
|
||||||
|
}
|
||||||
+7
-141
@@ -4,138 +4,18 @@
|
|||||||
Add new items at the end of the relevant section under **Unreleased**.
|
Add new items at the end of the relevant section under **Unreleased**.
|
||||||
-->
|
-->
|
||||||
|
|
||||||
This project follows semantic versioning.
|
This project follows semantic versioning. While still in major version `0`,
|
||||||
|
source-stability is only guaranteed within minor versions (e.g. between
|
||||||
|
`0.0.3` and `0.0.4`). If you want to guard against potentially source-breaking
|
||||||
|
package updates, you can specify your package dependency using
|
||||||
|
`.upToNextMinor(from: "0.1.0")` as the requirement.
|
||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
*No new changes.*
|
*No changes yet.*
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## [1.0.0] - 2021-09-08
|
|
||||||
|
|
||||||
### Changes
|
|
||||||
|
|
||||||
- Most sequence and collection types have been renamed, following a more
|
|
||||||
consistent naming structure:
|
|
||||||
- The `Lazy` prefix was dropped.
|
|
||||||
- Either a `Sequence` or `Collection` suffix was added depending on whether or
|
|
||||||
not the type is unconditionally a collection.
|
|
||||||
- The base name was derived from the name of the method that produces it,
|
|
||||||
including an argument label to disambiguate if necessary.
|
|
||||||
```
|
|
||||||
Chain2 -> Chain2Sequence
|
|
||||||
ChunkedBy -> ChunkedByCollection
|
|
||||||
ChunkedOn -> ChunkedOnCollection
|
|
||||||
ChunkedByCount -> ChunksOfCountCollection
|
|
||||||
Combinations -> CombinationsSequence
|
|
||||||
Cycle -> CycledSequence
|
|
||||||
FiniteCycle -> CycledTimesCollection
|
|
||||||
Indexed -> IndexedCollection
|
|
||||||
Intersperse -> InterspersedSequence
|
|
||||||
LazySplitSequence -> SplitSequence
|
|
||||||
LazySplitCollection -> SplitCollection
|
|
||||||
Permutations -> PermutationsSequence
|
|
||||||
UniquePermutations -> UniquePermutationsSequence
|
|
||||||
Product2 -> Product2Sequence
|
|
||||||
ExclusiveReductions -> ExclusiveReductionsSequence
|
|
||||||
InclusiveReductions -> InclusiveReductionsSequence
|
|
||||||
StrideSequence -> StridingSequence
|
|
||||||
StrideCollection -> StridingCollection
|
|
||||||
Uniqued -> UniquedSequence
|
|
||||||
Windows -> WindowsOfCountCollection
|
|
||||||
```
|
|
||||||
- Types that can only be produced from a lazy sequence chain now unconditionally
|
|
||||||
conform to `LazySequenceProtocol` and wrap the base sequence instead of the
|
|
||||||
lazy wrapper, making some return types slightly simpler.
|
|
||||||
- e.g. `[1, 2, 3].lazy.reductions(+)` now returns
|
|
||||||
`ExclusiveReductionsSequence<[Int]>`, not
|
|
||||||
`ExclusiveReductionsSequence<LazySequence<[Int]>>`.
|
|
||||||
- This concerns `JoinedByClosureSequence`, `JoinedByClosureCollection`,
|
|
||||||
`ExclusiveReductionsSequence`, `InclusiveReductionsSequence`.
|
|
||||||
- The generic parameters of the `ExclusiveReductions` type have been swapped,
|
|
||||||
putting the base collection first and the result type second.
|
|
||||||
- The `Indices` associated type of `IndexedCollection` now matches
|
|
||||||
`Base.Indices`.
|
|
||||||
|
|
||||||
### Removals
|
|
||||||
|
|
||||||
- Previously deprecated type and method names have been removed:
|
|
||||||
- The `Chain` type alias for `Chain2Sequence`
|
|
||||||
- The `chained(with:)` method which was replaced with the `chain(_:_:)` free
|
|
||||||
function
|
|
||||||
- The `LazyChunked` and `Chunked` type aliases for `ChunkedByCollection`
|
|
||||||
- The `rotate(subrange:at:)` and `rotate(at:)` methods which were renamed to
|
|
||||||
`rotate(subrange:toStartAt:)` and `rotate(toStartAt:)` respectively
|
|
||||||
|
|
||||||
### Fixes
|
|
||||||
|
|
||||||
- The `StridingSequence` and `StridingCollection` types now conditionally
|
|
||||||
conform to `LazySequenceProtocol`, allowing the `striding(by:)` method to
|
|
||||||
properly propagate laziness in a lazy sequence chain.
|
|
||||||
- Fixed `chunked(by:)` to always compare two consecutive elements rather than
|
|
||||||
each element with the first element of the current chunk. ([#162])
|
|
||||||
|
|
||||||
The 1.0.0 release includes contributions from [iainsmith], [mdznr], and
|
|
||||||
[timvermeulen]. Thank you!
|
|
||||||
|
|
||||||
## [0.2.1] - 2021-06-01
|
|
||||||
|
|
||||||
### Additions
|
|
||||||
|
|
||||||
Expanded versatility for two existing operations:
|
|
||||||
|
|
||||||
- A series of `joined(by:)` overloads concatenate a sequence of sequences using
|
|
||||||
an element or a collection, either passed in or generated from consecutive
|
|
||||||
elements via a closure. ([#138])
|
|
||||||
- Additional `trimming(while:)` methods for trimming only the start or end of a
|
|
||||||
collection, as well as mutating versions of all three variants. ([#104])
|
|
||||||
|
|
||||||
The 0.2.1 release includes contributions from [fedeci] and [timvermeulen].
|
|
||||||
Thank you!
|
|
||||||
|
|
||||||
## [0.2.0] - 2021-05-17
|
|
||||||
|
|
||||||
### Additions
|
|
||||||
|
|
||||||
Two new additions to the list of algorithms:
|
|
||||||
|
|
||||||
- `adjacentPairs()` lazily iterates over tuples of adjacent elements of a
|
|
||||||
sequence. ([#119])
|
|
||||||
- `minAndMax()` finds both the smallest and largest elements of a sequence in
|
|
||||||
a single pass. ([#90])
|
|
||||||
|
|
||||||
### Changes
|
|
||||||
|
|
||||||
- When calling `chunked(on:)`, the resulting collection has an element type of
|
|
||||||
`(Subject, SubSequence)` instead of just `SubSequence`, making the subject
|
|
||||||
value available when iterating.
|
|
||||||
|
|
||||||
```swift
|
|
||||||
let numbers = [5, 6, -3, -9, -11, 2, 7, 6]
|
|
||||||
for (signum, values) in numbers.chunked(on: { $0.signum() }) {
|
|
||||||
print(signum, values)
|
|
||||||
}
|
|
||||||
// 1 [5, 6]
|
|
||||||
// -1 [-3, -9, -11]
|
|
||||||
// 1 [2, 7, 6]
|
|
||||||
```
|
|
||||||
|
|
||||||
### Fixes
|
|
||||||
|
|
||||||
- Improvements to the documentation and PR templates.
|
|
||||||
|
|
||||||
The 0.2.0 release includes contributions from [CTMacUser], [LemonSpike],
|
|
||||||
[mpangburn], and [natecook1000]. Thank you!
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## [0.1.1] - 2021-04-14
|
|
||||||
|
|
||||||
### Fixes
|
|
||||||
|
|
||||||
- `Product2` associated type inference error in release build ([#130])
|
|
||||||
|
|
||||||
## [0.1.0] - 2021-04-13
|
## [0.1.0] - 2021-04-13
|
||||||
|
|
||||||
### Additions
|
### Additions
|
||||||
@@ -269,11 +149,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
|||||||
|
|
||||||
<!-- Link references for releases -->
|
<!-- Link references for releases -->
|
||||||
|
|
||||||
[Unreleased]: https://github.com/apple/swift-algorithms/compare/1.0.0...HEAD
|
[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.1.0...HEAD
|
||||||
[1.0.0]: https://github.com/apple/swift-algorithms/compare/0.2.1...1.0.0
|
|
||||||
[0.2.1]: https://github.com/apple/swift-algorithms/compare/0.2.0...0.2.1
|
|
||||||
[0.2.0]: https://github.com/apple/swift-algorithms/compare/0.1.1...0.2.0
|
|
||||||
[0.1.1]: https://github.com/apple/swift-algorithms/compare/0.1.0...0.1.1
|
|
||||||
[0.1.0]: https://github.com/apple/swift-algorithms/compare/0.0.4...0.1.0
|
[0.1.0]: https://github.com/apple/swift-algorithms/compare/0.0.4...0.1.0
|
||||||
[0.0.4]: https://github.com/apple/swift-algorithms/compare/0.0.3...0.0.4
|
[0.0.4]: https://github.com/apple/swift-algorithms/compare/0.0.3...0.0.4
|
||||||
[0.0.3]: https://github.com/apple/swift-algorithms/compare/0.0.2...0.0.3
|
[0.0.3]: https://github.com/apple/swift-algorithms/compare/0.0.2...0.0.3
|
||||||
@@ -297,31 +173,22 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
|||||||
[#77]: https://github.com/apple/swift-algorithms/pull/77
|
[#77]: https://github.com/apple/swift-algorithms/pull/77
|
||||||
[#78]: https://github.com/apple/swift-algorithms/pull/78
|
[#78]: https://github.com/apple/swift-algorithms/pull/78
|
||||||
[#85]: https://github.com/apple/swift-algorithms/pull/85
|
[#85]: https://github.com/apple/swift-algorithms/pull/85
|
||||||
[#90]: https://github.com/apple/swift-algorithms/pull/90
|
|
||||||
[#91]: https://github.com/apple/swift-algorithms/pull/91
|
[#91]: https://github.com/apple/swift-algorithms/pull/91
|
||||||
[#104]: https://github.com/apple/swift-algorithms/pull/104
|
|
||||||
[#106]: https://github.com/apple/swift-algorithms/pull/106
|
[#106]: https://github.com/apple/swift-algorithms/pull/106
|
||||||
[#112]: https://github.com/apple/swift-algorithms/pull/112
|
[#112]: https://github.com/apple/swift-algorithms/pull/112
|
||||||
[#119]: https://github.com/apple/swift-algorithms/pull/119
|
|
||||||
[#124]: https://github.com/apple/swift-algorithms/pull/124
|
[#124]: https://github.com/apple/swift-algorithms/pull/124
|
||||||
[#125]: https://github.com/apple/swift-algorithms/pull/125
|
[#125]: https://github.com/apple/swift-algorithms/pull/125
|
||||||
[#130]: https://github.com/apple/swift-algorithms/pull/130
|
|
||||||
[#138]: https://github.com/apple/swift-algorithms/pull/138
|
|
||||||
[#162]: https://github.com/apple/swift-algorithms/pull/162
|
|
||||||
|
|
||||||
<!-- Link references for contributors -->
|
<!-- Link references for contributors -->
|
||||||
|
|
||||||
[AustinConlon]: https://github.com/apple/swift-algorithms/commits?author=AustinConlon
|
[AustinConlon]: https://github.com/apple/swift-algorithms/commits?author=AustinConlon
|
||||||
[benrimmington]: https://github.com/apple/swift-algorithms/commits?author=benrimmington
|
[benrimmington]: https://github.com/apple/swift-algorithms/commits?author=benrimmington
|
||||||
[bjhomer]: https://github.com/apple/swift-algorithms/commits?author=bjhomer
|
[bjhomer]: https://github.com/apple/swift-algorithms/commits?author=bjhomer
|
||||||
[CTMacUser]: https://github.com/apple/swift-algorithms/commits?author=CTMacUser
|
|
||||||
[danielctull]: https://github.com/apple/swift-algorithms/commits?author=danielctull
|
[danielctull]: https://github.com/apple/swift-algorithms/commits?author=danielctull
|
||||||
[dhruvshah8]: https://github.com/apple/swift-algorithms/commits?author=dhruvshah8
|
[dhruvshah8]: https://github.com/apple/swift-algorithms/commits?author=dhruvshah8
|
||||||
[egorzhdan]: https://github.com/apple/swift-algorithms/commits?author=egorzhdan
|
[egorzhdan]: https://github.com/apple/swift-algorithms/commits?author=egorzhdan
|
||||||
[fedeci]: https://github.com/apple/swift-algorithms/commits?author=fedeci
|
|
||||||
[hashemi]: https://github.com/apple/swift-algorithms/commits?author=hashemi
|
[hashemi]: https://github.com/apple/swift-algorithms/commits?author=hashemi
|
||||||
[IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen
|
[IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen
|
||||||
[iainsmith]: https://github.com/apple/swift-algorithms/commits?author=iainsmith
|
|
||||||
[iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7
|
[iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7
|
||||||
[karwa]: https://github.com/apple/swift-algorithms/commits?author=karwa
|
[karwa]: https://github.com/apple/swift-algorithms/commits?author=karwa
|
||||||
[kylemacomber]: https://github.com/apple/swift-algorithms/commits?author=kylemacomber
|
[kylemacomber]: https://github.com/apple/swift-algorithms/commits?author=kylemacomber
|
||||||
@@ -330,7 +197,6 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
|||||||
[markuswntr]: https://github.com/apple/swift-algorithms/commits?author=markuswntr
|
[markuswntr]: https://github.com/apple/swift-algorithms/commits?author=markuswntr
|
||||||
[mdznr]: https://github.com/apple/swift-algorithms/commits?author=mdznr
|
[mdznr]: https://github.com/apple/swift-algorithms/commits?author=mdznr
|
||||||
[michiboo]: https://github.com/apple/swift-algorithms/commits?author=michiboo
|
[michiboo]: https://github.com/apple/swift-algorithms/commits?author=michiboo
|
||||||
[mpangburn]: https://github.com/apple/swift-algorithms/commits?author=mpangburn
|
|
||||||
[natecook1000]: https://github.com/apple/swift-algorithms/commits?author=natecook1000
|
[natecook1000]: https://github.com/apple/swift-algorithms/commits?author=natecook1000
|
||||||
[nordicio]: https://github.com/apple/swift-algorithms/commits?author=nordicio
|
[nordicio]: https://github.com/apple/swift-algorithms/commits?author=nordicio
|
||||||
[ollieatkinson]: https://github.com/apple/swift-algorithms/commits?author=ollieatkinson
|
[ollieatkinson]: https://github.com/apple/swift-algorithms/commits?author=ollieatkinson
|
||||||
|
|||||||
@@ -1,63 +0,0 @@
|
|||||||
# AdjacentPairs
|
|
||||||
|
|
||||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/AdjacentPairs.swift) |
|
|
||||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/AdjacentPairsTests.swift)]
|
|
||||||
|
|
||||||
Lazily iterates over tuples of adjacent elements.
|
|
||||||
|
|
||||||
This operation is available for any sequence by calling the `adjacentPairs()`
|
|
||||||
method.
|
|
||||||
|
|
||||||
```swift
|
|
||||||
let numbers = (1...5)
|
|
||||||
let pairs = numbers.adjacentPairs()
|
|
||||||
// Array(pairs) == [(1, 2), (2, 3), (3, 4), (4, 5)]
|
|
||||||
```
|
|
||||||
|
|
||||||
## Detailed Design
|
|
||||||
|
|
||||||
The `adjacentPairs()` method is declared as a `Sequence` extension returning
|
|
||||||
`AdjacentPairsSequence` and as a `Collection` extension returning
|
|
||||||
`AdjacentPairsCollection`.
|
|
||||||
|
|
||||||
```swift
|
|
||||||
extension Sequence {
|
|
||||||
public func adjacentPairs() -> AdjacentPairsSequence<Self>
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```swift
|
|
||||||
extension Collection {
|
|
||||||
public func adjacentPairs() -> AdjacentPairsCollection<Self>
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The `AdjacentPairsSequence` type is a sequence, and the
|
|
||||||
`AdjacentPairsCollection` type is a collection with conditional conformance to
|
|
||||||
`BidirectionalCollection` and `RandomAccessCollection` when the underlying
|
|
||||||
collection conforms.
|
|
||||||
|
|
||||||
### Complexity
|
|
||||||
|
|
||||||
Calling `adjacentPairs` is an O(1) operation.
|
|
||||||
|
|
||||||
### Naming
|
|
||||||
|
|
||||||
This method is named for clarity while remaining agnostic to any particular
|
|
||||||
domain of programming. In natural language processing, this operation is akin to
|
|
||||||
computing a list of bigrams; however, this algorithm is not specific to this use
|
|
||||||
case.
|
|
||||||
|
|
||||||
### Comparison with other languages
|
|
||||||
|
|
||||||
This function is often written as a `zip` of a sequence together with itself,
|
|
||||||
minus its first element.
|
|
||||||
|
|
||||||
**Haskell:** This operation is spelled ``s `zip` tail s``.
|
|
||||||
|
|
||||||
**Python:** Python users may write `zip(s, s[1:])` for a list with at least one
|
|
||||||
element. For natural language processing, the `nltk` package offers a `bigrams`
|
|
||||||
function akin to this method.
|
|
||||||
|
|
||||||
Note that in Swift, the spelling `zip(s, s.dropFirst())` is undefined behavior
|
|
||||||
for a single-pass sequence `s`.
|
|
||||||
+4
-4
@@ -25,13 +25,13 @@ the shared conformances of the two underlying types.
|
|||||||
The `chain(_:_:)` function takes two sequences as arguments:
|
The `chain(_:_:)` function takes two sequences as arguments:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2Sequence<S1, S2>
|
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2<S1, S2>
|
||||||
where S1.Element == S2.Element
|
where S1.Element == S2.Element
|
||||||
```
|
```
|
||||||
|
|
||||||
The resulting `Chain2Sequence` type is a sequence, with conditional conformance
|
The resulting `Chain2` type is a sequence, with conditional conformance to
|
||||||
to `Collection`, `BidirectionalCollection`, and `RandomAccessCollection` when
|
`Collection`, `BidirectionalCollection`, and `RandomAccessCollection` when both
|
||||||
both the first and second arguments conform.
|
the first and second arguments conform.
|
||||||
|
|
||||||
### Naming
|
### Naming
|
||||||
|
|
||||||
|
|||||||
+37
-52
@@ -4,9 +4,9 @@
|
|||||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ChunkedTests.swift)]
|
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ChunkedTests.swift)]
|
||||||
|
|
||||||
Break a collection into subsequences where consecutive elements pass a binary
|
Break a collection into subsequences where consecutive elements pass a binary
|
||||||
predicate, or where all elements in each chunk project to the same value.
|
predicate, or where all elements in each chunk project to the same value.
|
||||||
|
|
||||||
Also includes a `chunks(ofCount:)` that breaks a collection into subsequences
|
Also, includes a `chunks(ofCount:)` that breaks a collection into subsequences
|
||||||
of a given `count`.
|
of a given `count`.
|
||||||
|
|
||||||
There are two variations of the `chunked` method: `chunked(by:)` and
|
There are two variations of the `chunked` method: `chunked(by:)` and
|
||||||
@@ -20,22 +20,20 @@ let chunks = numbers.chunked(by: { $0 <= $1 })
|
|||||||
// [[10, 20, 30], [10, 40, 40], [10, 20]]
|
// [[10, 20, 30], [10, 40, 40], [10, 20]]
|
||||||
```
|
```
|
||||||
|
|
||||||
The `chunked(on:)` method, by contrast, takes a projection of each element and
|
The `chunk(on:)` method, by contrast, takes a projection of each element and
|
||||||
separates chunks where the projection of two consecutive elements is not equal.
|
separates chunks where the projection of two consecutive elements is not equal.
|
||||||
The result includes both the projected value and the subsequence that groups
|
|
||||||
elements with that projected value:
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let names = ["David", "Kyle", "Karoy", "Nate"]
|
let names = ["David", "Kyle", "Karoy", "Nate"]
|
||||||
let chunks = names.chunked(on: \.first!)
|
let chunks = names.chunked(on: \.first!)
|
||||||
// [("D", ["David"]), ("K", ["Kyle", "Karoy"]), ("N", ["Nate"])]
|
// [["David"], ["Kyle", "Karoy"], ["Nate"]]
|
||||||
```
|
```
|
||||||
|
|
||||||
The `chunks(ofCount:)` method takes a `count` parameter (greater than zero)
|
The `chunks(ofCount:)` takes a `count` parameter (required to be > 0) and separates
|
||||||
and separates the collection into chunks of this given count. If the `count`
|
the collection into `n` chunks of this given count. If the `count` parameter is
|
||||||
parameter is evenly divided by the count of the base `Collection`, all the
|
evenly divided by the count of the base `Collection` all the chunks will have
|
||||||
chunks will have a count equal to the parameter. Otherwise, the last chunk will
|
the count equals to the parameter. Otherwise, the last chunk will contain the
|
||||||
contain the remaining elements.
|
remaining elements.
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let names = ["David", "Kyle", "Karoy", "Nate"]
|
let names = ["David", "Kyle", "Karoy", "Nate"]
|
||||||
@@ -46,53 +44,48 @@ let remaining = names.chunks(ofCount: 3)
|
|||||||
// equivalent to [["David", "Kyle", "Karoy"], ["Nate"]]
|
// equivalent to [["David", "Kyle", "Karoy"], ["Nate"]]
|
||||||
```
|
```
|
||||||
|
|
||||||
The `chunks(ofCount:)` is the subject of an [existing SE proposal][proposal].
|
The `chunks(ofCount:)` is the method of the [existing SE proposal][proposal].
|
||||||
|
Unlike the `split` family of methods, the entire collection is included in the
|
||||||
When "chunking" a collection, the entire collection is included in the result,
|
chunked result — joining the resulting chunks recreates the original collection.
|
||||||
unlike the `split` family of methods, where separators are dropped.
|
|
||||||
Joining the result of a chunking method call recreates the original collection.
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
c.elementsEqual(c.chunked(...).joined())
|
c.elementsEqual(c.chunked(...).joined())
|
||||||
// true
|
// true
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Check the [proposal][proposal] detailed design section for more info.
|
||||||
|
|
||||||
[proposal]: https://github.com/apple/swift-evolution/pull/935
|
[proposal]: https://github.com/apple/swift-evolution/pull/935
|
||||||
|
|
||||||
## Detailed Design
|
## Detailed Design
|
||||||
|
|
||||||
The three methods are added as extension to `Collection`. `chunked(by:)` and
|
The two methods are added as extension to `Collection`, with two matching
|
||||||
`chunked(on:)` are eager by default, both with a matching version that return a
|
versions that return a lazy wrapper added to `LazyCollectionProtocol`.
|
||||||
lazy wrapper added to `LazySequenceProtocol`.
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension Collection {
|
extension Collection {
|
||||||
public func chunked(
|
public func chunked(
|
||||||
by belongInSameGroup: (Element, Element) -> Bool
|
by belongInSameGroup: (Element, Element) -> Bool
|
||||||
) -> [SubSequence]
|
) -> [SubSequence]
|
||||||
|
|
||||||
public func chunked<Subject: Equatable>(
|
public func chunked<Subject: Equatable>(
|
||||||
on projection: (Element) -> Subject
|
on projection: (Element) -> Subject
|
||||||
) -> [(Subject, SubSequence)]
|
) -> [SubSequence]
|
||||||
|
}
|
||||||
public func chunks(ofCount count: Int) -> ChunksOfCountCollection<Self>
|
|
||||||
}
|
|
||||||
|
|
||||||
extension LazySequenceProtocol where Self: Collection, Elements: Collection {
|
extension LazyCollectionProtocol {
|
||||||
public func chunked(
|
public func chunked(
|
||||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||||
) -> ChunkedByCollection<Elements, Element>
|
) -> Chunked<Elements>
|
||||||
|
|
||||||
public func chunked<Subject: Equatable>(
|
public func chunked<Subject: Equatable>(
|
||||||
on projection: @escaping (Element) -> Subject
|
on projection: @escaping (Element) -> Subject
|
||||||
) -> ChunkedOnCollection<Elements, Subject>
|
) -> Chunked<Elements>
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The `ChunkedByCollection`, `ChunkedOnCollection`, and `ChunksOfCountCollection`
|
The `Chunked` type is bidirectional when the wrapped collection is
|
||||||
types are bidirectional when the wrapped collection is bidirectional.
|
bidirectional.
|
||||||
`ChunksOfCountCollection` also conforms to `LazySequenceProtocol` when the base
|
|
||||||
collection conforms.
|
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
@@ -100,20 +93,12 @@ The eager methods are O(_n_), the lazy methods are O(_1_).
|
|||||||
|
|
||||||
### Naming
|
### Naming
|
||||||
|
|
||||||
The operation performed by these methods is similar to other ways of breaking a
|
The operation performed by these methods is similar to other ways of breaking a collection up into subsequences. In particular, the predicate-based `split(where:)` method looks similar to `chunked(on:)`. You can draw a distinction between these different operations based on the resulting subsequences:
|
||||||
collection up into subsequences. In particular, the predicate-based
|
|
||||||
`split(where:)` method looks similar to `chunked(on:)`. You can draw a
|
- `split`: *In the standard library.* Breaks a collection into subsequences, removing any elements that are considered "separators". The original collection cannot be recovered from the result of splitting.
|
||||||
distinction between these different operations based on the resulting
|
- `chunked`: *In this package.* Breaks a collection into subsequences, preserving each element in its initial ordering. Joining the resulting subsequences re-forms the original collection.
|
||||||
subsequences:
|
- `sliced`: *Not included in this package or the stdlib.* Breaks a collection into potentially overlapping subsequences.
|
||||||
|
|
||||||
- `split`: *In the standard library.* Breaks a collection into subsequences,
|
|
||||||
removing any elements that are considered "separators". The original collection
|
|
||||||
cannot be recovered from the result of splitting.
|
|
||||||
- `chunked`: *In this package.* Breaks a collection into subsequences,
|
|
||||||
preserving each element in its initial ordering. Joining the resulting
|
|
||||||
subsequences re-forms the original collection.
|
|
||||||
- `sliced`: *Not included in this package or the stdlib.* Breaks a collection
|
|
||||||
into potentially overlapping subsequences.
|
|
||||||
|
|
||||||
### Comparison with other languages
|
### Comparison with other languages
|
||||||
|
|
||||||
|
|||||||
+10
-11
@@ -60,28 +60,27 @@ for combo in numbers.combinations(ofCount: 2...3) {
|
|||||||
## Detailed Design
|
## Detailed Design
|
||||||
|
|
||||||
The `combinations(ofCount:)` method is declared as a `Collection` extension,
|
The `combinations(ofCount:)` method is declared as a `Collection` extension,
|
||||||
and returns a `CombinationsSequence` type:
|
and returns a `Combinations` type:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension Collection {
|
extension Collection {
|
||||||
public func combinations(ofCount k: Int) -> CombinationsSequence<Self>
|
public func combinations(ofCount k: Int) -> Combinations<Self>
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Since the `CombinationsSequence` type needs to store an array of the
|
Since the `Combinations` type needs to store an array of the collection’s
|
||||||
collection’s indices and mutate the array to generate each permutation,
|
indices and mutate the array to generate each permutation, `Combinations` only
|
||||||
`CombinationsSequence` only has `Sequence` conformance. Adding `Collection`
|
has `Sequence` conformance. Adding `Collection` conformance would require
|
||||||
conformance would require storing the array in the index type, which would in
|
storing the array in the index type, which would in turn lead to copying the
|
||||||
turn lead to copying the array at every index advancement.
|
array at every index advancement. `Combinations` does conform to
|
||||||
`CombinationsSequence` does conform to `LazySequenceProtocol` when the base type
|
`LazySequenceProtocol` when the base type conforms.
|
||||||
conforms.
|
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
Calling `combinations(ofCount:)` accesses the count of the collection, so it’s
|
Calling `combinations(ofCount:)` accesses the count of the collection, so it’s
|
||||||
an O(1) operation for random-access collections, or an O(_n_) operation
|
an O(1) operation for random-access collections, or an O(_n_) operation
|
||||||
otherwise. Creating the iterator for a `CombinationsSequence` instance and each
|
otherwise. Creating the iterator for a `Combinations` instance and each call to
|
||||||
call to `CombinationsSequence.Iterator.next()` is an O(_n_) operation.
|
`Combinations.Iterator.next()` is an O(_n_) operation.
|
||||||
|
|
||||||
### Naming
|
### Naming
|
||||||
|
|
||||||
|
|||||||
+2
-3
@@ -37,9 +37,8 @@ extension Collection {
|
|||||||
|
|
||||||
The `Sequence` version of `compacted()` returns a `CompactedSequence` type,
|
The `Sequence` version of `compacted()` returns a `CompactedSequence` type,
|
||||||
while the `Collection` version returns `CompactedCollection`. The collection
|
while the `Collection` version returns `CompactedCollection`. The collection
|
||||||
has conditional conformance to `BidirectionalCollection` when the base
|
has conditional conformance to `BidirectionalCollection` and
|
||||||
collection conforms, and both have conditional conformance to
|
`LazyCollectionProtocol` when the base collection conforms.
|
||||||
`LazySequenceProtocol` when the base collection conforms.
|
|
||||||
|
|
||||||
### Naming
|
### Naming
|
||||||
|
|
||||||
|
|||||||
+9
-9
@@ -26,20 +26,20 @@ Two new methods are added to collections:
|
|||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension Collection {
|
extension Collection {
|
||||||
func cycled() -> CycledSequence<Self>
|
func cycled() -> Cycle<Self>
|
||||||
|
|
||||||
func cycled(times: Int) -> CycledTimesCollection<Self>
|
func cycled(times: Int) -> FiniteCycle<Self>
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The new `CycledSequence` type is a sequence only, given that the `Collection`
|
The new `Cycle` type is a sequence only, given that the `Collection` protocol
|
||||||
protocol design makes infinitely large types impossible/impractical.
|
design makes infinitely large types impossible/impractical. `Cycle` also
|
||||||
`CycledSequence` also conforms to `LazySequenceProtocol` when the base type
|
conforms to `LazySequenceProtocol` when the base type conforms.
|
||||||
conforms.
|
|
||||||
|
|
||||||
The `CycledTimesCollection` type always has `Collection` conformance, with
|
The `FiniteCycle` type always has `Collection` conformance, with
|
||||||
`BidirectionalCollection`, `RandomAccessCollection`, and `LazySequenceProtocol`
|
`BidirectionalCollection` conformance
|
||||||
conformance when the base type conforms.
|
when called on a bidirectional collection. `FiniteCycle` also
|
||||||
|
conforms to `LazyCollectionProtocol` when the base type conforms.
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
|
|||||||
+5
-5
@@ -21,15 +21,15 @@ for (i, n) in numbers.indexed() {
|
|||||||
|
|
||||||
## Detailed Design
|
## Detailed Design
|
||||||
|
|
||||||
The `indexed` method returns an `IndexedCollection` type:
|
The `indexed` method returns an `Indexed` type:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension Collection {
|
extension Collection {
|
||||||
func indexed() -> IndexedCollection<Self>
|
func indexed() -> Indexed<Self>
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
`IndexedCollection` scales from a collection up to a random-access collection,
|
`Indexed` scales from a collection up to a random-access collection, depending on
|
||||||
depending on its base type. `Indexed` also conforms to `LazySequenceProtocol`
|
its base type. `Indexed` also conforms to `LazySequenceProtocol` and
|
||||||
when the base type conforms.
|
`LazyCollectionProtocol` when the base type conforms.
|
||||||
|
|
||||||
@@ -25,14 +25,14 @@ A new method is added to sequence:
|
|||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension Sequence {
|
extension Sequence {
|
||||||
func interspersed(with separator: Element) -> InterspersedSequence<Self>
|
func interspersed(with separator: Element) -> Intersperse<Self>
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The new `InterspersedSequence` type represents the sequence when the separator
|
The new `Intersperse` type represents the sequence when the separator is
|
||||||
is inserted between each element. `InterspersedSequence` conforms to
|
inserted between each element. `Intersperse` conforms to `Collection`,
|
||||||
`Collection`, `BidirectionalCollection`, `RandomAccessCollection` and
|
`BidirectionalCollection`, `RandomAccessCollection`, `LazySequenceProtocol` and
|
||||||
`LazySequenceProtocol` when the base sequence conforms to those respective
|
`LazyCollectionProtocol` when the base sequence conforms to those respective
|
||||||
protocols.
|
protocols.
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|||||||
@@ -1,100 +0,0 @@
|
|||||||
# Joined
|
|
||||||
|
|
||||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Joined.swift) |
|
|
||||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/JoinedTests.swift)]
|
|
||||||
|
|
||||||
Concatenate a sequence of sequences, inserting a separator between each element.
|
|
||||||
|
|
||||||
The separator can be either a single element or a sequence of elements, and it
|
|
||||||
can optionally depend on the sequences right before and after it by returning it
|
|
||||||
from a closure:
|
|
||||||
|
|
||||||
```swift
|
|
||||||
for number in [[1], [2, 3], [4, 5, 6]].joined(by: 100) {
|
|
||||||
print(number)
|
|
||||||
}
|
|
||||||
// 1, 100, 2, 3, 100, 4, 5, 6
|
|
||||||
|
|
||||||
for number in [[10], [20, 30], [40, 50, 60]].joined(by: { [$0.count, $1.count] }) {
|
|
||||||
print(number)
|
|
||||||
}
|
|
||||||
// 10, 1, 2, 20, 30, 2, 3, 40, 50, 60
|
|
||||||
```
|
|
||||||
|
|
||||||
## Detailed Design
|
|
||||||
|
|
||||||
The versions that take a closure are executed eagerly and are defined on
|
|
||||||
`Sequence`:
|
|
||||||
|
|
||||||
```swift
|
|
||||||
extension Sequence where Element: Sequence {
|
|
||||||
public func joined(
|
|
||||||
by separator: (Element, Element) throws -> Element.Element
|
|
||||||
) rethrows -> [Element.Element]
|
|
||||||
|
|
||||||
public func joined<Separator>(
|
|
||||||
by separator: (Element, Element) throws -> Separator
|
|
||||||
) rethrows -> [Element.Element]
|
|
||||||
where Separator: Sequence, Separator.Element == Element.Element
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The versions that do not take a closure are defined on both `Sequence` and
|
|
||||||
`Collection` because the resulting collections need to precompute their start
|
|
||||||
index to ensure O(1) access:
|
|
||||||
|
|
||||||
```swift
|
|
||||||
extension Sequence where Element: Sequence {
|
|
||||||
public func joined(by separator: Element.Element)
|
|
||||||
-> JoinedBySequence<Self, CollectionOfOne<Element.Element>>
|
|
||||||
|
|
||||||
public func joined<Separator>(
|
|
||||||
by separator: Separator
|
|
||||||
) -> JoinedBySequence<Self, Separator>
|
|
||||||
where Separator: Collection, Separator.Element == Element.Element
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Collection where Element: Sequence {
|
|
||||||
public func joined(by separator: Element.Element)
|
|
||||||
-> JoinedByCollection<Self, CollectionOfOne<Element.Element>>
|
|
||||||
|
|
||||||
public func joined<Separator>(
|
|
||||||
by separator: Separator
|
|
||||||
) -> JoinedByCollection<Self, Separator>
|
|
||||||
where Separator: Collection, Separator.Element == Element.Element
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Note that the sequence separator of the closure-less version defined on
|
|
||||||
`Sequence` is required to be a `Collection`, because a plain `Sequence` cannot in
|
|
||||||
general be iterated over multiple times.
|
|
||||||
|
|
||||||
The closure-based versions also have lazy variants that are defined on both
|
|
||||||
lazy sequences and collections for the same reason as explained above:
|
|
||||||
|
|
||||||
```swift
|
|
||||||
extension LazySequenceProtocol where Element: Sequence {
|
|
||||||
public func joined(
|
|
||||||
by separator: @escaping (Element, Element) -> Element.Element
|
|
||||||
) -> JoinedByClosureSequence<Self, CollectionOfOne<Element.Element>>
|
|
||||||
|
|
||||||
public func joined<Separator>(
|
|
||||||
by separator: @escaping (Element, Element) -> Separator
|
|
||||||
) -> JoinedByClosureSequence<Self, Separator>
|
|
||||||
}
|
|
||||||
|
|
||||||
extension LazySequenceProtocol where Self: Collection, Element: Collection {
|
|
||||||
public func joined(
|
|
||||||
by separator: @escaping (Element, Element) -> Element.Element
|
|
||||||
) -> JoinedByClosureCollection<Self, CollectionOfOne<Element.Element>>
|
|
||||||
|
|
||||||
public func joined<Separator>(
|
|
||||||
by separator: @escaping (Element, Element) -> Separator
|
|
||||||
) -> JoinedByClosureCollection<Self, Separator>
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`JoinedBySequence`, `JoinedByClosureSequence`, `JoinedByCollection`, and
|
|
||||||
`JoinedByClosureCollection` conform to `LazySequenceProtocol` when the base
|
|
||||||
sequence conforms. `JoinedByCollection` and `JoinedByClosureCollection` also
|
|
||||||
conform to `BidirectionalCollection` when the base collection conforms.
|
|
||||||
@@ -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).
|
||||||
+8
-59
@@ -1,15 +1,11 @@
|
|||||||
# Minima and/or Maxima
|
# Min/Max with Count
|
||||||
|
|
||||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/MinMax.swift) |
|
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/MinMax.swift) |
|
||||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/MinMaxTests.swift)]
|
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/MinMaxTests.swift)]
|
||||||
|
|
||||||
Returns the smallest or largest elements of this collection, sorted by a
|
Returns the smallest or largest elements of this collection, sorted by a predicate or in the order defined by `Comparable` conformance.
|
||||||
predicate or in the order defined by `Comparable` conformance.
|
|
||||||
|
|
||||||
If you need to sort a collection but only need access to a prefix or suffix of
|
If you need to sort a collection but only need access to a prefix or suffix of the sorted elements, using these methods can give you a performance boost over sorting the entire collection. The order of equal elements is guaranteed to be preserved.
|
||||||
the sorted elements, using these methods can give you a performance boost over
|
|
||||||
sorting the entire collection. The order of equal elements is guaranteed to be
|
|
||||||
preserved.
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let numbers = [7, 1, 6, 2, 8, 3, 9]
|
let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||||
@@ -17,20 +13,6 @@ let smallestThree = numbers.min(count: 3, sortedBy: <)
|
|||||||
// [1, 2, 3]
|
// [1, 2, 3]
|
||||||
```
|
```
|
||||||
|
|
||||||
Return the smallest and largest elements of this sequence, determined by a
|
|
||||||
predicate or in the order defined by `Comparable` conformance.
|
|
||||||
|
|
||||||
If you need both the minimum and maximum values of a collection, using these
|
|
||||||
methods can give you a performance boost over running the `min` method followed
|
|
||||||
by the `max` method. Plus they work with single-pass sequences.
|
|
||||||
|
|
||||||
```swift
|
|
||||||
let numbers = [7, 1, 6, 2, 8, 3, 9]
|
|
||||||
if let (smallest, largest) = numbers.minAndMax(by: <) {
|
|
||||||
// Work with 1 and 9....
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Detailed Design
|
## Detailed Design
|
||||||
|
|
||||||
This adds the `Collection` methods shown below:
|
This adds the `Collection` methods shown below:
|
||||||
@@ -49,18 +31,7 @@ extension Collection {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
And the `Sequence` method:
|
Additionally, versions of these methods for `Comparable` types are also provided:
|
||||||
|
|
||||||
```swift
|
|
||||||
extension Sequence {
|
|
||||||
public func minAndMax(
|
|
||||||
by areInIncreasingOrder: (Element, Element) throws -> Bool
|
|
||||||
) rethrows -> (min: Element, max: Element)?
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Additionally, versions of these methods for `Comparable` types are also
|
|
||||||
provided:
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension Collection where Element: Comparable {
|
extension Collection where Element: Comparable {
|
||||||
@@ -68,42 +39,20 @@ extension Collection where Element: Comparable {
|
|||||||
|
|
||||||
public func max(count: Int) -> [Element]
|
public func max(count: Int) -> [Element]
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Sequence where Element: Comparable {
|
|
||||||
public func minAndMax() -> (min: Element, max: Element)?
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
The algorithm used for minimal- or maximal-ordered subsets is based on
|
The algorithm used is based on [Soroush Khanlou's research on this matter](https://khanlou.com/2018/12/analyzing-complexity/). The total complexity is `O(k log k + nk)`, which will result in a runtime close to `O(n)` if *k* is a small amount. If *k* is a large amount (more than 10% of the collection), we fall back to sorting the entire array. Realistically, this means the worst case is actually `O(n log n)`.
|
||||||
[Soroush Khanlou's research on this matter](https://khanlou.com/2018/12/analyzing-complexity/).
|
|
||||||
The total complexity is `O(k log k + nk)`, which will result in a runtime close
|
|
||||||
to `O(n)` if *k* is a small amount. If *k* is a large amount (more than 10% of
|
|
||||||
the collection), we fall back to sorting the entire array. Realistically, this
|
|
||||||
means the worst case is actually `O(n log n)`.
|
|
||||||
|
|
||||||
Here are some benchmarks we made that demonstrates how this implementation
|
Here are some benchmarks we made that demonstrates how this implementation (SmallestM) behaves when *k* increases (before implementing the fallback):
|
||||||
(SmallestM) behaves when *k* increases (before implementing the fallback):
|
|
||||||
|
|
||||||

|

|
||||||

|

|
||||||
|
|
||||||
The algorithm used for simultaneous minimum and maximum is slightly optimized.
|
|
||||||
At each iteration, two elements are read, their relative order is determined,
|
|
||||||
then each is compared against exactly one of the current extrema for potential
|
|
||||||
replacement. When a comparison predicate has to analyze every component of both
|
|
||||||
operands, the optimized algorithm isn't much faster than the straightforward
|
|
||||||
approach. But when a predicate only needs to compare a small part of each
|
|
||||||
instance, the optimization shines through.
|
|
||||||
|
|
||||||
### Comparison with other languages
|
### Comparison with other languages
|
||||||
|
|
||||||
**C++:** The `<algorithm>` library defines a `partial_sort` function where the
|
**C++:** The `<algorithm>` library defines a `partial_sort` function where the entire array is returned using a partial heap sort.
|
||||||
entire array is returned using a partial heap sort. It also defines a
|
|
||||||
`minmax_element` function that scans a range for its minimal and maximal
|
|
||||||
elements.
|
|
||||||
|
|
||||||
**Python:** Defines a `heapq` priority queue that can be used to manually
|
**Python:** Defines a `heapq` priority queue that can be used to manually achieve the same result.
|
||||||
achieve the same result.
|
|
||||||
|
|
||||||
+1
-24
@@ -42,20 +42,6 @@ let p = numbers.partitioningIndex(where: { $0.isMultiple(of: 20) })
|
|||||||
// numbers[p...] = [20, 40, 60]
|
// numbers[p...] = [20, 40, 60]
|
||||||
```
|
```
|
||||||
|
|
||||||
The standard library’s existing `filter(_:)` method provides functionality to
|
|
||||||
get the elements that do match a given predicate. `partitioned(by:)` returns
|
|
||||||
both the elements that match the predicate as well as those that don’t, as a
|
|
||||||
tuple.
|
|
||||||
|
|
||||||
```swift
|
|
||||||
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
|
||||||
let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
|
||||||
print(longNames)
|
|
||||||
// Prints "["Vivien", "Marlon"]"
|
|
||||||
print(shortNames)
|
|
||||||
// Prints "["Kim", "Karl"]"
|
|
||||||
```
|
|
||||||
|
|
||||||
## Detailed Design
|
## Detailed Design
|
||||||
|
|
||||||
All mutating methods are declared as extensions to `MutableCollection`.
|
All mutating methods are declared as extensions to `MutableCollection`.
|
||||||
@@ -83,17 +69,11 @@ extension Collection {
|
|||||||
where belongsInSecondPartition: (Element) throws -> Bool
|
where belongsInSecondPartition: (Element) throws -> Bool
|
||||||
) rethrows -> Index
|
) rethrows -> Index
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Sequence {
|
|
||||||
public func partitioned(
|
|
||||||
by predicate: (Element) throws -> Bool
|
|
||||||
) rethrows -> (falseElements: [Element], trueElements: [Element])
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
The existing partition is an O(_n_) operation, where _n_ is the length of the
|
The existing partition is an O(_n_) operations, where _n_ is the length of the
|
||||||
range to be partitioned, while the stable partition is O(_n_ log _n_). Both
|
range to be partitioned, while the stable partition is O(_n_ log _n_). Both
|
||||||
partitions have algorithms with improved performance for bidirectional
|
partitions have algorithms with improved performance for bidirectional
|
||||||
collections, so it would be ideal for those to be customization points were they
|
collections, so it would be ideal for those to be customization points were they
|
||||||
@@ -102,9 +82,6 @@ to eventually land in the standard library.
|
|||||||
`partitioningIndex(where:)` is a slight generalization of a binary search, and
|
`partitioningIndex(where:)` is a slight generalization of a binary search, and
|
||||||
is an O(log _n_) operation for random-access collections; O(_n_) otherwise.
|
is an O(log _n_) operation for random-access collections; O(_n_) otherwise.
|
||||||
|
|
||||||
`partitioned(by:)` is an O(_n_) operation, where _n_ is the number of elements
|
|
||||||
in the original sequence.
|
|
||||||
|
|
||||||
### Comparison with other languages
|
### Comparison with other languages
|
||||||
|
|
||||||
**C++:** The `<algorithm>` library defines `partition`, `stable_partition`, and
|
**C++:** The `<algorithm>` library defines `partition`, `stable_partition`, and
|
||||||
|
|||||||
+13
-15
@@ -98,20 +98,19 @@ for perm in numbers.permutations(ofCount: 0...) {
|
|||||||
|
|
||||||
## Detailed Design
|
## Detailed Design
|
||||||
|
|
||||||
The `permutations(ofCount:)` and `uniquePermutations(ofCount:)` methods are
|
The `permutations(ofCount:)` and `uniquePermutations(ofCount:)` methods are declared as `Collection` extensions,
|
||||||
declared as `Collection` extensions, and return `PermutationsSequence` and
|
and return `Permutations` and `UniquePermutations` instances, respectively:
|
||||||
`UniquePermutationsSequence` instances, respectively:
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension Collection {
|
extension Collection {
|
||||||
public func permutations(ofCount k: Int? = nil) -> PermutationsSequence<Self>
|
public func permutations(ofCount k: Int? = nil) -> Permutations<Self>
|
||||||
public func permutations<R>(ofCount kRange: R) -> PermutationsSequence<Self>
|
public func permutations<R>(ofCount kRange: R) -> Permutations<Self>
|
||||||
where R: RangeExpression, R.Bound == Int
|
where R: RangeExpression, R.Bound == Int
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Collection where Element: Hashable {
|
extension Collection where Element: Hashable {
|
||||||
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutationsSequence<Self>
|
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self>
|
||||||
public func uniquePermutations<R>(ofCount kRange: R) -> UniquePermutationsSequence<Self>
|
public func uniquePermutations<R>(ofCount kRange: R) -> UniquePermutations<Self>
|
||||||
where R: RangeExpression, R.Bound == Int
|
where R: RangeExpression, R.Bound == Int
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -120,19 +119,18 @@ Since both result types need to store an array of the collection’s
|
|||||||
indices and mutate the array to generate each permutation, they only
|
indices and mutate the array to generate each permutation, they only
|
||||||
have `Sequence` conformance. Adding `Collection` conformance would require
|
have `Sequence` conformance. Adding `Collection` conformance would require
|
||||||
storing the array in the index type, which would in turn lead to copying the
|
storing the array in the index type, which would in turn lead to copying the
|
||||||
array at every index advancement. The `PermutationsSequence` and
|
array at every index advancement. The `Permutations` type
|
||||||
`UniquePermutationsSequence` types conforms to `LazySequenceProtocol` when their
|
conforms to `LazySequenceProtocol` when its base type conforms.
|
||||||
base type conforms.
|
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
Calling `permutations()` is an O(1) operation. Creating the iterator for a
|
Calling `permutations()` is an O(1) operation. Creating the iterator for a
|
||||||
`PermutationsSequence` instance and each call to
|
`Permutations` instance and each call to `Permutations.Iterator.next()` is an
|
||||||
`PermutationsSequence.Iterator.next()` is an O(_n_) operation.
|
O(_n_) operation.
|
||||||
|
|
||||||
Calling `uniquePermutations()` is an O(_n_) operation, because it preprocesses
|
Calling `uniquePermutations()` is an O(_n_) operation, because it preprocesses the
|
||||||
the collection to find duplicate elements. Creating the iterator for and each
|
collection to find duplicate elements. Creating the iterator for and each call to
|
||||||
call to `next()` is also an O(_n_) operation.
|
`next()` is also an O(_n_) operation.
|
||||||
|
|
||||||
### Naming
|
### Naming
|
||||||
|
|
||||||
|
|||||||
+7
-7
@@ -25,26 +25,26 @@ When either collection is empty, the resulting wrapper collection is also empty.
|
|||||||
## Detailed Design
|
## Detailed Design
|
||||||
|
|
||||||
The `product` function takes (at minimum) a sequence and a collection and
|
The `product` function takes (at minimum) a sequence and a collection and
|
||||||
returns a `Product2Sequence` type:
|
returns a `Product2` type:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
public func product<Base1: Sequence, Base2: Collection>(
|
public func product<Base1: Sequence, Base2: Collection>(
|
||||||
_ s1: Base1, _ s2: Base2
|
_ s1: Base1, _ s2: Base2
|
||||||
) -> Product2Sequence<Base1, Base2>
|
) -> Product2<Base1, Base2>
|
||||||
```
|
```
|
||||||
|
|
||||||
We require `Collection` conformance for `Base2`, since it needs to be iterated
|
We require `Collection` conformance for `Base2`, since it needs to be iterated
|
||||||
over multiple times. `Base1`, by contrast, is only iterated over a single time,
|
over multiple times. `Base1`, by contrast, is only iterated over a single time,
|
||||||
so it can be a sequence.
|
so it can be a sequence.
|
||||||
|
|
||||||
The `Product2Sequence` type wraps the base sequence and collection, and acts as
|
The `Product2` type wraps the base sequence and collection, and acts as a
|
||||||
a sequence in the base case, upgrading to a collection, a bidirectional
|
sequence in the base case, upgrading to a collection, a bidirectional
|
||||||
collection, and a random-access collection when both base collections have those
|
collection, and a random-access collection when both base collections have those
|
||||||
conformances.
|
conformances.
|
||||||
|
|
||||||
We don't provide higher arities (like `Product3Sequence`, `Product4Sequence`,
|
We don't provide higher arities (like `Product3`, `Product4`, etc.) at this
|
||||||
etc.) at this time to match the standard library's `Zip2Sequence` type. Users
|
time to match the standard library's `Zip2` type. Users can compose multiple
|
||||||
can compose multiple calls to `product` if they would like higher arities.
|
calls to `product` if they would like higher arities.
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ source.randomSample(count: 4)
|
|||||||
// e.g. [30, 10, 70, 50]
|
// e.g. [30, 10, 70, 50]
|
||||||
source.randomStableSample(count: 4)
|
source.randomStableSample(count: 4)
|
||||||
// e.g. [20, 30, 80, 100]
|
// e.g. [20, 30, 80, 100]
|
||||||
|
//
|
||||||
var rng = SplitMix64(seed: 0)
|
var rng = SplitMix64(seed: 0)
|
||||||
source.randomSample(count: 4, using: &rng)
|
source.randomSample(count: 4, using: &rng)
|
||||||
```
|
```
|
||||||
@@ -146,4 +146,4 @@ performance characteristics as the collection itself, so a user can call
|
|||||||
The stable version of sampling could theoretically return a lazy wrapper
|
The stable version of sampling could theoretically return a lazy wrapper
|
||||||
instead of eagerly creating the sample. However, this isn’t well-motivated and
|
instead of eagerly creating the sample. However, this isn’t well-motivated and
|
||||||
poses some challenges, such as needing to store a copy of the random generator
|
poses some challenges, such as needing to store a copy of the random generator
|
||||||
and potentially needing to cache the randomly-generated values.
|
and potentially needing to cache the randomly-generated values.
|
||||||
+26
-25
@@ -3,8 +3,7 @@
|
|||||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Reductions.swift) |
|
[[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)]
|
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ReductionsTests.swift)]
|
||||||
|
|
||||||
Produces all the intermediate results of reducing a sequence's elements using a
|
Produces all the intermediate results of reducing a sequence's elements using a closure.
|
||||||
closure.
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let exclusiveRunningTotal = (1...5).reductions(0, +)
|
let exclusiveRunningTotal = (1...5).reductions(0, +)
|
||||||
@@ -27,37 +26,39 @@ sequence and another trio are added to `Sequence` which are eagerly evaluated.
|
|||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension LazySequenceProtocol {
|
extension LazySequenceProtocol {
|
||||||
public func reductions<Result>(
|
|
||||||
_ initial: Result,
|
|
||||||
_ transform: @escaping (Result, Element) -> Result
|
|
||||||
) -> ExclusiveReductionsSequence<Result, Self>
|
|
||||||
|
|
||||||
public func reductions<Result>(
|
public func reductions<Result>(
|
||||||
into initial: Result,
|
_ initial: Result,
|
||||||
_ transform: @escaping (inout Result, Element) -> Void
|
_ transform: @escaping (Result, Element) -> Result
|
||||||
) -> ExclusiveReductionsSequence<Result, Self>
|
) -> ExclusiveReductions<Result, Self>
|
||||||
|
|
||||||
public func reductions(
|
public func reductions<Result>(
|
||||||
_ transform: @escaping (Element, Element) -> Element
|
into initial: Result,
|
||||||
) -> InclusiveReductionsSequence<Self>
|
_ transform: @escaping (inout Result, Element) -> Void
|
||||||
|
) -> ExclusiveReductions<Result, Self>
|
||||||
|
|
||||||
|
public func reductions(
|
||||||
|
_ transform: @escaping (Element, Element) -> Element
|
||||||
|
) -> InclusiveReductions<Self>
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension Sequence {
|
extension Sequence {
|
||||||
public func reductions<Result>(
|
|
||||||
_ initial: Result,
|
|
||||||
_ transform: (Result, Element) throws -> Result
|
|
||||||
) rethrows -> [Result]
|
|
||||||
|
|
||||||
public func reductions<Result>(
|
public func reductions<Result>(
|
||||||
into initial: Result,
|
_ initial: Result,
|
||||||
_ transform: (inout Result, Element) throws -> Void
|
_ transform: (Result, Element) throws -> Result
|
||||||
) rethrows -> [Result]
|
) rethrows -> [Result]
|
||||||
|
|
||||||
public func reductions(
|
public func reductions<Result>(
|
||||||
_ transform: (Element, Element) throws -> Element
|
into initial: Result,
|
||||||
) rethrows -> [Element]
|
_ transform: (inout Result, Element) throws -> Void
|
||||||
|
) rethrows -> [Result]
|
||||||
|
|
||||||
|
public func reductions(
|
||||||
|
_ transform: (Element, Element) throws -> Element
|
||||||
|
) rethrows -> [Element]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -101,7 +102,7 @@ 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
|
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
|
value. C++ calls these variants exclusive and inclusive respectively and so
|
||||||
these terms carry through as the name for the lazy sequences;
|
these terms carry through as the name for the lazy sequences;
|
||||||
`ExclusiveReductionsSequence` and `InclusiveReductionsSequence`.
|
`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
|
[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
|
[Issue 25]: https://github.com/apple/swift-algorithms/issues/25
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 64 KiB After Width: | Height: | Size: 74 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 69 KiB After Width: | Height: | Size: 77 KiB |
@@ -1,79 +0,0 @@
|
|||||||
# Split
|
|
||||||
|
|
||||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Split.swift) |
|
|
||||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/SplitTests.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
|
|
||||||
`SplitSequence`. The `LazyCollection` versions return an instance of
|
|
||||||
`SplitCollection`.
|
|
||||||
|
|
||||||
`SplitSequence` 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.
|
|
||||||
|
|
||||||
`SplitCollection` wraps the collection to be split. Its `Index` wraps a range of
|
|
||||||
base collection indices. `startIndex` is computed at initialization.
|
|
||||||
Subscripting a `SplitCollection` 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 `SplitSequence` instance is O(_n_) in time and space, since each
|
|
||||||
subsequence returned is a newly-allocated array.
|
|
||||||
|
|
||||||
Iterating a `SplitCollection` 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).
|
|
||||||
+18
-25
@@ -3,7 +3,7 @@
|
|||||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Stride.swift) |
|
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Stride.swift) |
|
||||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/StrideTests.swift)]
|
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/StrideTests.swift)]
|
||||||
|
|
||||||
Step over the elements of a sequence elements by a specified amount.
|
A type that steps over sequence elements by the specified amount.
|
||||||
|
|
||||||
This is available through the `striding(by:)` method on any `Sequence`.
|
This is available through the `striding(by:)` method on any `Sequence`.
|
||||||
|
|
||||||
@@ -11,39 +11,33 @@ This is available through the `striding(by:)` method on any `Sequence`.
|
|||||||
(0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]
|
(0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]
|
||||||
```
|
```
|
||||||
|
|
||||||
If the stride is larger than the length of the sequence, the resulting wrapper
|
If the stride is larger than the count, the resulting wrapper only contains the
|
||||||
only contains the first element.
|
first element.
|
||||||
|
|
||||||
The stride amount must be a positive value.
|
The stride amount must be a positive value.
|
||||||
|
|
||||||
## Detailed Design
|
## Detailed Design
|
||||||
|
|
||||||
The `striding(by:)` method is declared in extension of both `Sequence` and
|
The `striding(by:)` method is declared as a `Sequence` extension, and returns a
|
||||||
`Collection`:
|
`Stride` type:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension Sequence {
|
extension Sequence {
|
||||||
public func striding(by step: Int) -> StridingSequence<Self>
|
public func striding(by step: Int) -> Stride<Self>
|
||||||
}
|
|
||||||
|
|
||||||
extension Collection {
|
|
||||||
public func striding(by step: Int) -> StridingCollection<Self>
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The reason for this distinction is subtle. The `StridingSequence.Iterator` type
|
A custom `Index` type is defined so that it's not possible to get confused when trying
|
||||||
is unable to skip over multiple elements of the wrapped iterator at once since
|
to access an index of the stride collection.
|
||||||
that's not part of `IteratorProtocol`'s interface. In order to efficiently
|
|
||||||
stride over collections that provide a fast way of skipping multiple elements at
|
|
||||||
once, the `StridingCollection` type was added which does not provide a custom
|
|
||||||
`Iterator` type and therefore always strides over the underlying collection in
|
|
||||||
the fastest way possible. See the related
|
|
||||||
[GitHub issue](https://github.com/apple/swift-algorithms/issues/63) for more
|
|
||||||
information.
|
|
||||||
|
|
||||||
A careful thought was given to the composition of these strides by giving a
|
```swift
|
||||||
custom implementation to `index(_:offsetBy:limitedBy)` which multiplies the
|
[0, 1, 2, 3, 4].striding(by: 2)[1] // == 1
|
||||||
offset by the stride amount.
|
[0, 1, 2, 3, 4].striding(by: 2).map { $0 }[1] // == 2
|
||||||
|
```
|
||||||
|
|
||||||
|
A careful thought was given to the composition of these strides by giving a custom
|
||||||
|
implementation to `index(_:offsetBy:limitedBy)` which multiplies the offset by the
|
||||||
|
stride amount.
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
base.index(i.base, offsetBy: distance * stride, limitedBy: base.endIndex)
|
base.index(i.base, offsetBy: distance * stride, limitedBy: base.endIndex)
|
||||||
@@ -58,9 +52,8 @@ The following two lines of code are equivalent, including performance:
|
|||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
The call to `striding(by: k)` is always O(_1_) and access to the next value in
|
The call to `striding(by: k)` is always O(_1_) and access to the next value in the stride
|
||||||
the stride is O(_1_) if the collection conforms to `RandomAccessCollection`,
|
is O(_1_) if the collection conforms to `RandomAccessCollection`, otherwise O(_k_).
|
||||||
otherwise O(_k_).
|
|
||||||
|
|
||||||
### Comparison with other languages
|
### Comparison with other languages
|
||||||
|
|
||||||
|
|||||||
+14
-14
@@ -3,37 +3,37 @@
|
|||||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Suffix.swift) |
|
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Suffix.swift) |
|
||||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/SuffixTests.swift)]
|
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/SuffixTests.swift)]
|
||||||
|
|
||||||
This function returns a subsequence containing the elements from the end of the
|
|
||||||
collection until predicate returns `false` and skipping the remaining elements.
|
|
||||||
|
|
||||||
This example uses `suffix(while: )` to iterate through collection of integers
|
This function returns a subsequence containing the elements from the end of the collection until predicate returns `false` and skipping the remaining elements.
|
||||||
from the end until the predicate returns false, in this case when `$0 <= 5`
|
|
||||||
|
This example uses `suffix(while: )` to iterate through collection of integers from the end until the predicate returns false, in this case when `$0 <= 5`
|
||||||
```swift
|
```swift
|
||||||
(0...10).suffix(while: { $0 > 5 } // == [6,7,8,9,10]
|
(0...10).suffix(while: { $0 > 5 } // == [6,7,8,9,10]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## Detailed Design
|
## Detailed Design
|
||||||
|
|
||||||
The `suffix(while:)` function is added as a method on an extension of
|
The `suffix(while:)` function is added as a method on an extension of `BidirectionalCollection`.
|
||||||
`BidirectionalCollection`.
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension BidirectionalCollection {
|
extension BidirectionalCollection {
|
||||||
public func suffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
|
||||||
|
public func suffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
This method requires `BidirectionalCollection` for an efficient implementation
|
This method requires `BidirectionalCollection` for an efficient implementation which visits as few elements as possible. Swift's protocol allows for backward traversal of a collection as well as access to *last* property of a collection.
|
||||||
which visits as few elements as possible. Swift's protocol allows for backward
|
|
||||||
traversal of a collection as well as access to *last* property of a collection.
|
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
Calling this method is O(*n*), where *n* is the length of the collection.
|
Calling this method is O(*n*), where *n* is the length of the collection.
|
||||||
|
|
||||||
|
|
||||||
### Naming
|
### Naming
|
||||||
|
|
||||||
The function's name resembles that of an existing Swift function
|
The function's name resembles that of an existing Swift function `prefix(while:)`, which performs same operation however in the forward direction of the collection. Hence, as this function traverses from the end of the collection, `suffix(while:)` is an appropriate name.
|
||||||
`prefix(while:)`, which performs same operation however in the forward direction
|
|
||||||
of the collection. Hence, as this function traverses from the end of the
|
|
||||||
collection, `suffix(while:)` is an appropriate name.
|
|
||||||
+31
-66
@@ -3,11 +3,10 @@
|
|||||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Trim.swift) |
|
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Trim.swift) |
|
||||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/TrimTests.swift)]
|
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/TrimTests.swift)]
|
||||||
|
|
||||||
Returns a `SubSequence` formed by discarding all elements at the start and end
|
Returns a `SubSequence` formed by discarding all elements at the start and end of the collection
|
||||||
of the collection which satisfy the given predicate.
|
which satisfy the given predicate.
|
||||||
|
|
||||||
This example uses `trimming(while:)` to get a substring without the white space
|
This example uses `trimming(while:)` to get a substring without the white space at the beginning and end of the string.
|
||||||
at the beginning and end of the string.
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let myString = " hello, world "
|
let myString = " hello, world "
|
||||||
@@ -23,56 +22,31 @@ A new method is added to `BidirectionalCollection`:
|
|||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension BidirectionalCollection {
|
extension BidirectionalCollection {
|
||||||
public func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
|
||||||
|
public func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
This method requires `BidirectionalCollection` for an efficient implementation
|
This method requires `BidirectionalCollection` for an efficient implementation which visits as few elements as possible.
|
||||||
which visits as few elements as possible.
|
|
||||||
|
|
||||||
A less-efficient implementation is _possible_ for any `Collection`, which would
|
A less-efficient implementation is _possible_ for any `Collection`, which would involve always traversing the
|
||||||
involve always traversing the entire collection. This implementation is not
|
entire collection. This implementation is not provided, as it would mean developers of generic algorithms who forget
|
||||||
provided, as it would mean developers of generic algorithms who forget to add
|
to add the `BidirectionalCollection` constraint will receive that inefficient implementation:
|
||||||
the `BidirectionalCollection` constraint will receive that inefficient
|
|
||||||
implementation:
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
func myAlgorithm<Input>(input: Input) where Input: Collection {
|
func myAlgorithm<Input>(input: Input) where Input: Collection {
|
||||||
let trimmedInput = input.trimming(while: { ... }) // Uses least-efficient implementation.
|
|
||||||
|
let trimmedInput = input.trimming(while: { ... }) // Uses least-efficient implementation.
|
||||||
}
|
}
|
||||||
|
|
||||||
func myAlgorithm2<Input>(input: Input) where Input: BidirectionalCollection {
|
func myAlgorithm2<Input>(input: Input) where Input: BidirectionalCollection {
|
||||||
let trimmedInput = input.trimming(while: { ... }) // Uses most-efficient implementation.
|
|
||||||
|
let trimmedInput = input.trimming(while: { ... }) // Uses most-efficient implementation.
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Swift provides the `BidirectionalCollection` protocol for marking types which
|
Swift provides the `BidirectionalCollection` protocol for marking types which support reverse traversal,
|
||||||
support reverse traversal, and generic types and algorithms which want to make
|
and generic types and algorithms which want to make use of that should add it to their constraints.
|
||||||
use of that should add it to their constraints.
|
|
||||||
|
|
||||||
### >= 0.3.0
|
|
||||||
|
|
||||||
In `v0.3.0` new methods are added to allow discarding all the elements matching
|
|
||||||
the predicate at the beginning (prefix) or at the ending (suffix) of the
|
|
||||||
collection.
|
|
||||||
- `trimmingSuffix(while:)` can only be run on collections conforming to the
|
|
||||||
`BidirectionalCollection` protocol.
|
|
||||||
- `trimmingPrefix(while:)` can be run also on collections conforming to the
|
|
||||||
`Collection` protocol.
|
|
||||||
|
|
||||||
```swift
|
|
||||||
let myString = " hello, world "
|
|
||||||
print(myString.trimmingPrefix(while: \.isWhitespace)) // "hello, world "
|
|
||||||
|
|
||||||
print(myString.trimmingSuffix(while: \.isWhitespace)) // " hello, world"
|
|
||||||
```
|
|
||||||
Also mutating variants for all the methods already existing and the new ones are
|
|
||||||
added.
|
|
||||||
```swift
|
|
||||||
var myString = " hello, world "
|
|
||||||
myString.trim(while: \.isWhitespace)
|
|
||||||
print(myString) // "hello, world"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
@@ -80,8 +54,7 @@ Calling this method is O(_n_).
|
|||||||
|
|
||||||
### Naming
|
### Naming
|
||||||
|
|
||||||
The name `trim` has precedent in other programming languages. Another popular
|
The name `trim` has precedent in other programming languages. Another popular alternative might be `strip`.
|
||||||
alternative might be `strip`.
|
|
||||||
|
|
||||||
| Example usage | Languages |
|
| Example usage | Languages |
|
||||||
|-|-|
|
|-|-|
|
||||||
@@ -106,38 +79,30 @@ alternative might be `strip`.
|
|||||||
| TRIM(''string'') | SQL |
|
| TRIM(''string'') | SQL |
|
||||||
| String.trim ''string'' | OCaml 4+ |
|
| String.trim ''string'' | OCaml 4+ |
|
||||||
|
|
||||||
Note: This is an abbreviated list from Wikipedia.
|
Note: This is an abbreviated list from Wikipedia. [Full table](https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(string_functions)#trim)
|
||||||
[Full table](https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(string_functions)#trim)
|
|
||||||
|
|
||||||
The standard library includes a variety of methods which perform similar
|
The standard library includes a variety of methods which perform similar operations:
|
||||||
operations:
|
|
||||||
|
|
||||||
- Firstly, there are `dropFirst(Int)` and `dropLast(Int)`. These return slices
|
- Firstly, there are `dropFirst(Int)` and `dropLast(Int)`. These return slices but do not support user-defined predicates.
|
||||||
but do not support user-defined predicates. If the collection's `count` is less
|
If the collection's `count` is less than the number of elements to drop, they return an empty slice.
|
||||||
than the number of elements to drop, they return an empty slice.
|
- Secondly, there is `drop(while:)`, which also returns a slice and is equivalent to a 'left-trim' (trimming from the head but not the tail).
|
||||||
- Secondly, there is `drop(while:)`, which also returns a slice and is
|
If the entire collection is dropped, this method returns an empty slice.
|
||||||
equivalent to a 'left-trim' (trimming from the head but not the tail). If the
|
- Thirdly, there are `removeFirst(Int)` and `removeLast(Int)` which do not return slices and actually mutate the collection.
|
||||||
entire collection is dropped, this method returns an empty slice.
|
If the collection's `count` is less than the number of elements to remove, this method triggers a runtime error.
|
||||||
- Thirdly, there are `removeFirst(Int)` and `removeLast(Int)` which do not
|
- Lastly, there are the `popFirst()` and `popLast()` methods, which work like `removeFirst()` and `removeLast()`,
|
||||||
return slices and actually mutate the collection. If the collection's `count` is
|
except they do not trigger a runtime error for empty collections.
|
||||||
less than the number of elements to remove, this method triggers a runtime
|
|
||||||
error.
|
|
||||||
- Lastly, there are the `popFirst()` and `popLast()` methods, which work like
|
|
||||||
`removeFirst()` and `removeLast()`, except they do not trigger a runtime error
|
|
||||||
for empty collections.
|
|
||||||
|
|
||||||
The closest neighbours to this function would be the `drop` family of methods.
|
The closest neighbours to this function would be the `drop` family of methods. Unfortunately, unlike `dropFirst(Int)`,
|
||||||
Unfortunately, unlike `dropFirst(Int)`,the name `drop(while:)` does not specify
|
the name `drop(while:)` does not specify which end(s) of the collection it operates on. Moreover, one could easily
|
||||||
which end(s) of the collection it operates on. Moreover, one could easily
|
|
||||||
mistake code such as:
|
mistake code such as:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let result = myString.drop(while: \.isWhitespace)
|
let result = myString.drop(while: \.isWhitespace)
|
||||||
```
|
```
|
||||||
|
|
||||||
With a lazy filter that drops _all_ whitespace characters regardless of where
|
With a lazy filter that drops _all_ whitespace characters regardless of where they are in the string.
|
||||||
they are in the string. Besides that, the root `trim` leads to clearer, more
|
Besides that, the root `trim` leads to clearer, more concise code, which is more aligned with other programming
|
||||||
concise code, which is more aligned with other programming languages:
|
languages:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
// Does `result` contain the input, trimmed of certain elements?
|
// Does `result` contain the input, trimmed of certain elements?
|
||||||
|
|||||||
+12
-11
@@ -5,9 +5,10 @@
|
|||||||
|
|
||||||
Methods to strip repeated elements from a sequence or collection.
|
Methods to strip repeated elements from a sequence or collection.
|
||||||
|
|
||||||
The `uniqued()` method returns a sequence, dropping duplicate elements from a
|
The `uniqued()` method returns a sequence, dropping duplicate elements
|
||||||
sequence. The `uniqued(on:)` method does the same, using the result of the given
|
from a sequence. The `uniqued(on:)` method does the same, using
|
||||||
closure to determine the "uniqueness" of each element.
|
the result of the given closure to determine the "uniqueness" of each
|
||||||
|
element.
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1]
|
let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1]
|
||||||
@@ -18,14 +19,14 @@ let unique = numbers.uniqued()
|
|||||||
|
|
||||||
## Detailed Design
|
## Detailed Design
|
||||||
|
|
||||||
Both methods are available for sequences, with the simplest limited to when the
|
Both methods are available for sequences, with the simplest limited to
|
||||||
element type conforms to `Hashable`. Both methods preserve the relative order of
|
when the element type conforms to `Hashable`. Both methods preserve
|
||||||
the elements. `uniqued(on:)` has a matching lazy version that is added to
|
the relative order of the elements. `uniqued(on:)` has a matching lazy
|
||||||
`LazySequenceProtocol`.
|
version that is added to `LazySequenceProtocol`.
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension Sequence where Element: Hashable {
|
extension Sequence where Element: Hashable {
|
||||||
func uniqued() -> UniquedSequence<Self, Element>
|
func uniqued() -> Uniqued<Self, Element>
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Sequence {
|
extension Sequence {
|
||||||
@@ -34,15 +35,15 @@ extension Sequence {
|
|||||||
}
|
}
|
||||||
|
|
||||||
extension LazySequenceProtocol {
|
extension LazySequenceProtocol {
|
||||||
func uniqued<Subject>(on projection: @escaping (Element) -> Subject) -> UniquedSequence<Self, Subject>
|
func uniqued<Subject>(on projection: @escaping (Element) -> Subject) -> Uniqued<Self, Subject>
|
||||||
where Subject: Hashable
|
where Subject: Hashable
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
The eager `uniqued(on:)` method is O(_n_) in both time and space complexity. The
|
The eager `uniqued(on:)` method is O(_n_) in both time and space complexity.
|
||||||
lazy versions are O(_1_).
|
The lazy versions are O(_1_).
|
||||||
|
|
||||||
### Comparison with other languages
|
### Comparison with other languages
|
||||||
|
|
||||||
|
|||||||
+8
-12
@@ -6,9 +6,7 @@
|
|||||||
Break a collection into overlapping subsequences where
|
Break a collection into overlapping subsequences where
|
||||||
elements are slices from the original collection.
|
elements are slices from the original collection.
|
||||||
|
|
||||||
The `windows(ofCount:)` method takes a size as a parameter and returns a
|
The `windows(ofCount:)` method takes a size as a parameter and returns a collection of subsequences. Each element of the returned collection is a successive overlapping slice of the given size.
|
||||||
collection of subsequences. Each element of the returned collection is a
|
|
||||||
successive overlapping slice of the given size.
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let swift = "swift"
|
let swift = "swift"
|
||||||
@@ -23,26 +21,24 @@ The `windows(ofCount:)` method is added as an extension `Collection` method:
|
|||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension Collection {
|
extension Collection {
|
||||||
public func windows(ofCount count: Int) -> WindowsOfCountCollection<Self>
|
public func windows(ofCount count: Int) -> Windows<Self>
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
If a size larger than the collection's length is specified, the returned
|
If a size larger than the collection's length is specified, the returned collection is empty.
|
||||||
collection is empty.
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
[1, 2, 3].windows(ofCount: 5).isEmpty // true
|
[1, 2, 3].windows(ofCount: 5).isEmpty // true
|
||||||
```
|
```
|
||||||
|
|
||||||
The resulting `WindowsOfCountCollection` type is a collection, with conditional
|
The resulting `Windows` type is a collection, with conditional conformance to the
|
||||||
conformance to the `BidirectionalCollection`, `RandomAccessCollection`, and
|
`BidirectionalCollection`, `RandomAccessCollection`, and
|
||||||
`LazySequenceProtocol` protocols when the base collection conforms.
|
`LazyCollectionProtocol` protocols when the base collection conforms.
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
The call to `windows(ofCount: k)` is O(1) if the collection conforms to
|
The call to `windows(ofCount: k)` is O(1) if the collection conforms to
|
||||||
`RandomAccessCollection`, otherwise O(_k_). Access to each successive window is
|
`RandomAccessCollection`, otherwise O(_k_). Access to each successive window is O(1).
|
||||||
O(1).
|
|
||||||
|
|
||||||
### Naming
|
### Naming
|
||||||
|
|
||||||
@@ -55,5 +51,5 @@ and `permutations(ofCount:)`.
|
|||||||
### Comparison with other languages
|
### Comparison with other languages
|
||||||
|
|
||||||
[rust](https://doc.rust-lang.org/std/slice/struct.Windows.html) has
|
[rust](https://doc.rust-lang.org/std/slice/struct.Windows.html) has
|
||||||
`std::slice::Windows` which is a method available on slices. It has the same
|
`std::slice::Windows` which is a method available on slices. It has the same
|
||||||
semantics as described here.
|
semantics as described here.
|
||||||
+19
-19
@@ -13,23 +13,23 @@
|
|||||||
import PackageDescription
|
import PackageDescription
|
||||||
|
|
||||||
let package = Package(
|
let package = Package(
|
||||||
name: "swift-algorithms",
|
name: "swift-algorithms",
|
||||||
products: [
|
products: [
|
||||||
.library(
|
.library(
|
||||||
name: "Algorithms",
|
name: "Algorithms",
|
||||||
targets: ["Algorithms"]),
|
targets: ["Algorithms"])
|
||||||
],
|
],
|
||||||
dependencies: [
|
dependencies: [
|
||||||
.package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"),
|
.package(url: "https://github.com/apple/swift-numerics", from: "0.0.1")
|
||||||
],
|
],
|
||||||
targets: [
|
targets: [
|
||||||
.target(
|
.target(
|
||||||
name: "Algorithms",
|
name: "Algorithms",
|
||||||
dependencies: [
|
dependencies: [
|
||||||
.product(name: "RealModule", package: "swift-numerics"),
|
.product(name: "RealModule", package: "swift-numerics")
|
||||||
]),
|
]),
|
||||||
.testTarget(
|
.testTarget(
|
||||||
name: "SwiftAlgorithmsTests",
|
name: "SwiftAlgorithmsTests",
|
||||||
dependencies: ["Algorithms"]),
|
dependencies: ["Algorithms"]),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
@@ -20,21 +20,18 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
|||||||
#### Combining collections
|
#### Combining collections
|
||||||
|
|
||||||
- [`chain(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chain.md): Concatenates two collections with the same element type.
|
- [`chain(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chain.md): Concatenates two collections with the same element type.
|
||||||
- [`cycled()`, `cycled(times:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Cycle.md): Repeats the elements of a collection forever or a set number of times.
|
|
||||||
- [`joined(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Joined.md): Concatenate sequences of sequences, using an element or sequence as a separator, or using a closure to generate each separator.
|
|
||||||
- [`product(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Product.md): Iterates over all the pairs of two collections; equivalent to nested `for`-`in` loops.
|
- [`product(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Product.md): Iterates over all the pairs of two collections; equivalent to nested `for`-`in` loops.
|
||||||
|
- [`cycled()`, `cycled(times:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Cycle.md): Repeats the elements of a collection forever or a set number of times.
|
||||||
|
|
||||||
#### Subsetting operations
|
#### Subsetting operations
|
||||||
|
|
||||||
- [`compacted()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Compacted.md): Drops the `nil`s from a sequence or collection, unwrapping the remaining elements.
|
- [`compacted()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Compacted.md): Drops the `nil`s from a sequence or collection, unwrapping the remaining elements.
|
||||||
- [`partitioned(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the elements in a sequence or collection that do and do not match a given predicate.
|
|
||||||
- [`randomSample(count:)`, `randomSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection.
|
- [`randomSample(count:)`, `randomSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection.
|
||||||
- [`randomStableSample(count:)`, `randomStableSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection, preserving their original relative order.
|
- [`randomStableSample(count:)`, `randomStableSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection, preserving their original relative order.
|
||||||
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
|
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
|
||||||
- [`suffix(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Suffix.md): Returns the suffix of a collection where all element pass a given predicate.
|
- [`suffix(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Suffix.md): Returns the suffix of a collection where all element pass a given predicate.
|
||||||
- [`trimmingPrefix(while:)`, `trimmingSuffix(while)`, `trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start, end, or both. The mutating `trim...` methods trim a collection in place.
|
- [`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.
|
||||||
- [`uniqued()`, `uniqued(on:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Unique.md): The unique elements of a collection, preserving their order.
|
- [`uniqued()`, `uniqued(on:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Unique.md): The unique elements of a collection, preserving their order.
|
||||||
- [`minAndMax()`, `minAndMax(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest and largest elements of a sequence.
|
|
||||||
|
|
||||||
#### Partial sorting
|
#### Partial sorting
|
||||||
|
|
||||||
@@ -42,14 +39,12 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
|||||||
|
|
||||||
#### Other useful operations
|
#### Other useful operations
|
||||||
|
|
||||||
- [`adjacentPairs()`](https://github.com/apple/swift-algorithms/blob/main/Guides/AdjacentPairs.md): Lazily iterates over tuples of adjacent elements.
|
|
||||||
- [`chunked(by:)`, `chunked(on:)`, `chunks(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chunked.md): Eager and lazy operations that break a collection into chunks based on either a binary predicate or when the result of a projection changes or chunks of a given count.
|
- [`chunked(by:)`, `chunked(on:)`, `chunks(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chunked.md): Eager and lazy operations that break a collection into chunks based on either a binary predicate or when the result of a projection changes or chunks of a given count.
|
||||||
- [`firstNonNil(_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/FirstNonNil.md): Returns the first non-`nil` result from transforming a sequence's elements.
|
- [`firstNonNil(_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/FirstNonNil.md): Returns the first non-`nil` result from transforming a sequence's elements.
|
||||||
- [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements.
|
- [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements.
|
||||||
- [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence.
|
- [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence.
|
||||||
- [`partitioningIndex(where:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the starting index of the partition of a collection that matches a predicate.
|
|
||||||
- [`reductions(_:)`, `reductions(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Reductions.md): Returns all the intermediate states of reducing the elements of a sequence or collection.
|
- [`reductions(_:)`, `reductions(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Reductions.md): Returns all the intermediate states of reducing the elements of a sequence or collection.
|
||||||
- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Split.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element.
|
- [`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.
|
||||||
- [`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.
|
- [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection.
|
||||||
|
|
||||||
## Adding Swift Algorithms as a Dependency
|
## Adding Swift Algorithms as a Dependency
|
||||||
@@ -58,25 +53,32 @@ To use the `Algorithms` library in a SwiftPM project,
|
|||||||
add the following line to the dependencies in your `Package.swift` file:
|
add the following line to the dependencies in your `Package.swift` file:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
.package(url: "https://github.com/apple/swift-algorithms", from: "1.0.0"),
|
.package(url: "https://github.com/apple/swift-algorithms", from: "0.0.1"),
|
||||||
```
|
```
|
||||||
|
|
||||||
Include `"Algorithms"` as a dependency for your executable target:
|
Because `Algorithms` is under active development,
|
||||||
|
source-stability is only guaranteed within minor versions (e.g. between `0.0.3` and `0.0.4`).
|
||||||
|
If you don't want potentially source-breaking package updates,
|
||||||
|
use this dependency specification instead:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
.target(name: "<target>", dependencies: [
|
.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.1.0")),
|
||||||
.product(name: "Algorithms", package: "swift-algorithms"),
|
|
||||||
]),
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Finally, add `import Algorithms` to your source code.
|
Finally, include `"Algorithms"` as a dependency for your executable target:
|
||||||
|
|
||||||
## Source Stability
|
```swift
|
||||||
|
let package = Package(
|
||||||
The Swift Algorithms package is source stable; version numbers follow [Semantic Versioning](https://semver.org/). Source breaking changes to public API can only land in a new major version.
|
// name, platforms, products, etc.
|
||||||
|
dependencies: [
|
||||||
The public API of version 1.0 of the `swift-algorithms` package consists of non-underscored declarations that are marked `public` in the `Algorithms` module. Interfaces that aren't part of the public API may continue to change in any release, including patch releases.
|
.package(url: "https://github.com/apple/swift-algorithms", from: "0.1.0"),
|
||||||
|
// other dependencies
|
||||||
Future minor versions of the package may introduce changes to these rules as needed.
|
],
|
||||||
|
targets: [
|
||||||
We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release. Requiring a new Swift release will only require a minor version bump.
|
.target(name: "<target>", dependencies: [
|
||||||
|
.product(name: "Algorithms", package: "swift-algorithms"),
|
||||||
|
]),
|
||||||
|
// other targets
|
||||||
|
]
|
||||||
|
)
|
||||||
|
```
|
||||||
@@ -1,298 +0,0 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
|
||||||
//
|
|
||||||
// This source file is part of the Swift Algorithms open source project
|
|
||||||
//
|
|
||||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
|
||||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
|
||||||
//
|
|
||||||
// See https://swift.org/LICENSE.txt for license information
|
|
||||||
//
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
extension Sequence {
|
|
||||||
/// Creates a sequence of adjacent pairs of elements from this sequence.
|
|
||||||
///
|
|
||||||
/// In the `AdjacentPairsSequence` returned by this method, the elements of
|
|
||||||
/// the *i*th pair are the *i*th and *(i+1)*th elements of the underlying
|
|
||||||
/// sequence. The following example uses the `adjacentPairs()` method to
|
|
||||||
/// iterate over adjacent pairs of integers:
|
|
||||||
///
|
|
||||||
/// for pair in (1...).prefix(5).adjacentPairs() {
|
|
||||||
/// print(pair)
|
|
||||||
/// }
|
|
||||||
/// // Prints "(1, 2)"
|
|
||||||
/// // Prints "(2, 3)"
|
|
||||||
/// // Prints "(3, 4)"
|
|
||||||
/// // Prints "(4, 5)"
|
|
||||||
@inlinable
|
|
||||||
public func adjacentPairs() -> AdjacentPairsSequence<Self> {
|
|
||||||
AdjacentPairsSequence(base: self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Collection {
|
|
||||||
/// A collection of adjacent pairs of elements built from an underlying
|
|
||||||
/// collection.
|
|
||||||
///
|
|
||||||
/// In an `AdjacentPairsCollection`, the elements of the *i*th pair are the
|
|
||||||
/// *i*th and *(i+1)*th elements of the underlying sequence. The following
|
|
||||||
/// example uses the `adjacentPairs()` method to iterate over adjacent pairs
|
|
||||||
/// of integers:
|
|
||||||
///
|
|
||||||
/// for pair in (1...5).adjacentPairs() {
|
|
||||||
/// print(pair)
|
|
||||||
/// }
|
|
||||||
/// // Prints "(1, 2)"
|
|
||||||
/// // Prints "(2, 3)"
|
|
||||||
/// // Prints "(3, 4)"
|
|
||||||
/// // Prints "(4, 5)"
|
|
||||||
@inlinable
|
|
||||||
public func adjacentPairs() -> AdjacentPairsCollection<Self> {
|
|
||||||
AdjacentPairsCollection(base: self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A sequence of adjacent pairs of elements built from an underlying sequence.
|
|
||||||
///
|
|
||||||
/// Use the `adjacentPairs()` method on a sequence to create an
|
|
||||||
/// `AdjacentPairsSequence` instance.
|
|
||||||
public struct AdjacentPairsSequence<Base: Sequence> {
|
|
||||||
@usableFromInline
|
|
||||||
internal let base: Base
|
|
||||||
|
|
||||||
/// Creates an instance that makes pairs of adjacent elements from `base`.
|
|
||||||
@inlinable
|
|
||||||
internal init(base: Base) {
|
|
||||||
self.base = base
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension AdjacentPairsSequence {
|
|
||||||
/// The iterator for an `AdjacentPairsSequence` or `AdjacentPairsCollection`
|
|
||||||
/// instance.
|
|
||||||
public struct Iterator {
|
|
||||||
@usableFromInline
|
|
||||||
internal var base: Base.Iterator
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal var previousElement: Base.Element?
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(base: Base.Iterator) {
|
|
||||||
self.base = base
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension AdjacentPairsSequence.Iterator: IteratorProtocol {
|
|
||||||
public typealias Element = (Base.Element, Base.Element)
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public mutating func next() -> Element? {
|
|
||||||
if previousElement == nil {
|
|
||||||
previousElement = base.next()
|
|
||||||
}
|
|
||||||
|
|
||||||
guard let previous = previousElement, let next = base.next() else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
previousElement = next
|
|
||||||
return (previous, next)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension AdjacentPairsSequence: Sequence {
|
|
||||||
@inlinable
|
|
||||||
public func makeIterator() -> Iterator {
|
|
||||||
Iterator(base: base.makeIterator())
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public var underestimatedCount: Int {
|
|
||||||
Swift.max(0, base.underestimatedCount - 1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension AdjacentPairsSequence: LazySequenceProtocol
|
|
||||||
where Base: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
/// A collection of adjacent pairs of elements built from an underlying
|
|
||||||
/// collection.
|
|
||||||
///
|
|
||||||
/// Use the `adjacentPairs()` method on a collection to create an
|
|
||||||
/// `AdjacentPairsCollection` instance.
|
|
||||||
public struct AdjacentPairsCollection<Base: Collection> {
|
|
||||||
@usableFromInline
|
|
||||||
internal let base: Base
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let secondBaseIndex: Base.Index
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(base: Base) {
|
|
||||||
self.base = base
|
|
||||||
self.secondBaseIndex = base.isEmpty
|
|
||||||
? base.endIndex
|
|
||||||
: base.index(after: base.startIndex)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension AdjacentPairsCollection {
|
|
||||||
/// A position in an `AdjacentPairsCollection` instance.
|
|
||||||
public struct Index: Comparable {
|
|
||||||
@usableFromInline
|
|
||||||
internal var first: Base.Index
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal var second: Base.Index
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(first: Base.Index, second: Base.Index) {
|
|
||||||
self.first = first
|
|
||||||
self.second = second
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public static func == (lhs: Index, rhs: Index) -> Bool {
|
|
||||||
lhs.first == rhs.first
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
|
||||||
lhs.first < rhs.first
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension AdjacentPairsCollection: Collection {
|
|
||||||
@inlinable
|
|
||||||
public var startIndex: Index {
|
|
||||||
Index(
|
|
||||||
first: secondBaseIndex == base.endIndex ? base.endIndex : base.startIndex,
|
|
||||||
second: secondBaseIndex)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public var endIndex: Index {
|
|
||||||
Index(first: base.endIndex, second: base.endIndex)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public subscript(position: Index) -> (Base.Element, Base.Element) {
|
|
||||||
(base[position.first], base[position.second])
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func index(after i: Index) -> Index {
|
|
||||||
precondition(i != endIndex, "Can't advance beyond endIndex")
|
|
||||||
let next = base.index(after: i.second)
|
|
||||||
return next == base.endIndex
|
|
||||||
? endIndex
|
|
||||||
: Index(first: i.second, second: next)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
|
||||||
guard distance != 0 else { return i }
|
|
||||||
|
|
||||||
guard let result = distance > 0
|
|
||||||
? offsetForward(i, by: distance, limitedBy: endIndex)
|
|
||||||
: offsetBackward(i, by: -distance, limitedBy: startIndex)
|
|
||||||
else { fatalError("Index out of bounds") }
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func index(
|
|
||||||
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
guard distance != 0 else { return i }
|
|
||||||
guard limit != i else { return nil }
|
|
||||||
|
|
||||||
if distance > 0 {
|
|
||||||
let limit = limit > i ? limit : endIndex
|
|
||||||
return offsetForward(i, by: distance, limitedBy: limit)
|
|
||||||
} else {
|
|
||||||
let limit = limit < i ? limit : startIndex
|
|
||||||
return offsetBackward(i, by: -distance, limitedBy: limit)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func offsetForward(
|
|
||||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
assert(distance > 0)
|
|
||||||
assert(limit > i)
|
|
||||||
|
|
||||||
guard let newFirst = base.index(i.second, offsetBy: distance - 1, limitedBy: limit.first),
|
|
||||||
newFirst != base.endIndex
|
|
||||||
else { return nil }
|
|
||||||
let newSecond = base.index(after: newFirst)
|
|
||||||
|
|
||||||
precondition(newSecond <= base.endIndex, "Can't advance beyond endIndex")
|
|
||||||
return newSecond == base.endIndex
|
|
||||||
? endIndex
|
|
||||||
: Index(first: newFirst, second: newSecond)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func offsetBackward(
|
|
||||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
assert(distance > 0)
|
|
||||||
assert(limit < i)
|
|
||||||
|
|
||||||
let offset = i == endIndex ? 0 : 1
|
|
||||||
guard let newSecond = base.index(
|
|
||||||
i.first,
|
|
||||||
offsetBy: -(distance - offset),
|
|
||||||
limitedBy: limit.second)
|
|
||||||
else { return nil }
|
|
||||||
let newFirst = base.index(newSecond, offsetBy: -1)
|
|
||||||
precondition(newFirst >= base.startIndex, "Can't move before startIndex")
|
|
||||||
return Index(first: newFirst, second: newSecond)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func distance(from start: Index, to end: Index) -> Int {
|
|
||||||
// While there's a 2-step gap between the `first` base index values in
|
|
||||||
// `endIndex` and the penultimate index of this collection, the `second`
|
|
||||||
// base index values are consistently one step apart throughout the
|
|
||||||
// entire collection.
|
|
||||||
base.distance(from: start.second, to: end.second)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public var count: Int {
|
|
||||||
Swift.max(0, base.count - 1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension AdjacentPairsCollection: BidirectionalCollection
|
|
||||||
where Base: BidirectionalCollection
|
|
||||||
{
|
|
||||||
@inlinable
|
|
||||||
public func index(before i: Index) -> Index {
|
|
||||||
precondition(i != startIndex, "Can't offset before startIndex")
|
|
||||||
let second = i == endIndex
|
|
||||||
? base.index(before: base.endIndex)
|
|
||||||
: i.first
|
|
||||||
let first = base.index(before: second)
|
|
||||||
return Index(first: first, second: second)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension AdjacentPairsCollection: RandomAccessCollection
|
|
||||||
where Base: RandomAccessCollection {}
|
|
||||||
|
|
||||||
extension AdjacentPairsCollection: LazySequenceProtocol, LazyCollectionProtocol
|
|
||||||
where Base: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
extension AdjacentPairsCollection.Index: Hashable where Base.Index: Hashable {
|
|
||||||
@inlinable
|
|
||||||
public func hash(into hasher: inout Hasher) {
|
|
||||||
hasher.combine(first)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,13 +10,12 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
/// A concatenation of two sequences with the same element type.
|
/// A concatenation of two sequences with the same element type.
|
||||||
public struct Chain2Sequence<Base1: Sequence, Base2: Sequence>
|
public struct Chain2<Base1: Sequence, Base2: Sequence>
|
||||||
where Base1.Element == Base2.Element
|
where Base1.Element == Base2.Element {
|
||||||
{
|
|
||||||
/// The first sequence in this chain.
|
/// The first sequence in this chain.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base1: Base1
|
internal let base1: Base1
|
||||||
|
|
||||||
/// The second sequence in this chain.
|
/// The second sequence in this chain.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base2: Base2
|
internal let base2: Base2
|
||||||
@@ -28,35 +27,35 @@ public struct Chain2Sequence<Base1: Sequence, Base2: Sequence>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Chain2Sequence: Sequence {
|
extension Chain2: Sequence {
|
||||||
/// The iterator for a `Chain2Sequence` instance.
|
/// The iterator for a `Chain2` sequence.
|
||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var iterator1: Base1.Iterator
|
internal var iterator1: Base1.Iterator
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var iterator2: Base2.Iterator
|
internal var iterator2: Base2.Iterator
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(_ concatenation: Chain2Sequence) {
|
internal init(_ concatenation: Chain2) {
|
||||||
iterator1 = concatenation.base1.makeIterator()
|
iterator1 = concatenation.base1.makeIterator()
|
||||||
iterator2 = concatenation.base2.makeIterator()
|
iterator2 = concatenation.base2.makeIterator()
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public mutating func next() -> Base1.Element? {
|
public mutating func next() -> Base1.Element? {
|
||||||
return iterator1.next() ?? iterator2.next()
|
return iterator1.next() ?? iterator2.next()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func makeIterator() -> Iterator {
|
public func makeIterator() -> Iterator {
|
||||||
Iterator(self)
|
Iterator(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection {
|
extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||||
/// A position in a `Chain2Sequence` instance.
|
/// A position in a `Chain2` collection.
|
||||||
public struct Index: Comparable {
|
public struct Index: Comparable {
|
||||||
// The internal index representation, which can either be an index of the
|
// The internal index representation, which can either be an index of the
|
||||||
// first collection or the second. The `endIndex` of the first collection
|
// first collection or the second. The `endIndex` of the first collection
|
||||||
@@ -98,7 +97,7 @@ extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Converts an index of `Base1` to the corresponding `Index` by mapping
|
/// Converts an index of `Base1` to the corresponding `Index` by mapping
|
||||||
/// `base1.endIndex` to `base2.startIndex`.
|
/// `base1.endIndex` to `base2.startIndex`.
|
||||||
@inlinable
|
@inlinable
|
||||||
@@ -115,7 +114,7 @@ extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection
|
|||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var endIndex: Index {
|
public var endIndex: Index {
|
||||||
Index(second: base2.endIndex)
|
return Index(second: base2.endIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
@@ -138,16 +137,16 @@ extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection
|
|||||||
return Index(second: base2.index(after: i))
|
return Index(second: base2.index(after: i))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||||
guard distance != 0 else { return i }
|
guard distance != 0 else { return i }
|
||||||
|
|
||||||
return distance > 0
|
return distance > 0
|
||||||
? offsetForward(i, by: distance)
|
? offsetForward(i, by: distance)
|
||||||
: offsetBackward(i, by: -distance)
|
: offsetBackward(i, by: -distance)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(
|
public func index(
|
||||||
_ i: Index,
|
_ i: Index,
|
||||||
@@ -168,14 +167,14 @@ extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection
|
|||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||||
else { fatalError("Index is out of bounds") }
|
else { fatalError("Index is out of bounds") }
|
||||||
return index
|
return index
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
||||||
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
||||||
else { fatalError("Index is out of bounds") }
|
else { fatalError("Index is out of bounds") }
|
||||||
return index
|
return index
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,12 +184,12 @@ extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection
|
|||||||
) -> Index? {
|
) -> Index? {
|
||||||
assert(distance >= 0)
|
assert(distance >= 0)
|
||||||
assert(limit >= i)
|
assert(limit >= i)
|
||||||
|
|
||||||
switch (i.position, limit.position) {
|
switch (i.position, limit.position) {
|
||||||
case let (.first(i), .first(limit)):
|
case let (.first(i), .first(limit)):
|
||||||
return base1.index(i, offsetBy: distance, limitedBy: limit)
|
return base1.index(i, offsetBy: distance, limitedBy: limit)
|
||||||
.map(Index.init(first:))
|
.map(Index.init(first:))
|
||||||
|
|
||||||
case let (.first(i), .second(limit)):
|
case let (.first(i), .second(limit)):
|
||||||
if let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) {
|
if let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) {
|
||||||
// the offset stays within the bounds of `base1`
|
// the offset stays within the bounds of `base1`
|
||||||
@@ -201,11 +200,11 @@ extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection
|
|||||||
return base2.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit)
|
return base2.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit)
|
||||||
.map(Index.init(second:))
|
.map(Index.init(second:))
|
||||||
}
|
}
|
||||||
|
|
||||||
case (.second, .first):
|
case (.second, .first):
|
||||||
// impossible because `limit >= i`
|
// impossible because `limit >= i`
|
||||||
fatalError()
|
fatalError()
|
||||||
|
|
||||||
case let (.second(i), .second(limit)):
|
case let (.second(i), .second(limit)):
|
||||||
return base2.index(i, offsetBy: distance, limitedBy: limit)
|
return base2.index(i, offsetBy: distance, limitedBy: limit)
|
||||||
.map(Index.init(second:))
|
.map(Index.init(second:))
|
||||||
@@ -218,16 +217,16 @@ extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection
|
|||||||
) -> Index? {
|
) -> Index? {
|
||||||
assert(distance >= 0)
|
assert(distance >= 0)
|
||||||
assert(limit <= i)
|
assert(limit <= i)
|
||||||
|
|
||||||
switch (i.position, limit.position) {
|
switch (i.position, limit.position) {
|
||||||
case let (.first(i), .first(limit)):
|
case let (.first(i), .first(limit)):
|
||||||
return base1.index(i, offsetBy: -distance, limitedBy: limit)
|
return base1.index(i, offsetBy: -distance, limitedBy: limit)
|
||||||
.map(Index.init(first:))
|
.map(Index.init(first:))
|
||||||
|
|
||||||
case (.first, .second):
|
case (.first, .second):
|
||||||
// impossible because `limit <= i`
|
// impossible because `limit <= i`
|
||||||
fatalError()
|
fatalError()
|
||||||
|
|
||||||
case let (.second(i), .first(limit)):
|
case let (.second(i), .first(limit)):
|
||||||
if let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex) {
|
if let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex) {
|
||||||
// the offset stays within the bounds of `base2`
|
// the offset stays within the bounds of `base2`
|
||||||
@@ -245,7 +244,7 @@ extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection
|
|||||||
.map(Index.init(second:))
|
.map(Index.init(second:))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func distance(from start: Index, to end: Index) -> Int {
|
public func distance(from start: Index, to end: Index) -> Int {
|
||||||
switch (start.position, end.position) {
|
switch (start.position, end.position) {
|
||||||
@@ -263,9 +262,8 @@ extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Chain2Sequence: BidirectionalCollection
|
extension Chain2: BidirectionalCollection
|
||||||
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
|
where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
|
||||||
{
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(before i: Index) -> Index {
|
public func index(before i: Index) -> Index {
|
||||||
assert(i != startIndex, "Can't advance before startIndex")
|
assert(i != startIndex, "Can't advance before startIndex")
|
||||||
@@ -280,8 +278,8 @@ extension Chain2Sequence: BidirectionalCollection
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Chain2Sequence: RandomAccessCollection
|
extension Chain2: RandomAccessCollection
|
||||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// chain(_:_:)
|
// chain(_:_:)
|
||||||
@@ -314,6 +312,19 @@ extension Chain2Sequence: RandomAccessCollection
|
|||||||
///
|
///
|
||||||
/// - Complexity: O(1)
|
/// - Complexity: O(1)
|
||||||
@inlinable
|
@inlinable
|
||||||
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2Sequence<S1, S2> {
|
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2<S1, S2> {
|
||||||
Chain2Sequence(base1: s1, base2: s2)
|
Chain2(base1: s1, base2: s2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Deprecations
|
||||||
|
|
||||||
|
@available(*, deprecated, renamed: "Chain2")
|
||||||
|
public typealias Chain = Chain2
|
||||||
|
|
||||||
|
extension Sequence {
|
||||||
|
@available(*, deprecated, message: "Use the chain(_:_:) function, instead.")
|
||||||
|
public func chained<S: Sequence>(with other: S) -> Chain2<Self, S>
|
||||||
|
where Element == S.Element {
|
||||||
|
Chain2(base1: self, base2: other)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+182
-239
@@ -10,26 +10,24 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
/// A collection wrapper that breaks a collection into chunks based on a
|
/// A collection wrapper that breaks a collection into chunks based on a
|
||||||
/// predicate.
|
/// predicate or projection.
|
||||||
///
|
public struct Chunked<Base: Collection, Subject> {
|
||||||
/// Call `lazy.chunked(by:)` on a collection to create an instance of this type.
|
|
||||||
public struct ChunkedByCollection<Base: Collection, Subject> {
|
|
||||||
/// The collection that this instance provides a view onto.
|
/// The collection that this instance provides a view onto.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
/// The projection function.
|
/// The projection function.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let projection: (Base.Element) -> Subject
|
internal let projection: (Base.Element) -> Subject
|
||||||
|
|
||||||
/// The predicate.
|
/// The predicate.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let belongInSameGroup: (Subject, Subject) -> Bool
|
internal let belongInSameGroup: (Subject, Subject) -> Bool
|
||||||
|
|
||||||
/// The end index of the first chunk.
|
/// The upper bound of the first chunk.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var endOfFirstChunk: Base.Index
|
internal var firstUpperBound: Base.Index
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(
|
internal init(
|
||||||
base: Base,
|
base: Base,
|
||||||
@@ -39,33 +37,33 @@ public struct ChunkedByCollection<Base: Collection, Subject> {
|
|||||||
self.base = base
|
self.base = base
|
||||||
self.projection = projection
|
self.projection = projection
|
||||||
self.belongInSameGroup = belongInSameGroup
|
self.belongInSameGroup = belongInSameGroup
|
||||||
self.endOfFirstChunk = base.startIndex
|
self.firstUpperBound = base.startIndex
|
||||||
|
|
||||||
if !base.isEmpty {
|
if !base.isEmpty {
|
||||||
endOfFirstChunk = endOfChunk(startingAt: base.startIndex)
|
firstUpperBound = endOfChunk(startingAt: base.startIndex)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ChunkedByCollection: Collection {
|
extension Chunked: LazyCollectionProtocol {
|
||||||
/// A position in a chunked collection.
|
/// A position in a chunked collection.
|
||||||
public struct Index: Comparable {
|
public struct Index: Comparable {
|
||||||
/// The range corresponding to the chunk at this position.
|
/// The range corresponding to the chunk at this position.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var baseRange: Range<Base.Index>
|
internal var baseRange: Range<Base.Index>
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(_ baseRange: Range<Base.Index>) {
|
internal init(_ baseRange: Range<Base.Index>) {
|
||||||
self.baseRange = baseRange
|
self.baseRange = baseRange
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public static func == (lhs: Index, rhs: Index) -> Bool {
|
public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||||
// Since each index represents the range of a disparate chunk, no two
|
// Since each index represents the range of a disparate chunk, no two
|
||||||
// unique indices will have the same lower bound.
|
// unique indices will have the same lower bound.
|
||||||
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
|
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||||
// Only use the lower bound to test for ordering, as above.
|
// Only use the lower bound to test for ordering, as above.
|
||||||
@@ -77,25 +75,21 @@ extension ChunkedByCollection: Collection {
|
|||||||
/// at the given index.
|
/// at the given index.
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func endOfChunk(startingAt start: Base.Index) -> Base.Index {
|
internal func endOfChunk(startingAt start: Base.Index) -> Base.Index {
|
||||||
var subject = projection(base[start])
|
let subject = projection(base[start])
|
||||||
|
return base[base.index(after: start)...]
|
||||||
return base[base.index(after: start)...].endOfPrefix(while: { element in
|
.endOfPrefix(while: { belongInSameGroup(subject, projection($0)) })
|
||||||
let nextSubject = projection(element)
|
|
||||||
defer { subject = nextSubject }
|
|
||||||
return belongInSameGroup(subject, nextSubject)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var startIndex: Index {
|
public var startIndex: Index {
|
||||||
Index(base.startIndex..<endOfFirstChunk)
|
Index(base.startIndex..<firstUpperBound)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var endIndex: Index {
|
public var endIndex: Index {
|
||||||
Index(base.endIndex..<base.endIndex)
|
Index(base.endIndex..<base.endIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(after i: Index) -> Index {
|
public func index(after i: Index) -> Index {
|
||||||
precondition(i != endIndex, "Can't advance past endIndex")
|
precondition(i != endIndex, "Can't advance past endIndex")
|
||||||
@@ -104,7 +98,7 @@ extension ChunkedByCollection: Collection {
|
|||||||
let end = endOfChunk(startingAt: upperBound)
|
let end = endOfChunk(startingAt: upperBound)
|
||||||
return Index(upperBound..<end)
|
return Index(upperBound..<end)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public subscript(position: Index) -> Base.SubSequence {
|
public subscript(position: Index) -> Base.SubSequence {
|
||||||
precondition(position != endIndex, "Can't subscript using endIndex")
|
precondition(position != endIndex, "Can't subscript using endIndex")
|
||||||
@@ -112,23 +106,20 @@ extension ChunkedByCollection: Collection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ChunkedByCollection.Index: Hashable where Base.Index: Hashable {}
|
extension Chunked.Index: Hashable where Base.Index: Hashable {}
|
||||||
|
|
||||||
extension ChunkedByCollection: BidirectionalCollection
|
extension Chunked: BidirectionalCollection
|
||||||
where Base: BidirectionalCollection
|
where Base: BidirectionalCollection {
|
||||||
{
|
|
||||||
/// Returns the index in the base collection of the start of the chunk ending
|
/// Returns the index in the base collection of the start of the chunk ending
|
||||||
/// at the given index.
|
/// at the given index.
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
|
internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
|
||||||
let indexBeforeEnd = base.index(before: end)
|
let indexBeforeEnd = base.index(before: end)
|
||||||
var subject = projection(base[indexBeforeEnd])
|
|
||||||
|
// Get the projected value of the last element in the range ending at `end`.
|
||||||
return base[..<indexBeforeEnd].startOfSuffix(while: { element in
|
let subject = projection(base[indexBeforeEnd])
|
||||||
let nextSubject = projection(element)
|
return base[..<indexBeforeEnd]
|
||||||
defer { subject = nextSubject }
|
.startOfSuffix(while: { belongInSameGroup(projection($0), subject) })
|
||||||
return belongInSameGroup(nextSubject, subject)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
@@ -139,70 +130,14 @@ extension ChunkedByCollection: BidirectionalCollection
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ChunkedByCollection: LazyCollectionProtocol {}
|
@available(*, deprecated, renamed: "Chunked")
|
||||||
|
public typealias LazyChunked<Base: Collection, Subject> = Chunked<Base, Subject>
|
||||||
/// A collection wrapper that breaks a collection into chunks based on a
|
|
||||||
/// predicate.
|
|
||||||
///
|
|
||||||
/// Call `lazy.chunked(on:)` on a collection to create an instance of this type.
|
|
||||||
public struct ChunkedOnCollection<Base: Collection, Subject: Equatable> {
|
|
||||||
@usableFromInline
|
|
||||||
internal var chunked: ChunkedByCollection<Base, Subject>
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(
|
|
||||||
base: Base,
|
|
||||||
projection: @escaping (Base.Element) -> Subject
|
|
||||||
) {
|
|
||||||
self.chunked = ChunkedByCollection(
|
|
||||||
base: base,
|
|
||||||
projection: projection,
|
|
||||||
belongInSameGroup: ==)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension ChunkedOnCollection: Collection {
|
|
||||||
public typealias Index = ChunkedByCollection<Base, Subject>.Index
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public var startIndex: Index {
|
|
||||||
chunked.startIndex
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public var endIndex: Index {
|
|
||||||
chunked.endIndex
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public subscript(position: Index) -> (Subject, Base.SubSequence) {
|
|
||||||
let subsequence = chunked[position]
|
|
||||||
let subject = chunked.projection(subsequence.first!)
|
|
||||||
return (subject, subsequence)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func index(after i: Index) -> Index {
|
|
||||||
chunked.index(after: i)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension ChunkedOnCollection: BidirectionalCollection
|
|
||||||
where Base: BidirectionalCollection
|
|
||||||
{
|
|
||||||
@inlinable
|
|
||||||
public func index(before i: Index) -> Index {
|
|
||||||
chunked.index(before: i)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension ChunkedOnCollection: LazyCollectionProtocol {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// lazy.chunked(by:) / lazy.chunked(on:)
|
// lazy.chunked(by:)
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
extension LazySequenceProtocol where Self: Collection, Elements: Collection {
|
extension LazyCollectionProtocol {
|
||||||
/// Returns a lazy collection of subsequences of this collection, chunked by
|
/// Returns a lazy collection of subsequences of this collection, chunked by
|
||||||
/// the given predicate.
|
/// the given predicate.
|
||||||
///
|
///
|
||||||
@@ -210,59 +145,74 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
|
|||||||
@inlinable
|
@inlinable
|
||||||
public func chunked(
|
public func chunked(
|
||||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||||
) -> ChunkedByCollection<Elements, Element> {
|
) -> Chunked<Elements, Element> {
|
||||||
ChunkedByCollection(
|
Chunked(
|
||||||
base: elements,
|
base: elements,
|
||||||
projection: { $0 },
|
projection: { $0 },
|
||||||
belongInSameGroup: belongInSameGroup)
|
belongInSameGroup: belongInSameGroup)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a lazy collection of subsequences of this collection, chunked by
|
/// Returns a lazy collection of subsequences of this collection, chunked by
|
||||||
/// grouping elements that project to the same value.
|
/// grouping elements that project to the same value.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(*n*), because the start index is pre-computed.
|
/// - Complexity: O(*n*), because the start index is pre-computed.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func chunked<Subject>(
|
public func chunked<Subject: Equatable>(
|
||||||
on projection: @escaping (Element) -> Subject
|
on projection: @escaping (Element) -> Subject
|
||||||
) -> ChunkedOnCollection<Elements, Subject> {
|
) -> Chunked<Elements, Subject> {
|
||||||
ChunkedOnCollection(
|
Chunked(
|
||||||
base: elements,
|
base: elements,
|
||||||
projection: projection)
|
projection: projection,
|
||||||
|
belongInSameGroup: ==)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// chunked(by:) / chunked(on:)
|
// chunked(by:)
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
extension Collection {
|
extension Collection {
|
||||||
/// Returns a collection of subsequences of this collection, chunked by the
|
/// Returns a collection of subsequences of this collection, chunked by
|
||||||
/// given predicate.
|
/// grouping elements that project to the same value according to the given
|
||||||
|
/// predicate.
|
||||||
|
///
|
||||||
|
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||||
|
@inlinable
|
||||||
|
internal func chunked<Subject>(
|
||||||
|
on projection: (Element) throws -> Subject,
|
||||||
|
by belongInSameGroup: (Subject, Subject) throws -> Bool
|
||||||
|
) rethrows -> [SubSequence] {
|
||||||
|
guard !isEmpty else { return [] }
|
||||||
|
var result: [SubSequence] = []
|
||||||
|
|
||||||
|
var start = startIndex
|
||||||
|
var subject = try projection(self[start])
|
||||||
|
|
||||||
|
for (index, element) in indexed().dropFirst() {
|
||||||
|
let nextSubject = try projection(element)
|
||||||
|
if try !belongInSameGroup(subject, nextSubject) {
|
||||||
|
result.append(self[start..<index])
|
||||||
|
start = index
|
||||||
|
subject = nextSubject
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if start != endIndex {
|
||||||
|
result.append(self[start..<endIndex])
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a collection of subsequences of this collection, chunked by
|
||||||
|
/// the given predicate.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func chunked(
|
public func chunked(
|
||||||
by belongInSameGroup: (Element, Element) throws -> Bool
|
by belongInSameGroup: (Element, Element) throws -> Bool
|
||||||
) rethrows -> [SubSequence] {
|
) rethrows -> [SubSequence] {
|
||||||
guard !isEmpty else { return [] }
|
try chunked(on: { $0 }, by: belongInSameGroup)
|
||||||
var result: [SubSequence] = []
|
|
||||||
|
|
||||||
var start = startIndex
|
|
||||||
var current = self[start]
|
|
||||||
|
|
||||||
for (index, element) in indexed().dropFirst() {
|
|
||||||
if try !belongInSameGroup(current, element) {
|
|
||||||
result.append(self[start..<index])
|
|
||||||
start = index
|
|
||||||
}
|
|
||||||
current = element
|
|
||||||
}
|
|
||||||
|
|
||||||
if start != endIndex {
|
|
||||||
result.append(self[start...])
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a collection of subsequences of this collection, chunked by
|
/// Returns a collection of subsequences of this collection, chunked by
|
||||||
@@ -272,27 +222,8 @@ extension Collection {
|
|||||||
@inlinable
|
@inlinable
|
||||||
public func chunked<Subject: Equatable>(
|
public func chunked<Subject: Equatable>(
|
||||||
on projection: (Element) throws -> Subject
|
on projection: (Element) throws -> Subject
|
||||||
) rethrows -> [(Subject, SubSequence)] {
|
) rethrows -> [SubSequence] {
|
||||||
guard !isEmpty else { return [] }
|
try chunked(on: projection, by: ==)
|
||||||
var result: [(Subject, SubSequence)] = []
|
|
||||||
|
|
||||||
var start = startIndex
|
|
||||||
var subject = try projection(self[start])
|
|
||||||
|
|
||||||
for (index, element) in indexed().dropFirst() {
|
|
||||||
let nextSubject = try projection(element)
|
|
||||||
if subject != nextSubject {
|
|
||||||
result.append((subject, self[start..<index]))
|
|
||||||
start = index
|
|
||||||
subject = nextSubject
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if start != endIndex {
|
|
||||||
result.append((subject, self[start...]))
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -300,52 +231,52 @@ extension Collection {
|
|||||||
// chunks(ofCount:)
|
// chunks(ofCount:)
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
/// A collection that presents the elements of its base collection in
|
/// A collection that presents the elements of its base collection
|
||||||
/// `SubSequence` chunks of any given count.
|
/// in `SubSequence` chunks of any given count.
|
||||||
///
|
///
|
||||||
/// A `ChunksOfCountCollection` is a lazy view on the base `Collection`, but it
|
/// A `ChunkedByCount` is a lazy view on the base Collection, but it does not implicitly confer
|
||||||
/// does not implicitly confer laziness on algorithms applied to its result. In
|
/// laziness on algorithms applied to its result. In other words, for ordinary collections `c`:
|
||||||
/// other words, for ordinary collections `c`:
|
|
||||||
///
|
///
|
||||||
/// * `c.chunks(ofCount: 3)` does not create new storage
|
/// * `c.chunks(ofCount: 3)` does not create new storage
|
||||||
/// * `c.chunks(ofCount: 3).map(f)` maps eagerly and returns a new array
|
/// * `c.chunks(ofCount: 3).map(f)` maps eagerly and returns a new array
|
||||||
/// * `c.lazy.chunks(ofCount: 3).map(f)` maps lazily and returns a
|
/// * `c.lazy.chunks(ofCount: 3).map(f)` maps lazily and returns a `LazyMapCollection`
|
||||||
/// `LazyMapCollection`
|
public struct ChunkedByCount<Base: Collection> {
|
||||||
public struct ChunksOfCountCollection<Base: Collection> {
|
|
||||||
public typealias Element = Base.SubSequence
|
public typealias Element = Base.SubSequence
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let chunkCount: Int
|
internal let chunkCount: Int
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal var endOfFirstChunk: Base.Index
|
|
||||||
|
|
||||||
/// Creates a view instance that presents the elements of `base` in
|
@usableFromInline
|
||||||
/// `SubSequence` chunks of the given count.
|
internal var startUpperBound: Base.Index
|
||||||
|
|
||||||
|
/// Creates a view instance that presents the elements of `base`
|
||||||
|
/// in `SubSequence` chunks of the given count.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(*n*), because the start index is pre-computed.
|
/// - Complexity: O(*n*), because the start index is pre-computed.
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(_base: Base, _chunkCount: Int) {
|
internal init(_base: Base, _chunkCount: Int) {
|
||||||
self.base = _base
|
self.base = _base
|
||||||
self.chunkCount = _chunkCount
|
self.chunkCount = _chunkCount
|
||||||
|
|
||||||
// Compute the start index upfront in order to make start index a O(1)
|
// Compute the start index upfront in order to make
|
||||||
// lookup.
|
// start index a O(1) lookup.
|
||||||
self.endOfFirstChunk = _base.index(
|
self.startUpperBound =
|
||||||
_base.startIndex, offsetBy: _chunkCount,
|
_base.index(
|
||||||
limitedBy: _base.endIndex
|
_base.startIndex, offsetBy: _chunkCount,
|
||||||
) ?? _base.endIndex
|
limitedBy: _base.endIndex
|
||||||
|
) ?? _base.endIndex
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ChunksOfCountCollection: Collection {
|
extension ChunkedByCount: Collection {
|
||||||
public struct Index {
|
public struct Index {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let baseRange: Range<Base.Index>
|
internal let baseRange: Range<Base.Index>
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(_baseRange: Range<Base.Index>) {
|
internal init(_baseRange: Range<Base.Index>) {
|
||||||
self.baseRange = _baseRange
|
self.baseRange = _baseRange
|
||||||
@@ -355,53 +286,57 @@ extension ChunksOfCountCollection: Collection {
|
|||||||
/// - Complexity: O(1)
|
/// - Complexity: O(1)
|
||||||
@inlinable
|
@inlinable
|
||||||
public var startIndex: Index {
|
public var startIndex: Index {
|
||||||
Index(_baseRange: base.startIndex..<endOfFirstChunk)
|
Index(_baseRange: base.startIndex..<startUpperBound)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var endIndex: Index {
|
public var endIndex: Index {
|
||||||
Index(_baseRange: base.endIndex..<base.endIndex)
|
Index(_baseRange: base.endIndex..<base.endIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// - Complexity: O(1)
|
/// - Complexity: O(1)
|
||||||
@inlinable
|
@inlinable
|
||||||
public subscript(i: Index) -> Element {
|
public subscript(i: Index) -> Element {
|
||||||
precondition(i != endIndex, "Index out of range")
|
precondition(i < endIndex, "Index out of range")
|
||||||
return base[i.baseRange]
|
return base[i.baseRange]
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(after i: Index) -> Index {
|
public func index(after i: Index) -> Index {
|
||||||
precondition(i != endIndex, "Advancing past end index")
|
precondition(i < endIndex, "Advancing past end index")
|
||||||
let baseIdx = base.index(
|
let baseIdx =
|
||||||
i.baseRange.upperBound, offsetBy: chunkCount,
|
base.index(
|
||||||
limitedBy: base.endIndex
|
i.baseRange.upperBound, offsetBy: chunkCount,
|
||||||
) ?? base.endIndex
|
limitedBy: base.endIndex
|
||||||
|
) ?? base.endIndex
|
||||||
return Index(_baseRange: i.baseRange.upperBound..<baseIdx)
|
return Index(_baseRange: i.baseRange.upperBound..<baseIdx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ChunksOfCountCollection.Index: Comparable {
|
extension ChunkedByCount.Index: Comparable {
|
||||||
@inlinable
|
@inlinable
|
||||||
public static func == (lhs: ChunksOfCountCollection.Index,
|
public static func == (
|
||||||
rhs: ChunksOfCountCollection.Index) -> Bool {
|
lhs: ChunkedByCount.Index,
|
||||||
|
rhs: ChunkedByCount.Index
|
||||||
|
) -> Bool {
|
||||||
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
|
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public static func < (lhs: ChunksOfCountCollection.Index,
|
public static func < (
|
||||||
rhs: ChunksOfCountCollection.Index) -> Bool {
|
lhs: ChunkedByCount.Index,
|
||||||
|
rhs: ChunkedByCount.Index
|
||||||
|
) -> Bool {
|
||||||
lhs.baseRange.lowerBound < rhs.baseRange.lowerBound
|
lhs.baseRange.lowerBound < rhs.baseRange.lowerBound
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ChunksOfCountCollection:
|
extension ChunkedByCount:
|
||||||
BidirectionalCollection, RandomAccessCollection
|
BidirectionalCollection, RandomAccessCollection
|
||||||
where Base: RandomAccessCollection {
|
where Base: RandomAccessCollection {
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(before i: Index) -> Index {
|
public func index(before i: Index) -> Index {
|
||||||
precondition(i != startIndex, "Advancing past start index")
|
precondition(i > startIndex, "Advancing past start index")
|
||||||
|
|
||||||
var offset = chunkCount
|
var offset = chunkCount
|
||||||
if i.baseRange.lowerBound == base.endIndex {
|
if i.baseRange.lowerBound == base.endIndex {
|
||||||
let remainder = base.count % chunkCount
|
let remainder = base.count % chunkCount
|
||||||
@@ -409,21 +344,23 @@ where Base: RandomAccessCollection {
|
|||||||
offset = remainder
|
offset = remainder
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let baseIdx = base.index(
|
let baseIdx =
|
||||||
i.baseRange.lowerBound, offsetBy: -offset,
|
base.index(
|
||||||
limitedBy: base.startIndex
|
i.baseRange.lowerBound, offsetBy: -offset,
|
||||||
) ?? base.startIndex
|
limitedBy: base.startIndex
|
||||||
|
) ?? base.startIndex
|
||||||
return Index(_baseRange: baseIdx..<i.baseRange.lowerBound)
|
return Index(_baseRange: baseIdx..<i.baseRange.lowerBound)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ChunksOfCountCollection {
|
extension ChunkedByCount {
|
||||||
@inlinable
|
@inlinable
|
||||||
public func distance(from start: Index, to end: Index) -> Int {
|
public func distance(from start: Index, to end: Index) -> Int {
|
||||||
let distance =
|
let distance =
|
||||||
base.distance(from: start.baseRange.lowerBound,
|
base.distance(
|
||||||
to: end.baseRange.lowerBound)
|
from: start.baseRange.lowerBound,
|
||||||
|
to: end.baseRange.lowerBound)
|
||||||
let (quotient, remainder) =
|
let (quotient, remainder) =
|
||||||
distance.quotientAndRemainder(dividingBy: chunkCount)
|
distance.quotientAndRemainder(dividingBy: chunkCount)
|
||||||
return quotient + remainder.signum()
|
return quotient + remainder.signum()
|
||||||
@@ -435,14 +372,14 @@ extension ChunksOfCountCollection {
|
|||||||
base.count.quotientAndRemainder(dividingBy: chunkCount)
|
base.count.quotientAndRemainder(dividingBy: chunkCount)
|
||||||
return quotient + remainder.signum()
|
return quotient + remainder.signum()
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(
|
public func index(
|
||||||
_ i: Index, offsetBy offset: Int, limitedBy limit: Index
|
_ i: Index, offsetBy offset: Int, limitedBy limit: Index
|
||||||
) -> Index? {
|
) -> Index? {
|
||||||
guard offset != 0 else { return i }
|
guard offset != 0 else { return i }
|
||||||
guard limit != i else { return nil }
|
guard limit != i else { return nil }
|
||||||
|
|
||||||
if offset > 0 {
|
if offset > 0 {
|
||||||
return limit > i
|
return limit > i
|
||||||
? offsetForward(i, offsetBy: offset, limit: limit)
|
? offsetForward(i, offsetBy: offset, limit: limit)
|
||||||
@@ -457,16 +394,17 @@ extension ChunksOfCountCollection {
|
|||||||
@inlinable
|
@inlinable
|
||||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||||
guard distance != 0 else { return i }
|
guard distance != 0 else { return i }
|
||||||
|
|
||||||
let idx = distance > 0
|
let idx =
|
||||||
? offsetForward(i, offsetBy: distance)
|
distance > 0
|
||||||
: offsetBackward(i, offsetBy: distance)
|
? offsetForward(i, offsetBy: distance)
|
||||||
|
: offsetBackward(i, offsetBy: distance)
|
||||||
guard let index = idx else {
|
guard let index = idx else {
|
||||||
fatalError("Out of bounds")
|
fatalError("Out of bounds")
|
||||||
}
|
}
|
||||||
return index
|
return index
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetForward(
|
internal func offsetForward(
|
||||||
_ i: Index, offsetBy distance: Int, limit: Index? = nil
|
_ i: Index, offsetBy distance: Int, limit: Index? = nil
|
||||||
@@ -479,7 +417,7 @@ extension ChunksOfCountCollection {
|
|||||||
limit: limit, by: >
|
limit: limit, by: >
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convenience to compute offset backward base distance.
|
// Convenience to compute offset backward base distance.
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func computeOffsetBackwardBaseDistance(
|
internal func computeOffsetBackwardBaseDistance(
|
||||||
@@ -489,30 +427,30 @@ extension ChunksOfCountCollection {
|
|||||||
let remainder = base.count % chunkCount
|
let remainder = base.count % chunkCount
|
||||||
// We have to take it into account when calculating offsets.
|
// We have to take it into account when calculating offsets.
|
||||||
if remainder != 0 {
|
if remainder != 0 {
|
||||||
// Distance "minus" one (at this point distance is negative) because we
|
// Distance "minus" one(at this point distance is negative)
|
||||||
// need to adjust for the last position that have a variadic (remainder)
|
// because we need to adjust for the last position that have
|
||||||
// number of elements.
|
// a variadic(remainder) number of elements.
|
||||||
return ((distance + 1) * chunkCount) - remainder
|
return ((distance + 1) * chunkCount) - remainder
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return distance * chunkCount
|
return distance * chunkCount
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetBackward(
|
internal func offsetBackward(
|
||||||
_ i: Index, offsetBy distance: Int, limit: Index? = nil
|
_ i: Index, offsetBy distance: Int, limit: Index? = nil
|
||||||
) -> Index? {
|
) -> Index? {
|
||||||
assert(distance < 0)
|
assert(distance < 0)
|
||||||
let baseDistance =
|
let baseDistance =
|
||||||
computeOffsetBackwardBaseDistance(i, distance)
|
computeOffsetBackwardBaseDistance(i, distance)
|
||||||
return makeOffsetIndex(
|
return makeOffsetIndex(
|
||||||
from: i, baseBound: base.startIndex,
|
from: i, baseBound: base.startIndex,
|
||||||
distance: distance, baseDistance: baseDistance,
|
distance: distance, baseDistance: baseDistance,
|
||||||
limit: limit, by: <
|
limit: limit, by: <
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper to compute `index(offsetBy:)` index.
|
// Helper to compute index(offsetBy:) index.
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func makeOffsetIndex(
|
internal func makeOffsetIndex(
|
||||||
from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int,
|
from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int,
|
||||||
@@ -522,15 +460,16 @@ extension ChunksOfCountCollection {
|
|||||||
i.baseRange.lowerBound, offsetBy: baseDistance,
|
i.baseRange.lowerBound, offsetBy: baseDistance,
|
||||||
limitedBy: baseBound
|
limitedBy: baseBound
|
||||||
)
|
)
|
||||||
|
|
||||||
if let limit = limit {
|
if let limit = limit {
|
||||||
if baseIdx == nil {
|
if baseIdx == nil {
|
||||||
// If we passed the bounds while advancing forward, and the limit is the
|
// If we past the bounds while advancing forward and the
|
||||||
// `endIndex`, since the computation on `base` don't take into account
|
// limit is the `endIndex`, since the computation on base
|
||||||
// the remainder, we have to make sure that passing the bound was
|
// don't take into account the remainder, we have to make
|
||||||
// because of the distance not just because of a remainder. Special
|
// sure that passing the bound was because of the distance
|
||||||
// casing is less expensive than always using `count` (which could be
|
// not just because of a remainder. Special casing is less
|
||||||
// O(n) for non-random access collection base) to compute the base
|
// expensive than always use count(which could be O(n) for
|
||||||
|
// non-random access collection base) to compute the base
|
||||||
// distance taking remainder into account.
|
// distance taking remainder into account.
|
||||||
if baseDistance > 0 && limit == endIndex {
|
if baseDistance > 0 && limit == endIndex {
|
||||||
if self.distance(from: i, to: limit) < distance {
|
if self.distance(from: i, to: limit) < distance {
|
||||||
@@ -547,24 +486,25 @@ extension ChunksOfCountCollection {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let baseStartIdx = baseIdx ?? baseBound
|
let baseStartIdx = baseIdx ?? baseBound
|
||||||
let baseEndIdx = base.index(
|
let baseEndIdx =
|
||||||
baseStartIdx, offsetBy: chunkCount, limitedBy: base.endIndex
|
base.index(
|
||||||
) ?? base.endIndex
|
baseStartIdx, offsetBy: chunkCount, limitedBy: base.endIndex
|
||||||
|
) ?? base.endIndex
|
||||||
|
|
||||||
return Index(_baseRange: baseStartIdx..<baseEndIdx)
|
return Index(_baseRange: baseStartIdx..<baseEndIdx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Collection {
|
extension Collection {
|
||||||
/// Returns a `ChunksOfCountCollection<Self>` view presenting the elements in
|
/// Returns a `ChunkedCollection<Self>` view presenting the elements
|
||||||
/// chunks with count of the given count parameter.
|
/// in chunks with count of the given count parameter.
|
||||||
///
|
///
|
||||||
/// - Parameter count: The size of the chunks. If the `count` parameter is
|
/// - Parameter size: The size of the chunks. If the count parameter
|
||||||
/// evenly divided by the count of the base `Collection` all the chunks will
|
/// is evenly divided by the count of the base `Collection` all the
|
||||||
/// have the count equals to size. Otherwise, the last chunk will contain
|
/// chunks will have the count equals to size.
|
||||||
/// the remaining elements.
|
/// Otherwise, the last chunk will contain the remaining elements.
|
||||||
///
|
///
|
||||||
/// let c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
/// let c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||||
/// print(c.chunks(ofCount: 5).map(Array.init))
|
/// print(c.chunks(ofCount: 5).map(Array.init))
|
||||||
@@ -575,13 +515,16 @@ extension Collection {
|
|||||||
///
|
///
|
||||||
/// - Complexity: O(*n*), because the start index is pre-computed.
|
/// - Complexity: O(*n*), because the start index is pre-computed.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func chunks(ofCount count: Int) -> ChunksOfCountCollection<Self> {
|
public func chunks(ofCount count: Int) -> ChunkedByCount<Self> {
|
||||||
precondition(count > 0, "Cannot chunk with count <= 0!")
|
precondition(count > 0, "Cannot chunk with count <= 0!")
|
||||||
return ChunksOfCountCollection(_base: self, _chunkCount: count)
|
return ChunkedByCount(_base: self, _chunkCount: count)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ChunksOfCountCollection.Index: Hashable where Base.Index: Hashable {}
|
extension ChunkedByCount.Index: Hashable where Base.Index: Hashable {}
|
||||||
|
|
||||||
extension ChunksOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol
|
// Lazy conditional conformance.
|
||||||
where Base: LazySequenceProtocol {}
|
extension ChunkedByCount: LazySequenceProtocol
|
||||||
|
where Base: LazySequenceProtocol {}
|
||||||
|
extension ChunkedByCount: LazyCollectionProtocol
|
||||||
|
where Base: LazyCollectionProtocol {}
|
||||||
@@ -10,24 +10,21 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
/// A collection wrapper that generates combinations of a base collection.
|
/// A collection wrapper that generates combinations of a base collection.
|
||||||
public struct CombinationsSequence<Base: Collection> {
|
public struct Combinations<Base: Collection> {
|
||||||
/// The collection to iterate over for combinations.
|
/// The collection to iterate over for combinations.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let baseCount: Int
|
internal let baseCount: Int
|
||||||
|
|
||||||
/// The range of accepted sizes of combinations.
|
/// The range of accepted sizes of combinations.
|
||||||
///
|
|
||||||
/// - Note: This may be `nil` if the attempted range entirely exceeds the
|
/// - Note: This may be `nil` if the attempted range entirely exceeds the
|
||||||
/// upper bounds of the size of the `base` collection.
|
/// upper bounds of the size of the `base` collection.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let kRange: Range<Int>?
|
internal let kRange: Range<Int>?
|
||||||
|
|
||||||
/// Initializes a `CombinationsSequence` for all combinations of `base` of
|
/// Initializes a `Combinations` for all combinations of `base` of size `k`.
|
||||||
/// size `k`.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - base: The collection to iterate over for combinations.
|
/// - base: The collection to iterate over for combinations.
|
||||||
/// - k: The expected size of each combination.
|
/// - k: The expected size of each combination.
|
||||||
@@ -35,10 +32,9 @@ public struct CombinationsSequence<Base: Collection> {
|
|||||||
internal init(_ base: Base, k: Int) {
|
internal init(_ base: Base, k: Int) {
|
||||||
self.init(base, kRange: k...k)
|
self.init(base, kRange: k...k)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Initializes a `CombinationsSequence` for all combinations of `base` of
|
/// Initializes a `Combinations` for all combinations of `base` of sizes
|
||||||
/// sizes within a given range.
|
/// within a given range.
|
||||||
///
|
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - base: The collection to iterate over for combinations.
|
/// - base: The collection to iterate over for combinations.
|
||||||
/// - kRange: The range of accepted sizes of combinations.
|
/// - kRange: The range of accepted sizes of combinations.
|
||||||
@@ -51,20 +47,21 @@ public struct CombinationsSequence<Base: Collection> {
|
|||||||
let baseCount = base.count
|
let baseCount = base.count
|
||||||
self.baseCount = baseCount
|
self.baseCount = baseCount
|
||||||
let upperBound = baseCount + 1
|
let upperBound = baseCount + 1
|
||||||
self.kRange = range.lowerBound < upperBound
|
self.kRange =
|
||||||
? range.clamped(to: 0 ..< upperBound)
|
range.lowerBound < upperBound
|
||||||
|
? range.clamped(to: 0..<upperBound)
|
||||||
: nil
|
: nil
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The total number of combinations.
|
/// The total number of combinations.
|
||||||
@inlinable
|
@inlinable
|
||||||
public var count: Int {
|
public var count: Int {
|
||||||
guard let k = self.kRange else { return 0 }
|
guard let k = self.kRange else { return 0 }
|
||||||
let n = baseCount
|
let n = baseCount
|
||||||
if k == 0 ..< (n + 1) {
|
if k == 0..<(n + 1) {
|
||||||
return 1 << n
|
return 1 << n
|
||||||
}
|
}
|
||||||
|
|
||||||
func binomial(n: Int, k: Int) -> Int {
|
func binomial(n: Int, k: Int) -> Int {
|
||||||
switch k {
|
switch k {
|
||||||
case n, 0: return 1
|
case n, 0: return 1
|
||||||
@@ -73,43 +70,42 @@ public struct CombinationsSequence<Base: Collection> {
|
|||||||
default: return n * binomial(n: n - 1, k: k - 1) / k
|
default: return n * binomial(n: n - 1, k: k - 1) / k
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return k.map {
|
return k.map {
|
||||||
binomial(n: n, k: $0)
|
binomial(n: n, k: $0)
|
||||||
}.reduce(0, +)
|
}.reduce(0, +)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension CombinationsSequence: Sequence {
|
extension Combinations: Sequence {
|
||||||
/// The iterator for a `CombinationsSequence` instance.
|
/// The iterator for a `Combinations` instance.
|
||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
/// The current range of accepted sizes of combinations.
|
/// The current range of accepted sizes of combinations.
|
||||||
///
|
|
||||||
/// - Note: The range is contracted until empty while iterating over
|
/// - Note: The range is contracted until empty while iterating over
|
||||||
/// combinations of different sizes. When the range is empty, iteration is
|
/// combinations of different sizes. When the range is empty, iteration is
|
||||||
/// finished.
|
/// finished.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var kRange: Range<Int>
|
internal var kRange: Range<Int>
|
||||||
|
|
||||||
/// Whether or not iteration is finished (`kRange` is empty)
|
/// Whether or not iteration is finished (`kRange` is empty)
|
||||||
@inlinable
|
@inlinable
|
||||||
internal var isFinished: Bool {
|
internal var isFinished: Bool {
|
||||||
return kRange.isEmpty
|
return kRange.isEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var indexes: [Base.Index]
|
internal var indexes: [Base.Index]
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(_ combinations: CombinationsSequence) {
|
internal init(_ combinations: Combinations) {
|
||||||
self.base = combinations.base
|
self.base = combinations.base
|
||||||
self.kRange = combinations.kRange ?? 0..<0
|
self.kRange = combinations.kRange ?? 0..<0
|
||||||
self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound))
|
self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Advances the current indices to the next set of combinations. If
|
/// Advances the current indices to the next set of combinations. If
|
||||||
/// `indexes.count == 3` and `base.count == 5`, the indices advance like
|
/// `indexes.count == 3` and `base.count == 5`, the indices advance like
|
||||||
/// this:
|
/// this:
|
||||||
@@ -135,12 +131,12 @@ extension CombinationsSequence: Sequence {
|
|||||||
func advanceKRange() {
|
func advanceKRange() {
|
||||||
if kRange.lowerBound < kRange.upperBound {
|
if kRange.lowerBound < kRange.upperBound {
|
||||||
let advancedLowerBound = kRange.lowerBound + 1
|
let advancedLowerBound = kRange.lowerBound + 1
|
||||||
kRange = advancedLowerBound ..< kRange.upperBound
|
kRange = advancedLowerBound..<kRange.upperBound
|
||||||
indexes.removeAll(keepingCapacity: true)
|
indexes.removeAll(keepingCapacity: true)
|
||||||
indexes.append(contentsOf: base.indices.prefix(kRange.lowerBound))
|
indexes.append(contentsOf: base.indices.prefix(kRange.lowerBound))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
guard !indexes.isEmpty else {
|
guard !indexes.isEmpty else {
|
||||||
// Initial state for combinations of 0 elements is an empty array with
|
// Initial state for combinations of 0 elements is an empty array with
|
||||||
// `finished == false`. Even though no indexes are involved, advancing
|
// `finished == false`. Even though no indexes are involved, advancing
|
||||||
@@ -148,11 +144,11 @@ extension CombinationsSequence: Sequence {
|
|||||||
advanceKRange()
|
advanceKRange()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
let i = indexes.count - 1
|
let i = indexes.count - 1
|
||||||
base.formIndex(after: &indexes[i])
|
base.formIndex(after: &indexes[i])
|
||||||
if indexes[i] != base.endIndex { return }
|
if indexes[i] != base.endIndex { return }
|
||||||
|
|
||||||
var j = i
|
var j = i
|
||||||
while indexes[i] == base.endIndex {
|
while indexes[i] == base.endIndex {
|
||||||
j -= 1
|
j -= 1
|
||||||
@@ -161,7 +157,7 @@ extension CombinationsSequence: Sequence {
|
|||||||
advanceKRange()
|
advanceKRange()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
base.formIndex(after: &indexes[j])
|
base.formIndex(after: &indexes[j])
|
||||||
for k in indexes.indices[(j + 1)...] {
|
for k in indexes.indices[(j + 1)...] {
|
||||||
indexes[k] = base.index(after: indexes[k - 1])
|
indexes[k] = base.index(after: indexes[k - 1])
|
||||||
@@ -171,7 +167,7 @@ extension CombinationsSequence: Sequence {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public mutating func next() -> [Base.Element]? {
|
public mutating func next() -> [Base.Element]? {
|
||||||
guard !isFinished else { return nil }
|
guard !isFinished else { return nil }
|
||||||
@@ -179,15 +175,13 @@ extension CombinationsSequence: Sequence {
|
|||||||
return indexes.map { i in base[i] }
|
return indexes.map { i in base[i] }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func makeIterator() -> Iterator {
|
public func makeIterator() -> Iterator {
|
||||||
Iterator(self)
|
Iterator(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension CombinationsSequence: LazySequenceProtocol
|
extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||||
where Base: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// combinations(ofCount:)
|
// combinations(ofCount:)
|
||||||
@@ -250,18 +244,18 @@ extension Collection {
|
|||||||
/// limited range is empty, the resulting sequence has no elements.
|
/// limited range is empty, the resulting sequence has no elements.
|
||||||
///
|
///
|
||||||
/// - Parameter kRange: The range of numbers of elements to include in each
|
/// - Parameter kRange: The range of numbers of elements to include in each
|
||||||
/// combination.
|
/// combination.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||||
/// is the number of elements in the base collection, since
|
/// is the number of elements in the base collection, since `Combinations`
|
||||||
/// `CombinationsSequence` accesses the `count` of the base collection.
|
/// accesses the `count` of the base collection.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func combinations<R: RangeExpression>(
|
public func combinations<R: RangeExpression>(
|
||||||
ofCount kRange: R
|
ofCount kRange: R
|
||||||
) -> CombinationsSequence<Self> where R.Bound == Int {
|
) -> Combinations<Self> where R.Bound == Int {
|
||||||
CombinationsSequence(self, kRange: kRange)
|
return Combinations(self, kRange: kRange)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a collection of combinations of this collection's elements, with
|
/// Returns a collection of combinations of this collection's elements, with
|
||||||
/// each combination having the specified number of elements.
|
/// each combination having the specified number of elements.
|
||||||
///
|
///
|
||||||
@@ -289,11 +283,11 @@ extension Collection {
|
|||||||
/// - Parameter k: The number of elements to include in each combination.
|
/// - Parameter k: The number of elements to include in each combination.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||||
/// is the number of elements in the base collection, since
|
/// is the number of elements in the base collection, since `Combinations`
|
||||||
/// `CombinationsSequence` accesses the `count` of the base collection.
|
/// accesses the `count` of the base collection.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func combinations(ofCount k: Int) -> CombinationsSequence<Self> {
|
public func combinations(ofCount k: Int) -> Combinations<Self> {
|
||||||
precondition(k >= 0, "Can't have combinations with a negative number of elements.")
|
precondition(k >= 0, "Can't have combinations with a negative number of elements.")
|
||||||
return CombinationsSequence(self, k: k)
|
return Combinations(self, k: k)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,14 +9,13 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
/// A `Sequence` that iterates over every non-nil element from the original
|
/// A `Sequence` that iterates over every non-nil element from the original `Sequence`.
|
||||||
/// `Sequence`.
|
|
||||||
public struct CompactedSequence<Base: Sequence, Element>: Sequence
|
public struct CompactedSequence<Base: Sequence, Element>: Sequence
|
||||||
where Base.Element == Element? {
|
where Base.Element == Element? {
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
let base: Base
|
let base: Base
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
init(base: Base) {
|
init(base: Base) {
|
||||||
self.base = base
|
self.base = base
|
||||||
@@ -25,12 +24,12 @@ public struct CompactedSequence<Base: Sequence, Element>: Sequence
|
|||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
var base: Base.Iterator
|
var base: Base.Iterator
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
init(base: Base.Iterator) {
|
init(base: Base.Iterator) {
|
||||||
self.base = base
|
self.base = base
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public mutating func next() -> Element? {
|
public mutating func next() -> Element? {
|
||||||
while let wrapped = base.next() {
|
while let wrapped = base.next() {
|
||||||
@@ -43,15 +42,14 @@ public struct CompactedSequence<Base: Sequence, Element>: Sequence
|
|||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func makeIterator() -> Iterator {
|
public func makeIterator() -> Iterator {
|
||||||
Iterator(base: base.makeIterator())
|
return Iterator(base: base.makeIterator())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Sequence {
|
extension Sequence {
|
||||||
/// Returns a new `Sequence` that iterates over every non-nil element from the
|
/// Returns a new `Sequence` that iterates over every non-nil element
|
||||||
/// original `Sequence`.
|
/// from the original `Sequence`.
|
||||||
///
|
/// It produces the same result as `c.compactMap { $0 }`.
|
||||||
/// Produces the same result as `c.compactMap { $0 }`.
|
|
||||||
///
|
///
|
||||||
/// let c = [1, nil, 2, 3, nil]
|
/// let c = [1, nil, 2, 3, nil]
|
||||||
/// for num in c.compacted() {
|
/// for num in c.compacted() {
|
||||||
@@ -68,88 +66,89 @@ extension Sequence {
|
|||||||
/// Complexity: O(1)
|
/// Complexity: O(1)
|
||||||
@inlinable
|
@inlinable
|
||||||
public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
|
public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
|
||||||
where Element == Unwrapped? {
|
where Element == Unwrapped? {
|
||||||
CompactedSequence(base: self)
|
CompactedSequence(base: self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A `Collection` that iterates over every non-nil element from the original
|
/// A `Collection` that iterates over every non-nil element from the original `Collection`.
|
||||||
/// `Collection`.
|
|
||||||
public struct CompactedCollection<Base: Collection, Element>: Collection
|
public struct CompactedCollection<Base: Collection, Element>: Collection
|
||||||
where Base.Element == Element? {
|
where Base.Element == Element? {
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
let base: Base
|
let base: Base
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
init(base: Base) {
|
init(base: Base) {
|
||||||
self.base = base
|
self.base = base
|
||||||
let idx = base.firstIndex(where: { $0 != nil }) ?? base.endIndex
|
let idx = base.firstIndex(where: { $0 != nil }) ?? base.endIndex
|
||||||
self.startIndex = Index(base: idx)
|
self.startIndex = Index(base: idx)
|
||||||
}
|
}
|
||||||
|
|
||||||
public struct Index {
|
public struct Index {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
let base: Base.Index
|
let base: Base.Index
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
init(base: Base.Index) {
|
init(base: Base.Index) {
|
||||||
self.base = base
|
self.base = base
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public var startIndex: Index
|
public var startIndex: Index
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var endIndex: Index { Index(base: base.endIndex) }
|
public var endIndex: Index { Index(base: base.endIndex) }
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public subscript(position: Index) -> Element {
|
public subscript(position: Index) -> Element {
|
||||||
base[position.base]!
|
base[position.base]!
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(after i: Index) -> Index {
|
public func index(after i: Index) -> Index {
|
||||||
precondition(i != endIndex, "Index out of bounds")
|
precondition(i != endIndex, "Index out of bounds")
|
||||||
|
|
||||||
let baseIdx = base.index(after: i.base)
|
let baseIdx = base.index(after: i.base)
|
||||||
guard let idx = base[baseIdx...].firstIndex(where: { $0 != nil })
|
guard let idx = base[baseIdx...].firstIndex(where: { $0 != nil })
|
||||||
else { return endIndex }
|
else { return endIndex }
|
||||||
return Index(base: idx)
|
return Index(base: idx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension CompactedCollection: BidirectionalCollection
|
extension CompactedCollection: BidirectionalCollection
|
||||||
where Base: BidirectionalCollection {
|
where Base: BidirectionalCollection {
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(before i: Index) -> Index {
|
public func index(before i: Index) -> Index {
|
||||||
precondition(i != startIndex, "Index out of bounds")
|
precondition(i != startIndex, "Index out of bounds")
|
||||||
|
|
||||||
guard let idx =
|
guard
|
||||||
base[startIndex.base..<i.base]
|
let idx =
|
||||||
.lastIndex(where: { $0 != nil })
|
base[startIndex.base..<i.base]
|
||||||
else { fatalError("Index out of bounds") }
|
.lastIndex(where: { $0 != nil })
|
||||||
|
else { fatalError("Index out of bounds") }
|
||||||
return Index(base: idx)
|
return Index(base: idx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension CompactedCollection.Index: Comparable {
|
extension CompactedCollection.Index: Comparable {
|
||||||
@inlinable
|
@inlinable
|
||||||
public static func < (lhs: CompactedCollection.Index,
|
public static func < (
|
||||||
rhs: CompactedCollection.Index) -> Bool {
|
lhs: CompactedCollection.Index,
|
||||||
|
rhs: CompactedCollection.Index
|
||||||
|
) -> Bool {
|
||||||
lhs.base < rhs.base
|
lhs.base < rhs.base
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension CompactedCollection.Index: Hashable
|
extension CompactedCollection.Index: Hashable
|
||||||
where Base.Index: Hashable {}
|
where Base.Index: Hashable {}
|
||||||
|
|
||||||
extension Collection {
|
extension Collection {
|
||||||
/// Returns a new `Collection` that iterates over every non-nil element from
|
/// Returns a new `Collection` that iterates over every non-nil element
|
||||||
/// the original `Collection`.
|
/// from the original `Collection`.
|
||||||
///
|
/// It produces the same result as `c.compactMap { $0 }`.
|
||||||
/// Produces the same result as `c.compactMap { $0 }`.
|
|
||||||
///
|
///
|
||||||
/// let c = [1, nil, 2, 3, nil]
|
/// let c = [1, nil, 2, 3, nil]
|
||||||
/// for num in c.compacted() {
|
/// for num in c.compacted() {
|
||||||
@@ -163,12 +162,11 @@ extension Collection {
|
|||||||
/// element and iterates over every non-nil element from the original
|
/// element and iterates over every non-nil element from the original
|
||||||
/// `Collection`.
|
/// `Collection`.
|
||||||
///
|
///
|
||||||
/// Complexity: O(*n*) where *n* is the number of elements in the
|
/// Complexity: O(*n*) where *n* is the number of elements in the
|
||||||
/// original `Collection`.
|
/// original `Collection`.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
|
public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
|
||||||
where Element == Unwrapped?
|
where Element == Unwrapped? {
|
||||||
{
|
|
||||||
CompactedCollection(base: self)
|
CompactedCollection(base: self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -178,7 +176,9 @@ extension Collection {
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
extension CompactedSequence: LazySequenceProtocol
|
extension CompactedSequence: LazySequenceProtocol
|
||||||
where Base: LazySequenceProtocol {}
|
where Base: LazySequenceProtocol {}
|
||||||
|
|
||||||
extension CompactedCollection: LazySequenceProtocol, LazyCollectionProtocol
|
extension CompactedCollection: LazySequenceProtocol
|
||||||
where Base: LazySequenceProtocol {}
|
where Base: LazySequenceProtocol {}
|
||||||
|
extension CompactedCollection: LazyCollectionProtocol
|
||||||
|
where Base: LazyCollectionProtocol {}
|
||||||
@@ -10,78 +10,80 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
/// A collection wrapper that repeats the elements of a base collection.
|
/// A collection wrapper that repeats the elements of a base collection.
|
||||||
public struct CycledSequence<Base: Collection> {
|
public struct Cycle<Base: Collection> {
|
||||||
/// The collection to repeat.
|
/// The collection to repeat.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(base: Base) {
|
internal init(base: Base) {
|
||||||
self.base = base
|
self.base = base
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension CycledSequence: Sequence {
|
extension Cycle: Sequence {
|
||||||
/// The iterator for a `CycledSequence` instance.
|
/// The iterator for a `Cycle` sequence.
|
||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var current: Base.Index
|
internal var current: Base.Index
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(base: Base) {
|
internal init(base: Base) {
|
||||||
self.base = base
|
self.base = base
|
||||||
self.current = base.startIndex
|
self.current = base.startIndex
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public mutating func next() -> Base.Element? {
|
public mutating func next() -> Base.Element? {
|
||||||
guard !base.isEmpty else { return nil }
|
guard !base.isEmpty else { return nil }
|
||||||
|
|
||||||
if current == base.endIndex {
|
if current == base.endIndex {
|
||||||
current = base.startIndex
|
current = base.startIndex
|
||||||
}
|
}
|
||||||
|
|
||||||
defer { base.formIndex(after: ¤t) }
|
defer { base.formIndex(after: ¤t) }
|
||||||
return base[current]
|
return base[current]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func makeIterator() -> Iterator {
|
public func makeIterator() -> Iterator {
|
||||||
Iterator(base: base)
|
Iterator(base: base)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension CycledSequence: LazySequenceProtocol
|
extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||||
where Base: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
/// A collection wrapper that repeats the elements of a base collection for a
|
/// A collection wrapper that repeats the elements of a base collection for a
|
||||||
/// finite number of times.
|
/// finite number of times.
|
||||||
public struct CycledTimesCollection<Base: Collection> {
|
public struct FiniteCycle<Base: Collection> {
|
||||||
/// A `Product2Sequence` instance for iterating the base collection.
|
/// A Product2 instance for iterating the Base collection.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let product: Product2Sequence<Range<Int>, Base>
|
internal let product: Product2<Range<Int>, Base>
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(base: Base, times: Int) {
|
internal init(base: Base, times: Int) {
|
||||||
self.product = Product2Sequence(0..<times, base)
|
self.product = Product2(0..<times, base)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension CycledTimesCollection: Collection {
|
extension FiniteCycle: LazySequenceProtocol, LazyCollectionProtocol
|
||||||
|
where Base: LazyCollectionProtocol {}
|
||||||
|
|
||||||
|
extension FiniteCycle: Collection {
|
||||||
|
|
||||||
public typealias Element = Base.Element
|
public typealias Element = Base.Element
|
||||||
|
|
||||||
public struct Index: Comparable {
|
public struct Index: Comparable {
|
||||||
/// The index corresponding to the `Product2Sequence` index at this
|
/// The index corresponding to the Product2 index at this position.
|
||||||
/// position.
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let productIndex: Product2Sequence<Range<Int>, Base>.Index
|
internal let productIndex: Product2<Range<Int>, Base>.Index
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(_ productIndex: Product2Sequence<Range<Int>, Base>.Index) {
|
internal init(_ productIndex: Product2<Range<Int>, Base>.Index) {
|
||||||
self.productIndex = productIndex
|
self.productIndex = productIndex
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,11 +136,14 @@ extension CycledTimesCollection: Collection {
|
|||||||
offsetBy distance: Int,
|
offsetBy distance: Int,
|
||||||
limitedBy limit: Index
|
limitedBy limit: Index
|
||||||
) -> Index? {
|
) -> Index? {
|
||||||
guard let productIndex = product.index(
|
guard
|
||||||
i.productIndex,
|
let productIndex = product.index(
|
||||||
offsetBy: distance,
|
i.productIndex,
|
||||||
limitedBy: limit.productIndex)
|
offsetBy: distance,
|
||||||
else { return nil }
|
limitedBy: limit.productIndex)
|
||||||
|
else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
return Index(productIndex)
|
return Index(productIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,8 +153,8 @@ extension CycledTimesCollection: Collection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension CycledTimesCollection: BidirectionalCollection
|
extension FiniteCycle: BidirectionalCollection
|
||||||
where Base: BidirectionalCollection {
|
where Base: BidirectionalCollection {
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(before i: Index) -> Index {
|
public func index(before i: Index) -> Index {
|
||||||
let productIndex = product.index(before: i.productIndex)
|
let productIndex = product.index(before: i.productIndex)
|
||||||
@@ -157,11 +162,8 @@ extension CycledTimesCollection: BidirectionalCollection
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension CycledTimesCollection: RandomAccessCollection
|
extension FiniteCycle: RandomAccessCollection
|
||||||
where Base: RandomAccessCollection {}
|
where Base: RandomAccessCollection {}
|
||||||
|
|
||||||
extension CycledTimesCollection: LazySequenceProtocol, LazyCollectionProtocol
|
|
||||||
where Base: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// cycled()
|
// cycled()
|
||||||
@@ -194,10 +196,10 @@ extension Collection {
|
|||||||
///
|
///
|
||||||
/// - Complexity: O(1)
|
/// - Complexity: O(1)
|
||||||
@inlinable
|
@inlinable
|
||||||
public func cycled() -> CycledSequence<Self> {
|
public func cycled() -> Cycle<Self> {
|
||||||
CycledSequence(base: self)
|
Cycle(base: self)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a sequence that repeats the elements of this collection the
|
/// Returns a sequence that repeats the elements of this collection the
|
||||||
/// specified number of times.
|
/// specified number of times.
|
||||||
///
|
///
|
||||||
@@ -216,7 +218,7 @@ extension Collection {
|
|||||||
///
|
///
|
||||||
/// - Complexity: O(1)
|
/// - Complexity: O(1)
|
||||||
@inlinable
|
@inlinable
|
||||||
public func cycled(times: Int) -> CycledTimesCollection<Self> {
|
public func cycled(times: Int) -> FiniteCycle<Self> {
|
||||||
CycledTimesCollection(base: self, times: times)
|
FiniteCycle(base: self, times: times)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,200 +0,0 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
|
||||||
//
|
|
||||||
// This source file is part of the Swift Algorithms open source project
|
|
||||||
//
|
|
||||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
|
||||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
|
||||||
//
|
|
||||||
// See https://swift.org/LICENSE.txt for license information
|
|
||||||
//
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// Either
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
/// A general-purpose sum type.
|
|
||||||
@usableFromInline
|
|
||||||
internal enum Either<Left, Right> {
|
|
||||||
case left(Left)
|
|
||||||
case right(Right)
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Either: Equatable where Left: Equatable, Right: Equatable {
|
|
||||||
@usableFromInline
|
|
||||||
internal static func == (lhs: Self, rhs: Self) -> Bool {
|
|
||||||
switch (lhs, rhs) {
|
|
||||||
case let (.left(lhs), .left(rhs)):
|
|
||||||
return lhs == rhs
|
|
||||||
case let (.right(lhs), .right(rhs)):
|
|
||||||
return lhs == rhs
|
|
||||||
case (.left, .right), (.right, .left):
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Either: Comparable where Left: Comparable, Right: Comparable {
|
|
||||||
@usableFromInline
|
|
||||||
internal static func < (lhs: Self, rhs: Self) -> Bool {
|
|
||||||
switch (lhs, rhs) {
|
|
||||||
case let (.left(lhs), .left(rhs)):
|
|
||||||
return lhs < rhs
|
|
||||||
case let (.right(lhs), .right(rhs)):
|
|
||||||
return lhs < rhs
|
|
||||||
case (.left, .right):
|
|
||||||
return true
|
|
||||||
case (.right, .left):
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// EitherSequence
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
/// A sequence that has one of the two specified types.
|
|
||||||
@usableFromInline
|
|
||||||
internal enum EitherSequence<Left: Sequence, Right: Sequence>
|
|
||||||
where Left.Element == Right.Element
|
|
||||||
{
|
|
||||||
case left(Left)
|
|
||||||
case right(Right)
|
|
||||||
}
|
|
||||||
|
|
||||||
extension EitherSequence: Sequence {
|
|
||||||
@usableFromInline
|
|
||||||
internal struct Iterator: IteratorProtocol {
|
|
||||||
@usableFromInline
|
|
||||||
internal var left: Left.Iterator?
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal var right: Right.Iterator?
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal mutating func next() -> Left.Element? {
|
|
||||||
left?.next() ?? right?.next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal func makeIterator() -> Iterator {
|
|
||||||
switch self {
|
|
||||||
case .left(let left):
|
|
||||||
return Iterator(left: left.makeIterator(), right: nil)
|
|
||||||
case .right(let right):
|
|
||||||
return Iterator(left: nil, right: right.makeIterator())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension EitherSequence: Collection
|
|
||||||
where Left: Collection, Right: Collection, Left.Element == Right.Element
|
|
||||||
{
|
|
||||||
@usableFromInline
|
|
||||||
internal typealias Index = Either<Left.Index, Right.Index>
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal var startIndex: Index {
|
|
||||||
switch self {
|
|
||||||
case .left(let s):
|
|
||||||
return .left(s.startIndex)
|
|
||||||
case .right(let s):
|
|
||||||
return .right(s.startIndex)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal var endIndex: Index {
|
|
||||||
switch self {
|
|
||||||
case .left(let s):
|
|
||||||
return .left(s.endIndex)
|
|
||||||
case .right(let s):
|
|
||||||
return .right(s.endIndex)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal subscript(position: Index) -> Element {
|
|
||||||
switch (self, position) {
|
|
||||||
case let (.left(s), .left(i)):
|
|
||||||
return s[i]
|
|
||||||
case let (.right(s), .right(i)):
|
|
||||||
return s[i]
|
|
||||||
default:
|
|
||||||
fatalError()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func index(after i: Index) -> Index {
|
|
||||||
switch (self,i) {
|
|
||||||
case let (.left(s), .left(i)):
|
|
||||||
return .left(s.index(after: i))
|
|
||||||
case let (.right(s), .right(i)):
|
|
||||||
return .right(s.index(after: i))
|
|
||||||
default:
|
|
||||||
fatalError()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func index(
|
|
||||||
_ i: Index,
|
|
||||||
offsetBy distance: Int,
|
|
||||||
limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
switch (self, i, limit) {
|
|
||||||
case let (.left(s), .left(i), .left(limit)):
|
|
||||||
return s.index(i, offsetBy: distance, limitedBy: limit).map { .left($0) }
|
|
||||||
case let (.right(s), .right(i), .right(limit)):
|
|
||||||
return s.index(i, offsetBy: distance, limitedBy: limit).map { .right($0) }
|
|
||||||
default:
|
|
||||||
fatalError()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func index(_ i: Index, offsetBy distance: Int) -> Index {
|
|
||||||
switch (self, i) {
|
|
||||||
case let (.left(s), .left(i)):
|
|
||||||
return .left(s.index(i, offsetBy: distance))
|
|
||||||
case let (.right(s), .right(i)):
|
|
||||||
return .right(s.index(i, offsetBy: distance))
|
|
||||||
default:
|
|
||||||
fatalError()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func distance(from start: Index, to end: Index) -> Int {
|
|
||||||
switch (self, start, end) {
|
|
||||||
case let (.left(s), .left(i), .left(j)):
|
|
||||||
return s.distance(from: i, to: j)
|
|
||||||
case let (.right(s), .right(i), .right(j)):
|
|
||||||
return s.distance(from: i, to: j)
|
|
||||||
default:
|
|
||||||
fatalError()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension EitherSequence: BidirectionalCollection
|
|
||||||
where Left: BidirectionalCollection, Right: BidirectionalCollection
|
|
||||||
{
|
|
||||||
@inlinable
|
|
||||||
internal func index(before i: Index) -> Index {
|
|
||||||
switch (self, i) {
|
|
||||||
case let (.left(s), .left(i)):
|
|
||||||
return .left(s.index(before: i))
|
|
||||||
case let (.right(s), .right(i)):
|
|
||||||
return .right(s.index(before: i))
|
|
||||||
default:
|
|
||||||
fatalError()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension EitherSequence: RandomAccessCollection
|
|
||||||
where Left: RandomAccessCollection, Right: RandomAccessCollection {}
|
|
||||||
@@ -30,7 +30,6 @@ extension Sequence {
|
|||||||
///
|
///
|
||||||
/// - Complexity: O(*n*), where *n* is the number of elements at the start of
|
/// - Complexity: O(*n*), where *n* is the number of elements at the start of
|
||||||
/// the sequence that result in `nil` when applying the transformation.
|
/// the sequence that result in `nil` when applying the transformation.
|
||||||
@inlinable
|
|
||||||
public func firstNonNil<Result>(
|
public func firstNonNil<Result>(
|
||||||
_ transform: (Element) throws -> Result?
|
_ transform: (Element) throws -> Result?
|
||||||
) rethrows -> Result? {
|
) rethrows -> Result? {
|
||||||
|
|||||||
@@ -1,311 +0,0 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
|
||||||
//
|
|
||||||
// This source file is part of the Swift Algorithms open source project
|
|
||||||
//
|
|
||||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
|
||||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
|
||||||
//
|
|
||||||
// See https://swift.org/LICENSE.txt for license information
|
|
||||||
//
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
/// A collection consisting of all the elements contained in a collection of
|
|
||||||
/// collections.
|
|
||||||
@usableFromInline
|
|
||||||
internal struct FlattenCollection<Base: Collection>
|
|
||||||
where Base.Element: Collection
|
|
||||||
{
|
|
||||||
@usableFromInline
|
|
||||||
internal let base: Base
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let indexOfFirstNonEmptyElement: Base.Index
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(base: Base) {
|
|
||||||
self.base = base
|
|
||||||
self.indexOfFirstNonEmptyElement = base.endOfPrefix(while: { $0.isEmpty })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension FlattenCollection: Collection {
|
|
||||||
@usableFromInline
|
|
||||||
internal struct Index: Comparable {
|
|
||||||
@usableFromInline
|
|
||||||
internal let outer: Base.Index
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let inner: Base.Element.Index?
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
init(outer: Base.Index, inner: Base.Element.Index?) {
|
|
||||||
self.outer = outer
|
|
||||||
self.inner = inner
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal static func < (lhs: Self, rhs: Self) -> Bool {
|
|
||||||
guard lhs.outer == rhs.outer else { return lhs.outer < rhs.outer }
|
|
||||||
return lhs.inner == nil ? false : lhs.inner! < rhs.inner!
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal var startIndex: Index {
|
|
||||||
let outer = indexOfFirstNonEmptyElement
|
|
||||||
let inner = outer == base.endIndex ? nil : base[outer].startIndex
|
|
||||||
return Index(outer: outer, inner: inner)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal var endIndex: Index {
|
|
||||||
Index(outer: base.endIndex, inner: nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Forms an index from a pair of base indices, normalizing
|
|
||||||
/// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if
|
|
||||||
/// necessary.
|
|
||||||
@inlinable
|
|
||||||
internal func normalizeIndex(
|
|
||||||
outer: Base.Index,
|
|
||||||
inner: Base.Element.Index
|
|
||||||
) -> Index {
|
|
||||||
if inner == base[outer].endIndex {
|
|
||||||
let outer = base[base.index(after: outer)...]
|
|
||||||
.endOfPrefix(while: { $0.isEmpty })
|
|
||||||
let inner = outer == base.endIndex ? nil : base[outer].startIndex
|
|
||||||
return Index(outer: outer, inner: inner)
|
|
||||||
} else {
|
|
||||||
return Index(outer: outer, inner: inner)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func index(after index: Index) -> Index {
|
|
||||||
let element = base[index.outer]
|
|
||||||
let nextInner = element.index(after: index.inner!)
|
|
||||||
return normalizeIndex(outer: index.outer, inner: nextInner)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal subscript(position: Index) -> Base.Element.Element {
|
|
||||||
base[position.outer][position.inner!]
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func distance(from start: Index, to end: Index) -> Int {
|
|
||||||
guard start.outer <= end.outer
|
|
||||||
else { return -distance(from: end, to: start) }
|
|
||||||
guard let startInner = start.inner
|
|
||||||
else { return 0 }
|
|
||||||
guard start.outer != end.outer
|
|
||||||
else {
|
|
||||||
return base[start.outer].distance(from: startInner, to: end.inner!)
|
|
||||||
}
|
|
||||||
|
|
||||||
let firstPart = base[start.outer][startInner...].count
|
|
||||||
let middlePart = base[start.outer..<end.outer].dropFirst()
|
|
||||||
.reduce(0, { $0 + $1.count })
|
|
||||||
let lastPart = end.inner.map { base[end.outer][..<$0].count } ?? 0
|
|
||||||
|
|
||||||
return firstPart + middlePart + lastPart
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func index(_ index: Index, offsetBy distance: Int) -> Index {
|
|
||||||
guard distance != 0 else { return index }
|
|
||||||
|
|
||||||
return distance > 0
|
|
||||||
? offsetForward(index, by: distance)
|
|
||||||
: offsetBackward(index, by: -distance)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func index(
|
|
||||||
_ index: Index,
|
|
||||||
offsetBy distance: Int,
|
|
||||||
limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
guard distance != 0 else { return index }
|
|
||||||
|
|
||||||
if distance > 0 {
|
|
||||||
return limit >= index
|
|
||||||
? offsetForward(index, by: distance, limitedBy: limit)
|
|
||||||
: offsetForward(index, by: distance)
|
|
||||||
} else {
|
|
||||||
return limit <= index
|
|
||||||
? offsetBackward(index, by: -distance, limitedBy: limit)
|
|
||||||
: offsetBackward(index, by: -distance)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@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
|
|
||||||
}
|
|
||||||
|
|
||||||
@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
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func offsetForward(
|
|
||||||
_ index: Index, by distance: Int, limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
assert(distance > 0)
|
|
||||||
assert(limit >= index)
|
|
||||||
|
|
||||||
if index.outer == limit.outer {
|
|
||||||
if let indexInner = index.inner, let limitInner = limit.inner {
|
|
||||||
return base[index.outer]
|
|
||||||
.index(indexInner, offsetBy: distance, limitedBy: limitInner)
|
|
||||||
.map { inner in Index(outer: index.outer, inner: inner) }
|
|
||||||
} else {
|
|
||||||
// `index` and `limit` are both `endIndex`
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// `index <= limit` and `index.outer != limit.outer`, so `index != endIndex`
|
|
||||||
let indexInner = index.inner!
|
|
||||||
let element = base[index.outer]
|
|
||||||
|
|
||||||
if let inner = element.index(
|
|
||||||
indexInner,
|
|
||||||
offsetBy: distance,
|
|
||||||
limitedBy: element.endIndex
|
|
||||||
) {
|
|
||||||
return normalizeIndex(outer: index.outer, inner: inner)
|
|
||||||
}
|
|
||||||
|
|
||||||
var remainder = distance - element[indexInner...].count
|
|
||||||
var outer = base.index(after: index.outer)
|
|
||||||
|
|
||||||
while outer != limit.outer {
|
|
||||||
let element = base[outer]
|
|
||||||
|
|
||||||
if let inner = element.index(
|
|
||||||
element.startIndex,
|
|
||||||
offsetBy: remainder,
|
|
||||||
limitedBy: element.endIndex
|
|
||||||
) {
|
|
||||||
return normalizeIndex(outer: outer, inner: inner)
|
|
||||||
}
|
|
||||||
|
|
||||||
remainder -= element.count
|
|
||||||
base.formIndex(after: &outer)
|
|
||||||
}
|
|
||||||
|
|
||||||
if let limitInner = limit.inner {
|
|
||||||
let element = base[outer]
|
|
||||||
return element.index(
|
|
||||||
element.startIndex,
|
|
||||||
offsetBy: remainder,
|
|
||||||
limitedBy: limitInner)
|
|
||||||
.map { inner in Index(outer: outer, inner: inner) }
|
|
||||||
} else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func offsetBackward(
|
|
||||||
_ index: Index, by distance: Int, limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
assert(distance > 0)
|
|
||||||
assert(limit <= index)
|
|
||||||
|
|
||||||
if index.outer == limit.outer {
|
|
||||||
if let indexInner = index.inner, let limitInner = limit.inner {
|
|
||||||
return base[index.outer]
|
|
||||||
.index(indexInner, offsetBy: -distance, limitedBy: limitInner)
|
|
||||||
.map { inner in Index(outer: index.outer, inner: inner) }
|
|
||||||
} else {
|
|
||||||
// `index` and `limit` are both `endIndex`
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var remainder = distance
|
|
||||||
|
|
||||||
if let indexInner = index.inner {
|
|
||||||
let element = base[index.outer]
|
|
||||||
|
|
||||||
if let inner = element.index(
|
|
||||||
indexInner,
|
|
||||||
offsetBy: -remainder,
|
|
||||||
limitedBy: element.startIndex
|
|
||||||
) {
|
|
||||||
return Index(outer: index.outer, inner: inner)
|
|
||||||
}
|
|
||||||
|
|
||||||
remainder -= element[..<indexInner].count
|
|
||||||
}
|
|
||||||
|
|
||||||
var outer = base.index(index.outer, offsetBy: -1)
|
|
||||||
|
|
||||||
while outer != limit.outer {
|
|
||||||
let element = base[outer]
|
|
||||||
|
|
||||||
if let inner = element.index(
|
|
||||||
element.endIndex,
|
|
||||||
offsetBy: -remainder,
|
|
||||||
limitedBy: element.startIndex
|
|
||||||
) {
|
|
||||||
return Index(outer: outer, inner: inner)
|
|
||||||
}
|
|
||||||
|
|
||||||
remainder -= element.count
|
|
||||||
base.formIndex(&outer, offsetBy: -1)
|
|
||||||
}
|
|
||||||
|
|
||||||
let element = base[outer]
|
|
||||||
return element.index(
|
|
||||||
element.endIndex,
|
|
||||||
offsetBy: -remainder,
|
|
||||||
limitedBy: limit.inner!
|
|
||||||
).map { inner in Index(outer: outer, inner: inner) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension FlattenCollection: BidirectionalCollection
|
|
||||||
where Base: BidirectionalCollection, Base.Element: BidirectionalCollection
|
|
||||||
{
|
|
||||||
@inlinable
|
|
||||||
internal func index(before index: Index) -> Index {
|
|
||||||
if let inner = index.inner {
|
|
||||||
let element = base[index.outer]
|
|
||||||
|
|
||||||
if inner != element.startIndex {
|
|
||||||
let previousInner = element.index(before: inner)
|
|
||||||
return Index(outer: index.outer, inner: previousInner)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let previousOuter = base[..<index.outer].lastIndex(where: { !$0.isEmpty })!
|
|
||||||
let element = base[previousOuter]
|
|
||||||
let previousInner = element.index(before: element.endIndex)
|
|
||||||
return Index(outer: previousOuter, inner: previousInner)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension FlattenCollection: LazySequenceProtocol, LazyCollectionProtocol
|
|
||||||
where Base: LazySequenceProtocol, Base.Element: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// joined()
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
extension Collection where Element: Collection {
|
|
||||||
/// Returns the concatenation of the elements in this collection of
|
|
||||||
/// collections.
|
|
||||||
@inlinable
|
|
||||||
internal func joined() -> FlattenCollection<Self> {
|
|
||||||
FlattenCollection(base: self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -11,80 +11,69 @@
|
|||||||
|
|
||||||
/// A collection wrapper that iterates over the indices and elements of a
|
/// A collection wrapper that iterates over the indices and elements of a
|
||||||
/// collection together.
|
/// collection together.
|
||||||
public struct IndexedCollection<Base: Collection> {
|
public struct Indexed<Base: Collection> {
|
||||||
|
/// The element type for an `Indexed` collection.
|
||||||
|
public typealias Element = (index: Base.Index, element: Base.Element)
|
||||||
|
|
||||||
/// The base collection.
|
/// The base collection.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(base: Base) {
|
internal init(base: Base) {
|
||||||
self.base = base
|
self.base = base
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension IndexedCollection: Collection {
|
extension Indexed: Collection {
|
||||||
/// The element type for an `IndexedCollection` collection.
|
|
||||||
public typealias Element = (index: Base.Index, element: Base.Element)
|
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var startIndex: Base.Index {
|
public var startIndex: Base.Index {
|
||||||
base.startIndex
|
base.startIndex
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var endIndex: Base.Index {
|
public var endIndex: Base.Index {
|
||||||
base.endIndex
|
base.endIndex
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public subscript(position: Base.Index) -> Element {
|
public subscript(position: Base.Index) -> Element {
|
||||||
(index: position, element: base[position])
|
(index: position, element: base[position])
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(after i: Base.Index) -> Base.Index {
|
public func index(after i: Base.Index) -> Base.Index {
|
||||||
base.index(after: i)
|
base.index(after: i)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index {
|
public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index {
|
||||||
base.index(i, offsetBy: distance)
|
base.index(i, offsetBy: distance)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(
|
public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index) -> Base
|
||||||
_ i: Base.Index,
|
.Index?
|
||||||
offsetBy distance: Int,
|
{
|
||||||
limitedBy limit: Base.Index
|
|
||||||
) -> Base.Index? {
|
|
||||||
base.index(i, offsetBy: distance, limitedBy: limit)
|
base.index(i, offsetBy: distance, limitedBy: limit)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func distance(from start: Base.Index, to end: Base.Index) -> Int {
|
public func distance(from start: Base.Index, to end: Base.Index) -> Int {
|
||||||
base.distance(from: start, to: end)
|
base.distance(from: start, to: end)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public var indices: Base.Indices {
|
|
||||||
base.indices
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension IndexedCollection: BidirectionalCollection
|
extension Indexed: BidirectionalCollection where Base: BidirectionalCollection {
|
||||||
where Base: BidirectionalCollection
|
|
||||||
{
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(before i: Base.Index) -> Base.Index {
|
public func index(before i: Base.Index) -> Base.Index {
|
||||||
base.index(before: i)
|
base.index(before: i)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension IndexedCollection: RandomAccessCollection
|
extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||||
where Base: RandomAccessCollection {}
|
extension Indexed: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||||
|
extension Indexed: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
||||||
extension IndexedCollection: LazySequenceProtocol, LazyCollectionProtocol
|
|
||||||
where Base: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// indexed()
|
// indexed()
|
||||||
@@ -107,7 +96,7 @@ extension Collection {
|
|||||||
///
|
///
|
||||||
/// Returns: A collection of paired indices and elements of this collection.
|
/// Returns: A collection of paired indices and elements of this collection.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func indexed() -> IndexedCollection<Self> {
|
public func indexed() -> Indexed<Self> {
|
||||||
IndexedCollection(base: self)
|
Indexed(base: self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,19 +9,15 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
/// A sequence that presents the elements of a base sequence of elements
|
||||||
// Intersperse
|
/// with a separator between each of those elements.
|
||||||
//===----------------------------------------------------------------------===//
|
public struct Intersperse<Base: Sequence> {
|
||||||
|
|
||||||
/// A sequence that presents the elements of a base sequence of elements with a
|
|
||||||
/// separator between each of those elements.
|
|
||||||
public struct InterspersedSequence<Base: Sequence> {
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let separator: Base.Element
|
internal let separator: Base.Element
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(base: Base, separator: Base.Element) {
|
internal init(base: Base, separator: Base.Element) {
|
||||||
self.base = base
|
self.base = base
|
||||||
@@ -29,31 +25,31 @@ public struct InterspersedSequence<Base: Sequence> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension InterspersedSequence: Sequence {
|
extension Intersperse: Sequence {
|
||||||
/// The iterator for an `InterspersedSequence` sequence.
|
/// The iterator for an `Intersperse` sequence.
|
||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
|
||||||
internal enum State {
|
|
||||||
case start
|
|
||||||
case element(Base.Element)
|
|
||||||
case separator
|
|
||||||
}
|
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var iterator: Base.Iterator
|
internal var iterator: Base.Iterator
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let separator: Base.Element
|
internal let separator: Base.Element
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var state = State.start
|
internal var state = State.start
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(iterator: Base.Iterator, separator: Base.Element) {
|
internal init(iterator: Base.Iterator, separator: Base.Element) {
|
||||||
self.iterator = iterator
|
self.iterator = iterator
|
||||||
self.separator = separator
|
self.separator = separator
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@usableFromInline
|
||||||
|
enum State {
|
||||||
|
case start
|
||||||
|
case element(Base.Element)
|
||||||
|
case separator
|
||||||
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public mutating func next() -> Base.Element? {
|
public mutating func next() -> Base.Element? {
|
||||||
// After the start, the state flips between element and separator. Before
|
// After the start, the state flips between element and separator. Before
|
||||||
@@ -76,25 +72,25 @@ extension InterspersedSequence: Sequence {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func makeIterator() -> InterspersedSequence<Base>.Iterator {
|
public func makeIterator() -> Intersperse<Base>.Iterator {
|
||||||
Iterator(iterator: base.makeIterator(), separator: separator)
|
Iterator(iterator: base.makeIterator(), separator: separator)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension InterspersedSequence: Collection where Base: Collection {
|
extension Intersperse: Collection where Base: Collection {
|
||||||
/// A position in an `InterspersedSequence` instance.
|
/// A position in an `Intersperse` collection.
|
||||||
public struct Index: Comparable {
|
public struct Index: Comparable {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal enum Representation: Equatable {
|
enum Representation: Equatable {
|
||||||
case element(Base.Index)
|
case element(Base.Index)
|
||||||
case separator(next: Base.Index)
|
case separator(next: Base.Index)
|
||||||
}
|
}
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let representation: Representation
|
internal let representation: Representation
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(representation: Representation) {
|
init(representation: Representation) {
|
||||||
self.representation = representation
|
self.representation = representation
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,21 +98,21 @@ extension InterspersedSequence: Collection where Base: Collection {
|
|||||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||||
switch (lhs.representation, rhs.representation) {
|
switch (lhs.representation, rhs.representation) {
|
||||||
case let (.element(li), .element(ri)),
|
case let (.element(li), .element(ri)),
|
||||||
let (.separator(next: li), .separator(next: ri)),
|
let (.separator(next: li), .separator(next: ri)),
|
||||||
let (.element(li), .separator(next: ri)):
|
let (.element(li), .separator(next: ri)):
|
||||||
return li < ri
|
return li < ri
|
||||||
case let (.separator(next: li), .element(ri)):
|
case let (.separator(next: li), .element(ri)):
|
||||||
return li <= ri
|
return li <= ri
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal static func element(_ index: Base.Index) -> Self {
|
static func element(_ index: Base.Index) -> Self {
|
||||||
Self(representation: .element(index))
|
Self(representation: .element(index))
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal static func separator(next: Base.Index) -> Self {
|
static func separator(next: Base.Index) -> Self {
|
||||||
Self(representation: .separator(next: next))
|
Self(representation: .separator(next: next))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -149,7 +145,22 @@ extension InterspersedSequence: Collection where Base: Collection {
|
|||||||
case .separator: return separator
|
case .separator: return separator
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@inlinable
|
||||||
|
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||||
|
switch (i.representation, distance.isMultiple(of: 2)) {
|
||||||
|
case (let .element(index), true):
|
||||||
|
return .element(base.index(index, offsetBy: distance / 2))
|
||||||
|
case (let .element(index), false):
|
||||||
|
return .separator(next: base.index(index, offsetBy: (distance + 1) / 2))
|
||||||
|
case (let .separator(next: index), true):
|
||||||
|
return .separator(next: base.index(index, offsetBy: distance / 2))
|
||||||
|
case (let .separator(next: index), false):
|
||||||
|
return .element(base.index(index, offsetBy: (distance - 1) / 2))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Implement index(_:offsetBy:limitedBy:)
|
||||||
@inlinable
|
@inlinable
|
||||||
public func distance(from start: Index, to end: Index) -> Int {
|
public func distance(from start: Index, to end: Index) -> Int {
|
||||||
switch (start.representation, end.representation) {
|
switch (start.representation, end.representation) {
|
||||||
@@ -158,107 +169,14 @@ extension InterspersedSequence: Collection where Base: Collection {
|
|||||||
case let (.separator(next: separator), .element(element)):
|
case let (.separator(next: separator), .element(element)):
|
||||||
return 2 * base.distance(from: separator, to: element) + 1
|
return 2 * base.distance(from: separator, to: element) + 1
|
||||||
case let (.element(start), .element(end)),
|
case let (.element(start), .element(end)),
|
||||||
let (.separator(start), .separator(end)):
|
let (.separator(start), .separator(end)):
|
||||||
return 2 * base.distance(from: start, to: end)
|
return 2 * base.distance(from: start, to: end)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func index(_ index: Index, offsetBy distance: Int) -> Index {
|
|
||||||
distance >= 0
|
|
||||||
? offsetForward(index, by: distance)
|
|
||||||
: offsetBackward(index, by: -distance)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func index(
|
|
||||||
_ index: Index,
|
|
||||||
offsetBy distance: Int,
|
|
||||||
limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
if distance >= 0 {
|
|
||||||
return limit >= index
|
|
||||||
? offsetForward(index, by: distance, limitedBy: limit)
|
|
||||||
: offsetForward(index, by: distance)
|
|
||||||
} else {
|
|
||||||
return limit <= index
|
|
||||||
? offsetBackward(index, by: -distance, limitedBy: limit)
|
|
||||||
: offsetBackward(index, by: -distance)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@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
|
|
||||||
}
|
|
||||||
|
|
||||||
@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
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func offsetForward(
|
|
||||||
_ index: Index, by distance: Int, limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
assert(distance >= 0)
|
|
||||||
assert(limit >= index)
|
|
||||||
|
|
||||||
switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
|
|
||||||
case let (.element(index), .element(limit), true),
|
|
||||||
let (.separator(next: index), .element(limit), false):
|
|
||||||
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
|
|
||||||
.map { .element($0) }
|
|
||||||
|
|
||||||
case let (.element(index), .element(limit), false),
|
|
||||||
let (.element(index), .separator(next: limit), false),
|
|
||||||
let (.separator(next: index), .element(limit), true),
|
|
||||||
let (.separator(next: index), .separator(next: limit), true):
|
|
||||||
return base.index(index, offsetBy: (distance + 1) / 2, limitedBy: limit)
|
|
||||||
.map { .separator(next: $0) }
|
|
||||||
|
|
||||||
case let (.element(index), .separator(next: limit), true),
|
|
||||||
let (.separator(next: index), .separator(next: limit), false):
|
|
||||||
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
|
|
||||||
.flatMap { $0 == limit ? nil : .element($0) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func offsetBackward(
|
|
||||||
_ index: Index, by distance: Int, limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
assert(distance >= 0)
|
|
||||||
assert(limit <= index)
|
|
||||||
|
|
||||||
switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
|
|
||||||
case let (.element(index), .element(limit), true),
|
|
||||||
let (.element(index), .separator(next: limit), true),
|
|
||||||
let (.separator(next: index), .element(limit), false),
|
|
||||||
let (.separator(next: index), .separator(next: limit), false):
|
|
||||||
return base.index(index, offsetBy: -((distance + 1) / 2), limitedBy: limit)
|
|
||||||
.map { .element($0) }
|
|
||||||
|
|
||||||
case let (.element(index), .separator(next: limit), false),
|
|
||||||
let (.separator(next: index), .separator(next: limit), true):
|
|
||||||
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
|
|
||||||
.map { .separator(next: $0) }
|
|
||||||
|
|
||||||
case let (.element(index), .element(limit), false),
|
|
||||||
let (.separator(next: index), .element(limit), true):
|
|
||||||
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
|
|
||||||
.flatMap { $0 == limit ? nil : .separator(next: $0) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension InterspersedSequence: BidirectionalCollection
|
extension Intersperse: BidirectionalCollection
|
||||||
where Base: BidirectionalCollection
|
where Base: BidirectionalCollection {
|
||||||
{
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(before i: Index) -> Index {
|
public func index(before i: Index) -> Index {
|
||||||
precondition(i != startIndex, "Can't move before startIndex")
|
precondition(i != startIndex, "Can't move before startIndex")
|
||||||
@@ -271,337 +189,17 @@ extension InterspersedSequence: BidirectionalCollection
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension InterspersedSequence: RandomAccessCollection
|
extension Intersperse: RandomAccessCollection
|
||||||
where Base: RandomAccessCollection {}
|
where Base: RandomAccessCollection {}
|
||||||
|
|
||||||
extension InterspersedSequence: LazySequenceProtocol
|
extension Intersperse: LazySequenceProtocol
|
||||||
where Base: LazySequenceProtocol {}
|
where Base: LazySequenceProtocol {}
|
||||||
|
|
||||||
extension InterspersedSequence: LazyCollectionProtocol
|
extension Intersperse: LazyCollectionProtocol
|
||||||
where Base: LazySequenceProtocol & Collection {}
|
where Base: LazyCollectionProtocol {}
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// InterspersedMap
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
|
|
||||||
/// A sequence over the results of applying a closure to the sequence's
|
|
||||||
/// elements, with a separator that separates each pair of adjacent transformed
|
|
||||||
/// values.
|
|
||||||
@usableFromInline
|
|
||||||
internal struct InterspersedMapSequence<Base: Sequence, Result> {
|
|
||||||
@usableFromInline
|
|
||||||
internal let base: Base
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let transform: (Base.Element) -> Result
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let separator: (Base.Element, Base.Element) -> Result
|
|
||||||
}
|
|
||||||
|
|
||||||
extension InterspersedMapSequence: Sequence {
|
|
||||||
@usableFromInline
|
|
||||||
internal struct Iterator: IteratorProtocol {
|
|
||||||
@usableFromInline
|
|
||||||
internal enum State {
|
|
||||||
case start
|
|
||||||
case element(Base.Element)
|
|
||||||
case separator(previous: Base.Element)
|
|
||||||
}
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal var base: Base.Iterator
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let transform: (Base.Element) -> Result
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let separator: (Base.Element, Base.Element) -> Result
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal var state = State.start
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(
|
|
||||||
base: Base.Iterator,
|
|
||||||
transform: @escaping (Base.Element) -> Result,
|
|
||||||
separator: @escaping (Base.Element, Base.Element) -> Result
|
|
||||||
) {
|
|
||||||
self.base = base
|
|
||||||
self.transform = transform
|
|
||||||
self.separator = separator
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal mutating func next() -> Result? {
|
|
||||||
switch state {
|
|
||||||
case .start:
|
|
||||||
guard let first = base.next() else { return nil }
|
|
||||||
state = .separator(previous: first)
|
|
||||||
return transform(first)
|
|
||||||
case .separator(let previous):
|
|
||||||
guard let next = base.next() else { return nil }
|
|
||||||
state = .element(next)
|
|
||||||
return separator(previous, next)
|
|
||||||
case .element(let element):
|
|
||||||
state = .separator(previous: element)
|
|
||||||
return transform(element)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func makeIterator() -> Iterator {
|
|
||||||
Iterator(
|
|
||||||
base: base.makeIterator(),
|
|
||||||
transform: transform,
|
|
||||||
separator: separator)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension InterspersedMapSequence: Collection where Base: Collection {
|
|
||||||
@usableFromInline
|
|
||||||
internal struct Index: Comparable {
|
|
||||||
@usableFromInline
|
|
||||||
internal enum Representation {
|
|
||||||
case element(Base.Index)
|
|
||||||
case separator(previous: Base.Index, next: Base.Index)
|
|
||||||
}
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let representation: Representation
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(representation: Representation) {
|
|
||||||
self.representation = representation
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal static func element(_ index: Base.Index) -> Self {
|
|
||||||
Self(representation: .element(index))
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal static func separator(previous: Base.Index, next: Base.Index) -> Self {
|
|
||||||
Self(representation: .separator(previous: previous, next: next))
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal static func == (lhs: Self, rhs: Self) -> Bool {
|
|
||||||
switch (lhs.representation, rhs.representation) {
|
|
||||||
case let (.element(lhs), .element(rhs)),
|
|
||||||
let (.separator(_, next: lhs), .separator(_, next: rhs)):
|
|
||||||
return lhs == rhs
|
|
||||||
case (.element, .separator), (.separator, .element):
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal static func < (lhs: Self, rhs: Self) -> Bool {
|
|
||||||
switch (lhs.representation, rhs.representation) {
|
|
||||||
case let (.element(lhs), .element(rhs)),
|
|
||||||
let (.separator(_, next: lhs), .separator(_, next: rhs)),
|
|
||||||
let (.element(lhs), .separator(_, next: rhs)),
|
|
||||||
let (.separator(previous: lhs, _), .element(rhs)):
|
|
||||||
return lhs < rhs
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal var startIndex: Index {
|
|
||||||
base.isEmpty ? endIndex : .element(base.startIndex)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal var endIndex: Index {
|
|
||||||
.separator(previous: base.endIndex, next: base.endIndex)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func index(after index: Index) -> Index {
|
|
||||||
switch index.representation {
|
|
||||||
case .element(let index):
|
|
||||||
let next = base.index(after: index)
|
|
||||||
return .separator(previous: index, next: next)
|
|
||||||
case .separator(_, let next):
|
|
||||||
return .element(next)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal subscript(position: Index) -> Result {
|
|
||||||
switch position.representation {
|
|
||||||
case .element(let index):
|
|
||||||
return transform(base[index])
|
|
||||||
case let .separator(previous, next):
|
|
||||||
return separator(base[previous], base[next])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func distance(from start: Index, to end: Index) -> Int {
|
|
||||||
switch (start.representation, end.representation) {
|
|
||||||
case let (.element(lhs), .element(rhs)),
|
|
||||||
let (.separator(_, next: lhs), .separator(_, next: rhs)):
|
|
||||||
return 2 * base.distance(from: lhs, to: rhs)
|
|
||||||
case let (.element(lhs), .separator(_, next: rhs)):
|
|
||||||
return 2 * base.distance(from: lhs, to: rhs) - 1
|
|
||||||
case let (.separator(_, next: lhs), .element(rhs)):
|
|
||||||
return 2 * base.distance(from: lhs, to: rhs) + 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func index(_ index: Index, offsetBy distance: Int) -> Index {
|
|
||||||
guard distance != 0 else { return index }
|
|
||||||
|
|
||||||
return distance > 0
|
|
||||||
? offsetForward(index, by: distance)
|
|
||||||
: offsetBackward(index, by: -distance)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func index(
|
|
||||||
_ index: Index,
|
|
||||||
offsetBy distance: Int,
|
|
||||||
limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
guard distance != 0 else { return index }
|
|
||||||
|
|
||||||
if distance > 0 {
|
|
||||||
return limit >= index
|
|
||||||
? offsetForward(index, by: distance, limitedBy: limit)
|
|
||||||
: offsetForward(index, by: distance)
|
|
||||||
} else {
|
|
||||||
return limit <= index
|
|
||||||
? offsetBackward(index, by: -distance, limitedBy: limit)
|
|
||||||
: offsetBackward(index, by: -distance)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@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
|
|
||||||
}
|
|
||||||
|
|
||||||
@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
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func offsetForward(
|
|
||||||
_ index: Index, by distance: Int, limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
assert(distance > 0)
|
|
||||||
assert(limit >= index)
|
|
||||||
|
|
||||||
switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
|
|
||||||
case let (.element(index), .element(limit), true),
|
|
||||||
let (.separator(_, next: index), .element(limit), false):
|
|
||||||
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
|
|
||||||
.map { .element($0) }
|
|
||||||
|
|
||||||
case let (.element(index), .element(limit), false),
|
|
||||||
let (.element(index), .separator(_, next: limit), false),
|
|
||||||
let (.separator(_, next: index), .element(limit), true),
|
|
||||||
let (.separator(_, next: index), .separator(_, next: limit), true):
|
|
||||||
return base.index(index, offsetBy: (distance - 1) / 2, limitedBy: limit)
|
|
||||||
.flatMap {
|
|
||||||
guard $0 != limit else { return nil }
|
|
||||||
let next = base.index(after: $0)
|
|
||||||
return next == base.endIndex
|
|
||||||
? endIndex
|
|
||||||
: .separator(previous: $0, next: next)
|
|
||||||
}
|
|
||||||
|
|
||||||
case let (.element(index), .separator(_, next: limit), true),
|
|
||||||
let (.separator(_, next: index), .separator(_, next: limit), false):
|
|
||||||
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
|
|
||||||
.flatMap { $0 == limit ? nil : .element($0) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func offsetBackward(
|
|
||||||
_ index: Index, by distance: Int, limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
assert(distance > 0)
|
|
||||||
assert(limit <= index)
|
|
||||||
|
|
||||||
switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
|
|
||||||
case let (.element(index), .element(limit), true),
|
|
||||||
let (.element(index), .separator(_, next: limit), true),
|
|
||||||
let (.separator(_, next: index), .element(limit), false),
|
|
||||||
let (.separator(_, next: index), .separator(_, next: limit), false):
|
|
||||||
return base.index(index, offsetBy: -((distance + 1) / 2), limitedBy: limit)
|
|
||||||
.map { .element($0) }
|
|
||||||
|
|
||||||
case let (.element(index), .separator(_, next: limit), false),
|
|
||||||
let (.separator(_, next: index), .separator(_, next: limit), true):
|
|
||||||
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
|
|
||||||
.map { .separator(previous: base.index($0, offsetBy: -1), next: $0) }
|
|
||||||
|
|
||||||
case let (.element(index), .element(limit), false),
|
|
||||||
let (.separator(_, next: index), .element(limit), true):
|
|
||||||
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
|
|
||||||
.flatMap {
|
|
||||||
$0 == limit
|
|
||||||
? nil
|
|
||||||
: .separator(previous: base.index($0, offsetBy: -1), next: $0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension InterspersedMapSequence: BidirectionalCollection
|
|
||||||
where Base: BidirectionalCollection
|
|
||||||
{
|
|
||||||
@inlinable
|
|
||||||
internal func index(before index: Index) -> Index {
|
|
||||||
switch index.representation {
|
|
||||||
case .element(let index):
|
|
||||||
let previous = base.index(before: index)
|
|
||||||
return .separator(previous: previous, next: index)
|
|
||||||
case let .separator(previous, next):
|
|
||||||
let index = next == base.endIndex ? base.index(before: next) : previous
|
|
||||||
return .element(index)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension InterspersedMapSequence.Index: Hashable
|
|
||||||
where Base.Index: Hashable
|
|
||||||
{
|
|
||||||
@inlinable
|
|
||||||
internal func hash(into hasher: inout Hasher) {
|
|
||||||
switch representation {
|
|
||||||
case .element(let base):
|
|
||||||
hasher.combine(false)
|
|
||||||
hasher.combine(base)
|
|
||||||
case .separator(_, let next):
|
|
||||||
hasher.combine(true)
|
|
||||||
hasher.combine(next)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension InterspersedMapSequence: LazySequenceProtocol {}
|
|
||||||
extension InterspersedMapSequence: LazyCollectionProtocol
|
|
||||||
where Base: Collection {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// interspersed(with:)
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
extension Sequence {
|
extension Sequence {
|
||||||
|
|
||||||
/// Returns a sequence containing elements of this sequence with the given
|
/// Returns a sequence containing elements of this sequence with the given
|
||||||
/// separator inserted in between each element.
|
/// separator inserted in between each element.
|
||||||
///
|
///
|
||||||
@@ -631,39 +229,7 @@ extension Sequence {
|
|||||||
///
|
///
|
||||||
/// - Complexity: O(1)
|
/// - Complexity: O(1)
|
||||||
@inlinable
|
@inlinable
|
||||||
public func interspersed(
|
public func interspersed(with separator: Element) -> Intersperse<Self> {
|
||||||
with separator: Element
|
Intersperse(base: self, separator: separator)
|
||||||
) -> InterspersedSequence<Self> {
|
|
||||||
InterspersedSequence(base: self, separator: separator)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// lazy.interspersedMap(_:with:)
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
extension LazySequenceProtocol {
|
|
||||||
/// Returns a sequence over the results of applying a closure to the
|
|
||||||
/// sequence's elements, with a separator that separates each pair of adjacent
|
|
||||||
/// transformed values.
|
|
||||||
///
|
|
||||||
/// The transformation closure lets you intersperse a sequence using a
|
|
||||||
/// separator of a different type than the original's sequence's elements.
|
|
||||||
/// Each separator is produced by a closure that is given access to the
|
|
||||||
/// two elements in the original sequence right before and after it.
|
|
||||||
///
|
|
||||||
/// let strings = [1, 2, 2].interspersedMap(String.init,
|
|
||||||
/// with: { $0 == $1 ? " == " : " != " })
|
|
||||||
/// print(strings.joined()) // "1 != 2 == 2"
|
|
||||||
///
|
|
||||||
@usableFromInline
|
|
||||||
internal func interspersedMap<Result>(
|
|
||||||
_ transform: @escaping (Element) -> Result,
|
|
||||||
with separator: @escaping (Element, Element) -> Result
|
|
||||||
) -> InterspersedMapSequence<Elements, Result> {
|
|
||||||
InterspersedMapSequence(
|
|
||||||
base: elements,
|
|
||||||
transform: transform,
|
|
||||||
separator: separator)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,489 +0,0 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
|
||||||
//
|
|
||||||
// This source file is part of the Swift Algorithms open source project
|
|
||||||
//
|
|
||||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
|
||||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
|
||||||
//
|
|
||||||
// See https://swift.org/LICENSE.txt for license information
|
|
||||||
//
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// JoinedBySequence
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
/// A sequence that presents the elements of a base sequence of sequences
|
|
||||||
/// concatenated using a given separator.
|
|
||||||
public struct JoinedBySequence<Base: Sequence, Separator: Sequence>
|
|
||||||
where Base.Element: Sequence, Base.Element.Element == Separator.Element
|
|
||||||
{
|
|
||||||
@usableFromInline
|
|
||||||
internal typealias Inner = FlattenSequence<InterspersedSequence<
|
|
||||||
LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>>>
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let inner: Inner
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(base: Base, separator: Separator) {
|
|
||||||
self.inner = base.lazy
|
|
||||||
.map(EitherSequence.left)
|
|
||||||
.interspersed(with: .right(separator))
|
|
||||||
.joined()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension JoinedBySequence: Sequence {
|
|
||||||
public struct Iterator: IteratorProtocol {
|
|
||||||
@usableFromInline
|
|
||||||
internal var inner: Inner.Iterator
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(inner: Inner.Iterator) {
|
|
||||||
self.inner = inner
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public mutating func next() -> Base.Element.Element? {
|
|
||||||
inner.next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func makeIterator() -> Iterator {
|
|
||||||
Iterator(inner: inner.makeIterator())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension JoinedBySequence: LazySequenceProtocol
|
|
||||||
where Base: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// JoinedByClosureSequence
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
/// A sequence that presents the elements of a base sequence of sequences
|
|
||||||
/// concatenated using a given separator that depends on the sequences right
|
|
||||||
/// before and after it.
|
|
||||||
public struct JoinedByClosureSequence<Base: Sequence, Separator: Sequence>
|
|
||||||
where Base.Element: Sequence, Base.Element.Element == Separator.Element
|
|
||||||
{
|
|
||||||
@usableFromInline
|
|
||||||
internal typealias Inner = FlattenSequence<InterspersedMapSequence<
|
|
||||||
Base, EitherSequence<Base.Element, Separator>>>
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let inner: Inner
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(
|
|
||||||
base: Base,
|
|
||||||
separator: @escaping (Base.Element, Base.Element) -> Separator
|
|
||||||
) {
|
|
||||||
self.inner = base.lazy
|
|
||||||
.interspersedMap(
|
|
||||||
EitherSequence.left,
|
|
||||||
with: { EitherSequence.right(separator($0, $1)) })
|
|
||||||
.joined()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension JoinedByClosureSequence: Sequence {
|
|
||||||
public struct Iterator: IteratorProtocol {
|
|
||||||
@usableFromInline
|
|
||||||
internal var inner: Inner.Iterator
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(inner: Inner.Iterator) {
|
|
||||||
self.inner = inner
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public mutating func next() -> Base.Element.Element? {
|
|
||||||
inner.next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func makeIterator() -> Iterator {
|
|
||||||
Iterator(inner: inner.makeIterator())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension JoinedByClosureSequence: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// JoinedByCollection
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
/// A collection that presents the elements of a base collection of collections
|
|
||||||
/// concatenated using a given separator.
|
|
||||||
public struct JoinedByCollection<Base: Collection, Separator: Collection>
|
|
||||||
where Base.Element: Collection, Base.Element.Element == Separator.Element
|
|
||||||
{
|
|
||||||
@usableFromInline
|
|
||||||
internal typealias Inner = FlattenCollection<InterspersedSequence<
|
|
||||||
LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>>>
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let inner: Inner
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(base: Base, separator: Separator) {
|
|
||||||
self.inner = base.lazy
|
|
||||||
.map(EitherSequence.left)
|
|
||||||
.interspersed(with: .right(separator))
|
|
||||||
.joined()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension JoinedByCollection: Collection {
|
|
||||||
public struct Index: Comparable {
|
|
||||||
@usableFromInline
|
|
||||||
internal let inner: Inner.Index
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(_ inner: Inner.Index) {
|
|
||||||
self.inner = inner
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
|
||||||
lhs.inner == rhs.inner
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
|
||||||
lhs.inner < rhs.inner
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public var startIndex: Index {
|
|
||||||
Index(inner.startIndex)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public var endIndex: Index {
|
|
||||||
Index(inner.endIndex)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func index(after index: Index) -> Index {
|
|
||||||
Index(inner.index(after: index.inner))
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public subscript(position: Index) -> Base.Element.Element {
|
|
||||||
inner[position.inner]
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func index(_ index: Index, offsetBy distance: Int) -> Index {
|
|
||||||
Index(inner.index(index.inner, offsetBy: distance))
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func index(
|
|
||||||
_ index: Index,
|
|
||||||
offsetBy distance: Int,
|
|
||||||
limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
inner.index(index.inner, offsetBy: distance, limitedBy: limit.inner)
|
|
||||||
.map(Index.init)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func distance(from start: Index, to end: Index) -> Int {
|
|
||||||
inner.distance(from: start.inner, to: end.inner)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension JoinedByCollection: BidirectionalCollection
|
|
||||||
where Base: BidirectionalCollection,
|
|
||||||
Base.Element: BidirectionalCollection,
|
|
||||||
Separator: BidirectionalCollection
|
|
||||||
{
|
|
||||||
@inlinable
|
|
||||||
public func index(before index: Index) -> Index {
|
|
||||||
Index(inner.index(before: index.inner))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension JoinedByCollection: LazySequenceProtocol, LazyCollectionProtocol
|
|
||||||
where Base: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// JoinedByClosureCollection
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
/// A collection that presents the elements of a base collection of collections
|
|
||||||
/// concatenated using a given separator that depends on the collections right
|
|
||||||
/// before and after it.
|
|
||||||
public struct JoinedByClosureCollection<Base: Collection, Separator: Collection>
|
|
||||||
where Base.Element: Collection, Base.Element.Element == Separator.Element
|
|
||||||
{
|
|
||||||
@usableFromInline
|
|
||||||
internal typealias Inner = FlattenCollection<InterspersedMapSequence<
|
|
||||||
Base, EitherSequence<Base.Element, Separator>>>
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let inner: Inner
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(
|
|
||||||
base: Base,
|
|
||||||
separator: @escaping (Base.Element, Base.Element) -> Separator
|
|
||||||
) {
|
|
||||||
self.inner = base.lazy
|
|
||||||
.interspersedMap(
|
|
||||||
EitherSequence.left,
|
|
||||||
with: { EitherSequence.right(separator($0, $1)) })
|
|
||||||
.joined()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension JoinedByClosureCollection: Collection {
|
|
||||||
public struct Index: Comparable {
|
|
||||||
@usableFromInline
|
|
||||||
internal let inner: Inner.Index
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal init(_ inner: Inner.Index) {
|
|
||||||
self.inner = inner
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
|
||||||
lhs.inner == rhs.inner
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
|
||||||
lhs.inner < rhs.inner
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public var startIndex: Index {
|
|
||||||
Index(inner.startIndex)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public var endIndex: Index {
|
|
||||||
Index(inner.endIndex)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func index(after index: Index) -> Index {
|
|
||||||
Index(inner.index(after: index.inner))
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public subscript(position: Index) -> Base.Element.Element {
|
|
||||||
inner[position.inner]
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func index(_ index: Index, offsetBy distance: Int) -> Index {
|
|
||||||
Index(inner.index(index.inner, offsetBy: distance))
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func index(
|
|
||||||
_ index: Index,
|
|
||||||
offsetBy distance: Int,
|
|
||||||
limitedBy limit: Index
|
|
||||||
) -> Index? {
|
|
||||||
inner.index(index.inner, offsetBy: distance, limitedBy: limit.inner)
|
|
||||||
.map(Index.init)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func distance(from start: Index, to end: Index) -> Int {
|
|
||||||
inner.distance(from: start.inner, to: end.inner)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension JoinedByClosureCollection: BidirectionalCollection
|
|
||||||
where Base: BidirectionalCollection,
|
|
||||||
Base.Element: BidirectionalCollection,
|
|
||||||
Separator: BidirectionalCollection
|
|
||||||
{
|
|
||||||
@inlinable
|
|
||||||
public func index(before index: Index) -> Index {
|
|
||||||
Index(inner.index(before: index.inner))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension JoinedByClosureCollection: LazyCollectionProtocol {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// Sequence.joined(by:)
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
extension Sequence where Element: Sequence {
|
|
||||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
|
||||||
/// inserting the given separator between each sequence.
|
|
||||||
///
|
|
||||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: 100) {
|
|
||||||
/// print(x)
|
|
||||||
/// }
|
|
||||||
/// // 1, 2, 100, 3, 4, 100, 5, 6
|
|
||||||
@inlinable
|
|
||||||
public func joined(by separator: Element.Element)
|
|
||||||
-> JoinedBySequence<Self, CollectionOfOne<Element.Element>>
|
|
||||||
{
|
|
||||||
joined(by: CollectionOfOne(separator))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
|
||||||
/// inserting the given separator between each sequence.
|
|
||||||
///
|
|
||||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: [100, 200]) {
|
|
||||||
/// print(x)
|
|
||||||
/// }
|
|
||||||
/// // 1, 2, 100, 200, 3, 4, 100, 200, 5, 6
|
|
||||||
@inlinable
|
|
||||||
public func joined<Separator>(
|
|
||||||
by separator: Separator
|
|
||||||
) -> JoinedBySequence<Self, Separator>
|
|
||||||
where Separator: Collection, Separator.Element == Element.Element
|
|
||||||
{
|
|
||||||
JoinedBySequence(base: self, separator: separator)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
internal func _joined(
|
|
||||||
by update: (inout [Element.Element], Element, Element) throws -> Void
|
|
||||||
) rethrows -> [Element.Element] {
|
|
||||||
var iterator = makeIterator()
|
|
||||||
guard let first = iterator.next() else { return [] }
|
|
||||||
|
|
||||||
var result = Array(first)
|
|
||||||
var previous = first
|
|
||||||
|
|
||||||
while let next = iterator.next() {
|
|
||||||
try update(&result, previous, next)
|
|
||||||
result.append(contentsOf: next)
|
|
||||||
previous = next
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
|
||||||
/// inserting the separator produced by the closure between each sequence.
|
|
||||||
///
|
|
||||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: { $0.last! * $1.first! }) {
|
|
||||||
/// print(x)
|
|
||||||
/// }
|
|
||||||
/// // 1, 2, 6, 3, 4, 20, 5, 6
|
|
||||||
@inlinable
|
|
||||||
public func joined(
|
|
||||||
by separator: (Element, Element) throws -> Element.Element
|
|
||||||
) rethrows -> [Element.Element] {
|
|
||||||
try _joined(by: { $0.append(try separator($1, $2)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
|
||||||
/// inserting the separator produced by the closure between each sequence.
|
|
||||||
///
|
|
||||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: { [100 * $0.last!, 100 * $1.first!] }) {
|
|
||||||
/// print(x)
|
|
||||||
/// }
|
|
||||||
/// // 1, 2, 200, 300, 3, 4, 400, 500, 5, 6
|
|
||||||
@inlinable
|
|
||||||
public func joined<Separator>(
|
|
||||||
by separator: (Element, Element) throws -> Separator
|
|
||||||
) rethrows -> [Element.Element]
|
|
||||||
where Separator: Sequence, Separator.Element == Element.Element
|
|
||||||
{
|
|
||||||
try _joined(by: { $0.append(contentsOf: try separator($1, $2)) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// LazySequenceProtocol.joined(by:)
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
extension LazySequenceProtocol where Element: Sequence {
|
|
||||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
|
||||||
/// inserting the separator produced by the closure between each sequence.
|
|
||||||
@inlinable
|
|
||||||
public func joined(
|
|
||||||
by separator: @escaping (Element, Element) -> Element.Element
|
|
||||||
) -> JoinedByClosureSequence<Elements, CollectionOfOne<Element.Element>> {
|
|
||||||
joined(by: { CollectionOfOne(separator($0, $1)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
|
||||||
/// inserting the separator produced by the closure between each sequence.
|
|
||||||
@inlinable
|
|
||||||
public func joined<Separator>(
|
|
||||||
by separator: @escaping (Element, Element) -> Separator
|
|
||||||
) -> JoinedByClosureSequence<Elements, Separator> {
|
|
||||||
JoinedByClosureSequence(base: elements, separator: separator)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// Collection.joined(by:)
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
extension Collection where Element: Collection {
|
|
||||||
/// Returns the concatenation of the elements in this collection of
|
|
||||||
/// collections, inserting the given separator between each collection.
|
|
||||||
///
|
|
||||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: 100) {
|
|
||||||
/// print(x)
|
|
||||||
/// }
|
|
||||||
/// // 1, 2, 100, 3, 4, 100, 5, 6
|
|
||||||
@inlinable
|
|
||||||
public func joined(by separator: Element.Element)
|
|
||||||
-> JoinedByCollection<Self, CollectionOfOne<Element.Element>>
|
|
||||||
{
|
|
||||||
joined(by: CollectionOfOne(separator))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the concatenation of the elements in this collection of
|
|
||||||
/// collections, inserting the given separator between each collection.
|
|
||||||
///
|
|
||||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: [100, 200]) {
|
|
||||||
/// print(x)
|
|
||||||
/// }
|
|
||||||
/// // 1, 2, 100, 200, 3, 4, 100, 200, 5, 6
|
|
||||||
@inlinable
|
|
||||||
public func joined<Separator>(by separator: Separator)
|
|
||||||
-> JoinedByCollection<Self, Separator>
|
|
||||||
{
|
|
||||||
JoinedByCollection(base: self, separator: separator)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// LazySequenceProtocol.joined(by:) where Self: Collection
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
extension LazySequenceProtocol where Elements: Collection, Element: Collection {
|
|
||||||
/// Returns the concatenation of the elements in this collection of
|
|
||||||
/// collections, inserting the separator produced by the closure between each
|
|
||||||
/// sequence.
|
|
||||||
@inlinable
|
|
||||||
public func joined(
|
|
||||||
by separator: @escaping (Element, Element) -> Element.Element
|
|
||||||
) -> JoinedByClosureCollection<Elements, CollectionOfOne<Element.Element>> {
|
|
||||||
joined(by: { CollectionOfOne(separator($0, $1)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the concatenation of the elements in this collection of
|
|
||||||
/// collections, inserting the separator produced by the closure between each
|
|
||||||
/// sequence.
|
|
||||||
@inlinable
|
|
||||||
public func joined<Separator>(
|
|
||||||
by separator: @escaping (Element, Element) -> Separator
|
|
||||||
) -> JoinedByClosureCollection<Elements, Separator> {
|
|
||||||
JoinedByClosureCollection(base: elements, separator: separator)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,9 +10,8 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// SplitSequence
|
// LazySplitSequence
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
/// A sequence that lazily splits a base sequence into subsequences separated by
|
/// A sequence that lazily splits a base sequence into subsequences separated by
|
||||||
/// elements that satisfy the given `whereSeparator` predicate.
|
/// elements that satisfy the given `whereSeparator` predicate.
|
||||||
///
|
///
|
||||||
@@ -22,7 +21,7 @@
|
|||||||
/// x.split(separator:maxSplits:omittingEmptySubsequences)
|
/// x.split(separator:maxSplits:omittingEmptySubsequences)
|
||||||
///
|
///
|
||||||
/// where `x` conforms to `LazySequenceProtocol`.
|
/// where `x` conforms to `LazySequenceProtocol`.
|
||||||
public struct SplitSequence<Base: Sequence> {
|
public struct LazySplitSequence<Base: Sequence> {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@@ -49,7 +48,7 @@ public struct SplitSequence<Base: Sequence> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SplitSequence: Sequence {
|
extension LazySplitSequence {
|
||||||
public struct Iterator {
|
public struct Iterator {
|
||||||
public typealias Element = [Base.Element]
|
public typealias Element = [Base.Element]
|
||||||
|
|
||||||
@@ -86,19 +85,9 @@ extension SplitSequence: Sequence {
|
|||||||
self.omittingEmptySubsequences = omittingEmptySubsequences
|
self.omittingEmptySubsequences = omittingEmptySubsequences
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func makeIterator() -> Iterator {
|
|
||||||
Iterator(
|
|
||||||
base: base.makeIterator(),
|
|
||||||
whereSeparator: self.isSeparator,
|
|
||||||
maxSplits: self.maxSplits,
|
|
||||||
omittingEmptySubsequences: self.omittingEmptySubsequences
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SplitSequence.Iterator: IteratorProtocol {
|
extension LazySplitSequence.Iterator: IteratorProtocol {
|
||||||
@inlinable
|
@inlinable
|
||||||
public mutating func next() -> Element? {
|
public mutating func next() -> Element? {
|
||||||
var currentElement = base.next()
|
var currentElement = base.next()
|
||||||
@@ -139,7 +128,17 @@ extension SplitSequence.Iterator: IteratorProtocol {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SplitSequence: LazySequenceProtocol {}
|
extension LazySplitSequence: LazySequenceProtocol {
|
||||||
|
@inlinable
|
||||||
|
public func makeIterator() -> Iterator {
|
||||||
|
return Iterator(
|
||||||
|
base: base.makeIterator(),
|
||||||
|
whereSeparator: self.isSeparator,
|
||||||
|
maxSplits: self.maxSplits,
|
||||||
|
omittingEmptySubsequences: self.omittingEmptySubsequences
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
extension LazySequenceProtocol {
|
extension LazySequenceProtocol {
|
||||||
/// Lazily returns the longest possible subsequences of the sequence, in
|
/// Lazily returns the longest possible subsequences of the sequence, in
|
||||||
@@ -231,10 +230,10 @@ extension LazySequenceProtocol {
|
|||||||
maxSplits: Int = Int.max,
|
maxSplits: Int = Int.max,
|
||||||
omittingEmptySubsequences: Bool = true,
|
omittingEmptySubsequences: Bool = true,
|
||||||
whereSeparator isSeparator: @escaping (Element) -> Bool
|
whereSeparator isSeparator: @escaping (Element) -> Bool
|
||||||
) -> SplitSequence<Elements> {
|
) -> LazySplitSequence<Elements> {
|
||||||
precondition(maxSplits >= 0, "Must take zero or more splits")
|
precondition(maxSplits >= 0, "Must take zero or more splits")
|
||||||
|
|
||||||
return SplitSequence(
|
return LazySplitSequence(
|
||||||
base: elements,
|
base: elements,
|
||||||
isSeparator: isSeparator,
|
isSeparator: isSeparator,
|
||||||
maxSplits: maxSplits,
|
maxSplits: maxSplits,
|
||||||
@@ -321,10 +320,10 @@ extension LazySequenceProtocol where Element: Equatable {
|
|||||||
separator: Element,
|
separator: Element,
|
||||||
maxSplits: Int = Int.max,
|
maxSplits: Int = Int.max,
|
||||||
omittingEmptySubsequences: Bool = true
|
omittingEmptySubsequences: Bool = true
|
||||||
) -> SplitSequence<Elements> {
|
) -> LazySplitSequence<Elements> {
|
||||||
precondition(maxSplits >= 0, "Must take zero or more splits")
|
precondition(maxSplits >= 0, "Must take zero or more splits")
|
||||||
|
|
||||||
return SplitSequence(
|
return LazySplitSequence(
|
||||||
base: elements,
|
base: elements,
|
||||||
isSeparator: { $0 == separator },
|
isSeparator: { $0 == separator },
|
||||||
maxSplits: maxSplits,
|
maxSplits: maxSplits,
|
||||||
@@ -334,9 +333,8 @@ extension LazySequenceProtocol where Element: Equatable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// SplitCollection
|
// LazySplitCollection
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
/// A collection that lazily splits a base collection into subsequences
|
/// A collection that lazily splits a base collection into subsequences
|
||||||
/// separated by elements that satisfy the given `whereSeparator` predicate.
|
/// separated by elements that satisfy the given `whereSeparator` predicate.
|
||||||
///
|
///
|
||||||
@@ -345,8 +343,8 @@ extension LazySequenceProtocol where Element: Equatable {
|
|||||||
/// x.split(maxSplits:omittingEmptySubsequences:whereSeparator)
|
/// x.split(maxSplits:omittingEmptySubsequences:whereSeparator)
|
||||||
/// x.split(separator:maxSplits:omittingEmptySubsequences)
|
/// x.split(separator:maxSplits:omittingEmptySubsequences)
|
||||||
///
|
///
|
||||||
/// where `x` conforms to `LazySequenceProtocol` and `Collection`.
|
/// where `x` conforms to `LazyCollectionProtocol`.
|
||||||
public struct SplitCollection<Base: Collection> {
|
public struct LazySplitCollection<Base: Collection> {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@@ -400,7 +398,7 @@ public struct SplitCollection<Base: Collection> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SplitCollection: Collection {
|
extension LazySplitCollection: LazyCollectionProtocol {
|
||||||
/// Position of a subsequence in a split collection.
|
/// Position of a subsequence in a split collection.
|
||||||
public struct Index: Comparable {
|
public struct Index: Comparable {
|
||||||
/// The range corresponding to the subsequence at this position.
|
/// The range corresponding to the subsequence at this position.
|
||||||
@@ -477,7 +475,7 @@ extension SplitCollection: Collection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var updatedSplitCount = splitCount
|
var updatedSplitCount = splitCount
|
||||||
if end != base.endIndex {
|
if end < base.endIndex {
|
||||||
// This subsequence ends on a separator (and perhaps includes other
|
// This subsequence ends on a separator (and perhaps includes other
|
||||||
// separators, if we're omitting empty subsequences), so we've performed
|
// separators, if we're omitting empty subsequences), so we've performed
|
||||||
// another split.
|
// another split.
|
||||||
@@ -549,16 +547,13 @@ extension SplitCollection: Collection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SplitCollection.Index: Hashable {
|
extension LazySplitCollection.Index: Hashable {
|
||||||
@inlinable
|
|
||||||
public func hash(into hasher: inout Hasher) {
|
public func hash(into hasher: inout Hasher) {
|
||||||
hasher.combine(sequenceLength)
|
hasher.combine(sequenceLength)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SplitCollection: LazyCollectionProtocol {}
|
extension LazyCollectionProtocol {
|
||||||
|
|
||||||
extension LazySequenceProtocol where Self: Collection, Elements: Collection {
|
|
||||||
/// Lazily returns the longest possible subsequences of the collection, in
|
/// Lazily returns the longest possible subsequences of the collection, in
|
||||||
/// order, that don't contain elements satisfying the given predicate.
|
/// order, that don't contain elements satisfying the given predicate.
|
||||||
///
|
///
|
||||||
@@ -646,10 +641,10 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
|
|||||||
maxSplits: Int = Int.max,
|
maxSplits: Int = Int.max,
|
||||||
omittingEmptySubsequences: Bool = true,
|
omittingEmptySubsequences: Bool = true,
|
||||||
whereSeparator isSeparator: @escaping (Element) -> Bool
|
whereSeparator isSeparator: @escaping (Element) -> Bool
|
||||||
) -> SplitCollection<Elements> {
|
) -> LazySplitCollection<Elements> {
|
||||||
precondition(maxSplits >= 0, "Must take zero or more splits")
|
precondition(maxSplits >= 0, "Must take zero or more splits")
|
||||||
|
|
||||||
return SplitCollection(
|
return LazySplitCollection(
|
||||||
base: elements,
|
base: elements,
|
||||||
isSeparator: isSeparator,
|
isSeparator: isSeparator,
|
||||||
maxSplits: maxSplits,
|
maxSplits: maxSplits,
|
||||||
@@ -658,9 +653,8 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension LazySequenceProtocol
|
extension LazyCollectionProtocol
|
||||||
where Self: Collection, Elements: Collection, Element: Equatable
|
where Element: Equatable {
|
||||||
{
|
|
||||||
/// Lazily returns the longest possible subsequences of the collection, in
|
/// Lazily returns the longest possible subsequences of the collection, in
|
||||||
/// order, around elements equal to the given element.
|
/// order, around elements equal to the given element.
|
||||||
///
|
///
|
||||||
@@ -743,10 +737,10 @@ extension LazySequenceProtocol
|
|||||||
separator: Element,
|
separator: Element,
|
||||||
maxSplits: Int = Int.max,
|
maxSplits: Int = Int.max,
|
||||||
omittingEmptySubsequences: Bool = true
|
omittingEmptySubsequences: Bool = true
|
||||||
) -> SplitCollection<Elements> {
|
) -> LazySplitCollection<Elements> {
|
||||||
precondition(maxSplits >= 0, "Must take zero or more splits")
|
precondition(maxSplits >= 0, "Must take zero or more splits")
|
||||||
|
|
||||||
return SplitCollection(
|
return LazySplitCollection(
|
||||||
base: elements,
|
base: elements,
|
||||||
isSeparator: { $0 == separator },
|
isSeparator: { $0 == separator },
|
||||||
maxSplits: maxSplits,
|
maxSplits: maxSplits,
|
||||||
+27
-116
@@ -17,26 +17,28 @@ extension Sequence {
|
|||||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||||
) rethrows -> [Element] {
|
) rethrows -> [Element] {
|
||||||
var iterator = makeIterator()
|
var iterator = makeIterator()
|
||||||
|
|
||||||
var result: [Element] = []
|
var result: [Element] = []
|
||||||
result.reserveCapacity(count)
|
result.reserveCapacity(count)
|
||||||
while result.count < count, let e = iterator.next() {
|
while result.count < count, let e = iterator.next() {
|
||||||
result.append(e)
|
result.append(e)
|
||||||
}
|
}
|
||||||
try result.sort(by: areInIncreasingOrder)
|
try result.sort(by: areInIncreasingOrder)
|
||||||
|
|
||||||
while let e = iterator.next() {
|
while let e = iterator.next() {
|
||||||
// To be part of `result`, `e` must be strictly less than `result.last`.
|
// To be part of `result`, `e` must be strictly less than `result.last`.
|
||||||
guard try areInIncreasingOrder(e, result.last!) else { continue }
|
guard try areInIncreasingOrder(e, result.last!) else { continue }
|
||||||
result.removeLast()
|
|
||||||
let insertionIndex =
|
let insertionIndex =
|
||||||
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
|
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
|
||||||
|
|
||||||
|
assert(insertionIndex != result.endIndex)
|
||||||
|
result.removeLast()
|
||||||
result.insert(e, at: insertionIndex)
|
result.insert(e, at: insertionIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Implementation for max(count:areInIncreasingOrder:)
|
/// Implementation for max(count:areInIncreasingOrder:)
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func _maxImplementation(
|
internal func _maxImplementation(
|
||||||
@@ -44,14 +46,14 @@ extension Sequence {
|
|||||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||||
) rethrows -> [Element] {
|
) rethrows -> [Element] {
|
||||||
var iterator = makeIterator()
|
var iterator = makeIterator()
|
||||||
|
|
||||||
var result: [Element] = []
|
var result: [Element] = []
|
||||||
result.reserveCapacity(count)
|
result.reserveCapacity(count)
|
||||||
while result.count < count, let e = iterator.next() {
|
while result.count < count, let e = iterator.next() {
|
||||||
result.append(e)
|
result.append(e)
|
||||||
}
|
}
|
||||||
try result.sort(by: areInIncreasingOrder)
|
try result.sort(by: areInIncreasingOrder)
|
||||||
|
|
||||||
while let e = iterator.next() {
|
while let e = iterator.next() {
|
||||||
// To be part of `result`, `e` must be greater/equal to `result.first`.
|
// To be part of `result`, `e` must be greater/equal to `result.first`.
|
||||||
guard try !areInIncreasingOrder(e, result.first!) else { continue }
|
guard try !areInIncreasingOrder(e, result.first!) else { continue }
|
||||||
@@ -69,10 +71,10 @@ extension Sequence {
|
|||||||
}
|
}
|
||||||
result[insertionIndex - 1] = e
|
result[insertionIndex - 1] = e
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the smallest elements of this sequence, as sorted by the given
|
/// Returns the smallest elements of this sequence, as sorted by the given
|
||||||
/// predicate.
|
/// predicate.
|
||||||
///
|
///
|
||||||
@@ -105,7 +107,9 @@ extension Sequence {
|
|||||||
count: Int,
|
count: Int,
|
||||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||||
) rethrows -> [Element] {
|
) rethrows -> [Element] {
|
||||||
precondition(count >= 0, """
|
precondition(
|
||||||
|
count >= 0,
|
||||||
|
"""
|
||||||
Cannot find a minimum with a negative count of elements!
|
Cannot find a minimum with a negative count of elements!
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
@@ -150,7 +154,9 @@ extension Sequence {
|
|||||||
count: Int,
|
count: Int,
|
||||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||||
) rethrows -> [Element] {
|
) rethrows -> [Element] {
|
||||||
precondition(count >= 0, """
|
precondition(
|
||||||
|
count >= 0,
|
||||||
|
"""
|
||||||
Cannot find a maximum with a negative count of elements!
|
Cannot find a maximum with a negative count of elements!
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
@@ -188,7 +194,7 @@ extension Sequence where Element: Comparable {
|
|||||||
/// sequence and *k* is `count`.
|
/// sequence and *k* is `count`.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func min(count: Int) -> [Element] {
|
public func min(count: Int) -> [Element] {
|
||||||
min(count: count, sortedBy: <)
|
return min(count: count, sortedBy: <)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the largest elements of this sequence.
|
/// Returns the largest elements of this sequence.
|
||||||
@@ -214,7 +220,7 @@ extension Sequence where Element: Comparable {
|
|||||||
/// sequence and *k* is `count`.
|
/// sequence and *k* is `count`.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func max(count: Int) -> [Element] {
|
public func max(count: Int) -> [Element] {
|
||||||
max(count: count, sortedBy: <)
|
return max(count: count, sortedBy: <)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -251,7 +257,9 @@ extension Collection {
|
|||||||
count: Int,
|
count: Int,
|
||||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||||
) rethrows -> [Element] {
|
) rethrows -> [Element] {
|
||||||
precondition(count >= 0, """
|
precondition(
|
||||||
|
count >= 0,
|
||||||
|
"""
|
||||||
Cannot find a minimum with a negative count of elements!
|
Cannot find a minimum with a negative count of elements!
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
@@ -269,7 +277,7 @@ extension Collection {
|
|||||||
guard prefixCount < (self.count / 10) else {
|
guard prefixCount < (self.count / 10) else {
|
||||||
return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount))
|
return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount))
|
||||||
}
|
}
|
||||||
|
|
||||||
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
|
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -305,7 +313,9 @@ extension Collection {
|
|||||||
count: Int,
|
count: Int,
|
||||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||||
) rethrows -> [Element] {
|
) rethrows -> [Element] {
|
||||||
precondition(count >= 0, """
|
precondition(
|
||||||
|
count >= 0,
|
||||||
|
"""
|
||||||
Cannot find a maximum with a negative count of elements!
|
Cannot find a maximum with a negative count of elements!
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
@@ -352,7 +362,7 @@ extension Collection where Element: Comparable {
|
|||||||
/// collection and *k* is `count`.
|
/// collection and *k* is `count`.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func min(count: Int) -> [Element] {
|
public func min(count: Int) -> [Element] {
|
||||||
min(count: count, sortedBy: <)
|
return min(count: count, sortedBy: <)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the largest elements of this collection.
|
/// Returns the largest elements of this collection.
|
||||||
@@ -378,105 +388,6 @@ extension Collection where Element: Comparable {
|
|||||||
/// collection and *k* is `count`.
|
/// collection and *k* is `count`.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func max(count: Int) -> [Element] {
|
public func max(count: Int) -> [Element] {
|
||||||
max(count: count, sortedBy: <)
|
return max(count: count, sortedBy: <)
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// Simultaneous minimum and maximum evaluation
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
extension Sequence {
|
|
||||||
/// Returns both the minimum and maximum elements in the sequence, using the
|
|
||||||
/// given predicate as the comparison between elements.
|
|
||||||
///
|
|
||||||
/// The predicate must be a *strict weak ordering* over the elements. That is,
|
|
||||||
/// for any elements `a`, `b`, and `c`, the following conditions must hold:
|
|
||||||
///
|
|
||||||
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
|
|
||||||
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
|
|
||||||
/// both `true`, then `areInIncreasingOrder(a, c)` is also
|
|
||||||
/// `true`. (Transitive comparability)
|
|
||||||
/// - Two elements are *incomparable* if neither is ordered before the other
|
|
||||||
/// according to the predicate. If `a` and `b` are incomparable, and `b`
|
|
||||||
/// and `c` are incomparable, then `a` and `c` are also incomparable.
|
|
||||||
/// (Transitive incomparability)
|
|
||||||
///
|
|
||||||
/// This example shows how to use the `minAndMax(by:)` method on a dictionary
|
|
||||||
/// to find the key-value pair with the lowest value and the pair with the
|
|
||||||
/// highest value.
|
|
||||||
///
|
|
||||||
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
|
|
||||||
/// if let extremeHues = hues.minAndMax(by: {$0.value < $1.value}) {
|
|
||||||
/// print(extremeHues.min, extremeHues.max)
|
|
||||||
/// } else {
|
|
||||||
/// print("There are no hues")
|
|
||||||
/// }
|
|
||||||
/// // Prints: "(key: "Coral", value: 16) (key: "Heliotrope", value: 296)"
|
|
||||||
///
|
|
||||||
/// - Precondition: The sequence is finite.
|
|
||||||
///
|
|
||||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
|
|
||||||
/// first argument should be ordered before its second argument; otherwise,
|
|
||||||
/// `false`.
|
|
||||||
/// - Returns: A tuple with the sequence's minimum element, followed by its
|
|
||||||
/// maximum element. If the sequence provides multiple qualifying minimum
|
|
||||||
/// elements, the first equivalent element is returned; of multiple maximum
|
|
||||||
/// elements, the last is returned. If the sequence has no elements, the
|
|
||||||
/// method returns `nil`.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
|
||||||
@inlinable
|
|
||||||
public func minAndMax(
|
|
||||||
by areInIncreasingOrder: (Element, Element) throws -> Bool
|
|
||||||
) rethrows -> (min: Element, max: Element)? {
|
|
||||||
// Check short sequences.
|
|
||||||
var iterator = makeIterator()
|
|
||||||
guard var lowest = iterator.next() else { return nil }
|
|
||||||
guard var highest = iterator.next() else { return (lowest, lowest) }
|
|
||||||
|
|
||||||
// Confirm the initial bounds.
|
|
||||||
if try areInIncreasingOrder(highest, lowest) { swap(&lowest, &highest) }
|
|
||||||
|
|
||||||
// Read the elements in pairwise. Structuring the comparisons around this
|
|
||||||
// is actually faster than loops based on extracting and testing elements
|
|
||||||
// one-at-a-time.
|
|
||||||
while var low = iterator.next() {
|
|
||||||
var high = iterator.next() ?? low
|
|
||||||
if try areInIncreasingOrder(high, low) { swap(&low, &high) }
|
|
||||||
if try areInIncreasingOrder(low, lowest) { lowest = low }
|
|
||||||
if try !areInIncreasingOrder(high, highest) { highest = high }
|
|
||||||
}
|
|
||||||
|
|
||||||
return (lowest, highest)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Sequence where Element: Comparable {
|
|
||||||
/// Returns both the minimum and maximum elements in the sequence.
|
|
||||||
///
|
|
||||||
/// This example finds the smallest and largest values in an array of height
|
|
||||||
/// measurements.
|
|
||||||
///
|
|
||||||
/// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
|
|
||||||
/// if let (lowestHeight, greatestHeight) = heights.minAndMax() {
|
|
||||||
/// print(lowestHeight, greatestHeight)
|
|
||||||
/// } else {
|
|
||||||
/// print("The list of heights is empty")
|
|
||||||
/// }
|
|
||||||
/// // Prints: "58.5 67.5"
|
|
||||||
///
|
|
||||||
/// - Precondition: The sequence is finite.
|
|
||||||
///
|
|
||||||
/// - Returns: A tuple with the sequence's minimum element, followed by its
|
|
||||||
/// maximum element. If the sequence provides multiple qualifying minimum
|
|
||||||
/// elements, the first equivalent element is returned; of multiple maximum
|
|
||||||
/// elements, the last is returned. If the sequence has no elements, the
|
|
||||||
/// method returns `nil`.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
|
||||||
@inlinable
|
|
||||||
public func minAndMax() -> (min: Element, max: Element)? {
|
|
||||||
minAndMax(by: <)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
//
|
//
|
||||||
// This source file is part of the Swift Algorithms open source project
|
// This source file is part of the Swift Algorithms open source project
|
||||||
//
|
//
|
||||||
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
|
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||||
//
|
//
|
||||||
// See https://swift.org/LICENSE.txt for license information
|
// See https://swift.org/LICENSE.txt for license information
|
||||||
@@ -14,9 +14,9 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
extension MutableCollection {
|
extension MutableCollection {
|
||||||
/// Moves all elements satisfying `belongsInSecondPartition` into a suffix of
|
/// Moves all elements satisfying `belongsInSecondPartition` into a suffix
|
||||||
/// the collection, preserving their relative order, and returns the start of
|
/// of the collection, preserving their relative order, and returns the
|
||||||
/// the resulting suffix.
|
/// start of the resulting suffix.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(*n* log *n*), where *n* is the number of elements.
|
/// - Complexity: O(*n* log *n*), where *n* is the number of elements.
|
||||||
/// - Precondition:
|
/// - Precondition:
|
||||||
@@ -33,8 +33,9 @@ extension MutableCollection {
|
|||||||
? subrange.lowerBound
|
? subrange.lowerBound
|
||||||
: subrange.upperBound
|
: subrange.upperBound
|
||||||
}
|
}
|
||||||
|
|
||||||
let h = n / 2, i = index(subrange.lowerBound, offsetBy: h)
|
let h = n / 2
|
||||||
|
let i = index(subrange.lowerBound, offsetBy: h)
|
||||||
let j = try stablePartition(
|
let j = try stablePartition(
|
||||||
count: h,
|
count: h,
|
||||||
subrange: subrange.lowerBound..<i,
|
subrange: subrange.lowerBound..<i,
|
||||||
@@ -45,7 +46,7 @@ extension MutableCollection {
|
|||||||
by: belongsInSecondPartition)
|
by: belongsInSecondPartition)
|
||||||
return rotate(subrange: j..<k, toStartAt: i)
|
return rotate(subrange: j..<k, toStartAt: i)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Moves all elements satisfying the given predicate into a suffix of the
|
/// Moves all elements satisfying the given predicate into a suffix of the
|
||||||
/// given range, preserving the relative order of the elements in both
|
/// given range, preserving the relative order of the elements in both
|
||||||
/// partitions, and returns the start of the resulting suffix.
|
/// partitions, and returns the start of the resulting suffix.
|
||||||
@@ -60,14 +61,14 @@ extension MutableCollection {
|
|||||||
@inlinable
|
@inlinable
|
||||||
public mutating func stablePartition(
|
public mutating func stablePartition(
|
||||||
subrange: Range<Index>,
|
subrange: Range<Index>,
|
||||||
by belongsInSecondPartition: (Element) throws-> Bool
|
by belongsInSecondPartition: (Element) throws -> Bool
|
||||||
) rethrows -> Index {
|
) rethrows -> Index {
|
||||||
try stablePartition(
|
try stablePartition(
|
||||||
count: distance(from: subrange.lowerBound, to: subrange.upperBound),
|
count: distance(from: subrange.lowerBound, to: subrange.upperBound),
|
||||||
subrange: subrange,
|
subrange: subrange,
|
||||||
by: belongsInSecondPartition)
|
by: belongsInSecondPartition)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Moves all elements satisfying the given predicate into a suffix of this
|
/// Moves all elements satisfying the given predicate into a suffix of this
|
||||||
/// collection, preserving the relative order of the elements in both
|
/// collection, preserving the relative order of the elements in both
|
||||||
/// partitions, and returns the start of the resulting suffix.
|
/// partitions, and returns the start of the resulting suffix.
|
||||||
@@ -79,7 +80,7 @@ extension MutableCollection {
|
|||||||
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
|
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
|
||||||
@inlinable
|
@inlinable
|
||||||
public mutating func stablePartition(
|
public mutating func stablePartition(
|
||||||
by belongsInSecondPartition: (Element) throws-> Bool
|
by belongsInSecondPartition: (Element) throws -> Bool
|
||||||
) rethrows -> Index {
|
) rethrows -> Index {
|
||||||
try stablePartition(
|
try stablePartition(
|
||||||
subrange: startIndex..<endIndex,
|
subrange: startIndex..<endIndex,
|
||||||
@@ -104,8 +105,8 @@ extension MutableCollection {
|
|||||||
// This version of `partition(subrange:)` is half stable; the elements in
|
// This version of `partition(subrange:)` is half stable; the elements in
|
||||||
// the first partition retain their original relative order.
|
// the first partition retain their original relative order.
|
||||||
guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition)
|
guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition)
|
||||||
else { return subrange.upperBound }
|
else { return subrange.upperBound }
|
||||||
|
|
||||||
var j = index(after: i)
|
var j = index(after: i)
|
||||||
while j != subrange.upperBound {
|
while j != subrange.upperBound {
|
||||||
if try !belongsInSecondPartition(self[j]) {
|
if try !belongsInSecondPartition(self[j]) {
|
||||||
@@ -114,7 +115,7 @@ extension MutableCollection {
|
|||||||
}
|
}
|
||||||
formIndex(after: &j)
|
formIndex(after: &j)
|
||||||
}
|
}
|
||||||
|
|
||||||
return i
|
return i
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -138,22 +139,22 @@ extension MutableCollection where Self: BidirectionalCollection {
|
|||||||
// * predicate(self[i]) == true, for i in hi ..< endIndex
|
// * predicate(self[i]) == true, for i in hi ..< endIndex
|
||||||
|
|
||||||
Loop: while true {
|
Loop: while true {
|
||||||
FindLo: do {
|
FindLo: repeat {
|
||||||
while lo < hi {
|
while lo < hi {
|
||||||
if try belongsInSecondPartition(self[lo]) { break FindLo }
|
if try belongsInSecondPartition(self[lo]) { break FindLo }
|
||||||
formIndex(after: &lo)
|
formIndex(after: &lo)
|
||||||
}
|
}
|
||||||
break Loop
|
break Loop
|
||||||
}
|
} while false
|
||||||
|
|
||||||
FindHi: do {
|
FindHi: repeat {
|
||||||
formIndex(before: &hi)
|
formIndex(before: &hi)
|
||||||
while lo < hi {
|
while lo < hi {
|
||||||
if try !belongsInSecondPartition(self[hi]) { break FindHi }
|
if try !belongsInSecondPartition(self[hi]) { break FindHi }
|
||||||
formIndex(before: &hi)
|
formIndex(before: &hi)
|
||||||
}
|
}
|
||||||
break Loop
|
break Loop
|
||||||
}
|
} while false
|
||||||
|
|
||||||
swapAt(lo, hi)
|
swapAt(lo, hi)
|
||||||
formIndex(after: &lo)
|
formIndex(after: &lo)
|
||||||
@@ -168,19 +169,18 @@ extension MutableCollection where Self: BidirectionalCollection {
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
extension Collection {
|
extension Collection {
|
||||||
/// Returns the start index of the partition of a collection that matches
|
/// Returns the index of the first element in the collection that matches
|
||||||
/// the given predicate.
|
/// the predicate.
|
||||||
///
|
///
|
||||||
/// The collection must already be partitioned according to the predicate.
|
/// The collection must already be partitioned according to the predicate.
|
||||||
/// That is, there should be an index `i` where for every element in
|
/// That is, there should be an index `i` where for every element in
|
||||||
/// `collection[..<i]` the predicate is `false`, and for every element in
|
/// `collection[..<i]` the predicate is `false`, and for every element
|
||||||
/// `collection[i...]` the predicate is `true`.
|
/// in `collection[i...]` the predicate is `true`.
|
||||||
///
|
///
|
||||||
/// - Parameter belongsInSecondPartition: A predicate that partitions the
|
/// - Parameter belongsInSecondPartition: A predicate that partitions the
|
||||||
/// collection.
|
/// collection.
|
||||||
/// - Returns: The index of the first element in the collection for which
|
/// - Returns: The index of the first element in the collection for which
|
||||||
/// `predicate` returns `true`, or `endIndex` if there are no elements
|
/// `predicate` returns `true`.
|
||||||
/// for which `predicate` returns `true`.
|
|
||||||
///
|
///
|
||||||
/// - Complexity: O(log *n*), where *n* is the length of this collection if
|
/// - Complexity: O(log *n*), where *n* is the length of this collection if
|
||||||
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
|
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
|
||||||
@@ -190,7 +190,7 @@ extension Collection {
|
|||||||
) rethrows -> Index {
|
) rethrows -> Index {
|
||||||
var n = count
|
var n = count
|
||||||
var l = startIndex
|
var l = startIndex
|
||||||
|
|
||||||
while n > 0 {
|
while n > 0 {
|
||||||
let half = n / 2
|
let half = n / 2
|
||||||
let mid = index(l, offsetBy: half)
|
let mid = index(l, offsetBy: half)
|
||||||
@@ -204,138 +204,3 @@ extension Collection {
|
|||||||
return l
|
return l
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// partitioned(by:)
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
extension Sequence {
|
|
||||||
/// Returns two arrays containing, in order, the elements of the sequence that
|
|
||||||
/// do and don’t satisfy the given predicate.
|
|
||||||
///
|
|
||||||
/// In this example, `partitioned(by:)` is used to separate the input based on
|
|
||||||
/// whether a name is shorter than five characters:
|
|
||||||
///
|
|
||||||
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
|
||||||
/// let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
|
||||||
/// print(longNames)
|
|
||||||
/// // Prints "["Vivien", "Marlon"]"
|
|
||||||
/// print(shortNames)
|
|
||||||
/// // Prints "["Kim", "Karl"]"
|
|
||||||
///
|
|
||||||
/// - Parameter predicate: A closure that takes an element of the sequence as
|
|
||||||
/// its argument and returns a Boolean value indicating whether the element
|
|
||||||
/// should be included in the second returned array. Otherwise, the element
|
|
||||||
/// will appear in the first returned array.
|
|
||||||
///
|
|
||||||
/// - Returns: Two arrays with all of the elements of the receiver. The
|
|
||||||
/// first array contains all the elements that `predicate` didn’t allow, and
|
|
||||||
/// the second array contains all the elements that `predicate` allowed.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
|
||||||
@inlinable
|
|
||||||
public func partitioned(
|
|
||||||
by predicate: (Element) throws -> Bool
|
|
||||||
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
|
|
||||||
var lhs = [Element]()
|
|
||||||
var rhs = [Element]()
|
|
||||||
|
|
||||||
for element in self {
|
|
||||||
if try predicate(element) {
|
|
||||||
rhs.append(element)
|
|
||||||
} else {
|
|
||||||
lhs.append(element)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (lhs, rhs)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Collection {
|
|
||||||
/// Returns two arrays containing, in order, the elements of the collection
|
|
||||||
/// that do and don’t satisfy the given predicate.
|
|
||||||
///
|
|
||||||
/// In this example, `partitioned(by:)` is used to separate the input based on
|
|
||||||
/// whether a name is shorter than five characters.
|
|
||||||
///
|
|
||||||
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
|
||||||
/// let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
|
||||||
/// print(longNames)
|
|
||||||
/// // Prints "["Vivien", "Marlon"]"
|
|
||||||
/// print(shortNames)
|
|
||||||
/// // Prints "["Kim", "Karl"]"
|
|
||||||
///
|
|
||||||
/// - Parameter predicate: A closure that takes an element of the collection
|
|
||||||
/// as its argument and returns a Boolean value indicating whether the element
|
|
||||||
/// should be included in the second returned array. Otherwise, the element
|
|
||||||
/// will appear in the first returned array.
|
|
||||||
///
|
|
||||||
/// - Returns: Two arrays with all of the elements of the receiver. The
|
|
||||||
/// first array contains all the elements that `predicate` didn’t allow, and
|
|
||||||
/// the second array contains all the elements that `predicate` allowed.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
|
||||||
@inlinable
|
|
||||||
public func partitioned(
|
|
||||||
by predicate: (Element) throws -> Bool
|
|
||||||
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
|
|
||||||
guard !self.isEmpty else {
|
|
||||||
return ([], [])
|
|
||||||
}
|
|
||||||
|
|
||||||
// Since collections have known sizes, we can allocate one array of size
|
|
||||||
// `self.count`, then insert items at the beginning or end of that contiguous
|
|
||||||
// block. This way, we don’t have to do any dynamic array resizing. Since we
|
|
||||||
// insert the right elements on the right side in reverse order, we need to
|
|
||||||
// reverse them back to the original order at the end.
|
|
||||||
|
|
||||||
let count = self.count
|
|
||||||
|
|
||||||
// Inside of the `initializer` closure, we set what the actual mid-point is.
|
|
||||||
// We will use this to partition the single array into two.
|
|
||||||
var midPoint: Int = 0
|
|
||||||
|
|
||||||
let elements = try [Element](
|
|
||||||
unsafeUninitializedCapacity: count,
|
|
||||||
initializingWith: { buffer, initializedCount in
|
|
||||||
var lhs = buffer.baseAddress!
|
|
||||||
var rhs = lhs + buffer.count
|
|
||||||
do {
|
|
||||||
for element in self {
|
|
||||||
if try predicate(element) {
|
|
||||||
rhs -= 1
|
|
||||||
rhs.initialize(to: element)
|
|
||||||
} else {
|
|
||||||
lhs.initialize(to: element)
|
|
||||||
lhs += 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
precondition(lhs == rhs, """
|
|
||||||
Collection's `count` differed from the number of elements iterated.
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
|
|
||||||
let rhsIndex = rhs - buffer.baseAddress!
|
|
||||||
buffer[rhsIndex...].reverse()
|
|
||||||
initializedCount = buffer.count
|
|
||||||
|
|
||||||
midPoint = rhsIndex
|
|
||||||
} catch {
|
|
||||||
let lhsCount = lhs - buffer.baseAddress!
|
|
||||||
let rhsCount = (buffer.baseAddress! + buffer.count) - rhs
|
|
||||||
buffer.baseAddress!.deinitialize(count: lhsCount)
|
|
||||||
rhs.deinitialize(count: rhsCount)
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
let lhs = elements[..<midPoint]
|
|
||||||
let rhs = elements[midPoint...]
|
|
||||||
return (
|
|
||||||
Array(lhs),
|
|
||||||
Array(rhs)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -14,13 +14,12 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
extension MutableCollection
|
extension MutableCollection
|
||||||
where Self: BidirectionalCollection, Element: Comparable
|
where Self: BidirectionalCollection, Element: Comparable {
|
||||||
{
|
|
||||||
/// Permutes this collection's elements through all the lexical orderings.
|
/// Permutes this collection's elements through all the lexical orderings.
|
||||||
///
|
///
|
||||||
/// Call `nextPermutation()` repeatedly starting with the collection in sorted
|
/// Call `nextPermutation()` repeatedly starting with the collection in
|
||||||
/// order. When the full cycle of all permutations has been completed, the
|
/// sorted order. When the full cycle of all permutations has been completed,
|
||||||
/// collection will be back in sorted order and this method will return
|
/// the collection will be back in sorted order and this method will return
|
||||||
/// `false`.
|
/// `false`.
|
||||||
///
|
///
|
||||||
/// - Returns: A Boolean value indicating whether the collection still has
|
/// - Returns: A Boolean value indicating whether the collection still has
|
||||||
@@ -34,26 +33,26 @@ extension MutableCollection
|
|||||||
guard !isEmpty else { return false }
|
guard !isEmpty else { return false }
|
||||||
var i = index(before: endIndex)
|
var i = index(before: endIndex)
|
||||||
if i == startIndex { return false }
|
if i == startIndex { return false }
|
||||||
|
|
||||||
let upperBound = upperBound ?? endIndex
|
let upperBound = upperBound ?? endIndex
|
||||||
|
|
||||||
while true {
|
while true {
|
||||||
let ip1 = i
|
let ip1 = i
|
||||||
formIndex(before: &i)
|
formIndex(before: &i)
|
||||||
|
|
||||||
// Find the last ascending pair (ie. ..., a, b, ... where a < b)
|
// Find the last ascending pair (ie. ..., a, b, ... where a < b)
|
||||||
if self[i] < self[ip1] {
|
if self[i] < self[ip1] {
|
||||||
// Find the last element greater than self[i]
|
// Find the last element greater than self[i]
|
||||||
// This is _always_ at most `ip1` due to if statement above
|
// This is _always_ at most `ip1` due to if statement above
|
||||||
let j = lastIndex(where: { self[i] < $0 })!
|
let j = lastIndex(where: { self[i] < $0 })!
|
||||||
|
|
||||||
// At this point we have something like this:
|
// At this point we have something like this:
|
||||||
// 0, 1, 4, 3, 2
|
// 0, 1, 4, 3, 2
|
||||||
// ^ ^
|
// ^ ^
|
||||||
// i j
|
// i j
|
||||||
swapAt(i, j)
|
swapAt(i, j)
|
||||||
self.reverse(subrange: ip1 ..< endIndex)
|
self.reverse(subrange: ip1..<endIndex)
|
||||||
|
|
||||||
// Only return if we've made a change within ..<upperBound region
|
// Only return if we've made a change within ..<upperBound region
|
||||||
if i < upperBound {
|
if i < upperBound {
|
||||||
return true
|
return true
|
||||||
@@ -62,7 +61,7 @@ extension MutableCollection
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if i == startIndex {
|
if i == startIndex {
|
||||||
self.reverse()
|
self.reverse()
|
||||||
return false
|
return false
|
||||||
@@ -76,24 +75,21 @@ extension MutableCollection
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
/// A sequence of all the permutations of a collection's elements.
|
/// A sequence of all the permutations of a collection's elements.
|
||||||
public struct PermutationsSequence<Base: Collection> {
|
public struct Permutations<Base: Collection> {
|
||||||
/// The base collection to iterate over for permutations.
|
/// The base collection to iterate over for permutations.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let baseCount: Int
|
internal let baseCount: Int
|
||||||
|
|
||||||
/// The range of accepted sizes of permutations.
|
/// The range of accepted sizes of permutations.
|
||||||
///
|
|
||||||
/// - Note: This may be empty if the attempted range entirely exceeds the
|
/// - Note: This may be empty if the attempted range entirely exceeds the
|
||||||
/// bounds of the size of the `base` collection.
|
/// bounds of the size of the `base` collection.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let kRange: Range<Int>
|
internal let kRange: Range<Int>
|
||||||
|
|
||||||
/// Initializes a `PermutationsSequence` for all permutations of `base` of
|
/// Initializes a `Permutations` for all permutations of `base` of size `k`.
|
||||||
/// size `k`.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - base: The collection to iterate over for permutations
|
/// - base: The collection to iterate over for permutations
|
||||||
/// - k: The expected size of each permutation, or `nil` (default) to
|
/// - k: The expected size of each permutation, or `nil` (default) to
|
||||||
@@ -102,16 +98,15 @@ public struct PermutationsSequence<Base: Collection> {
|
|||||||
internal init(_ base: Base, k: Int? = nil) {
|
internal init(_ base: Base, k: Int? = nil) {
|
||||||
let kRange: ClosedRange<Int>?
|
let kRange: ClosedRange<Int>?
|
||||||
if let countToChoose = k {
|
if let countToChoose = k {
|
||||||
kRange = countToChoose ... countToChoose
|
kRange = countToChoose...countToChoose
|
||||||
} else {
|
} else {
|
||||||
kRange = nil
|
kRange = nil
|
||||||
}
|
}
|
||||||
self.init(base, kRange: kRange)
|
self.init(base, kRange: kRange)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Initializes a `PermutationsSequence` for all combinations of `base` of
|
/// Initializes a `Permutations` for all combinations of `base` of sizes
|
||||||
/// sizes within a given range.
|
/// within a given range.
|
||||||
///
|
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - base: The collection to iterate over for permutations.
|
/// - base: The collection to iterate over for permutations.
|
||||||
/// - kRange: The range of accepted sizes of permutations, or `nil` to
|
/// - kRange: The range of accepted sizes of permutations, or `nil` to
|
||||||
@@ -124,53 +119,53 @@ public struct PermutationsSequence<Base: Collection> {
|
|||||||
let baseCount = base.count
|
let baseCount = base.count
|
||||||
self.baseCount = baseCount
|
self.baseCount = baseCount
|
||||||
let upperBound = baseCount + 1
|
let upperBound = baseCount + 1
|
||||||
self.kRange = kRange?.relative(to: 0 ..< .max)
|
self.kRange =
|
||||||
.clamped(to: 0 ..< upperBound) ??
|
kRange?.relative(to: 0 ..< .max)
|
||||||
baseCount ..< upperBound
|
.clamped(to: 0..<upperBound) ?? baseCount..<upperBound
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The total number of permutations.
|
/// The total number of permutations.
|
||||||
@inlinable
|
@inlinable
|
||||||
public var count: Int {
|
public var count: Int {
|
||||||
kRange.map {
|
return kRange.map {
|
||||||
stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *)
|
stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *)
|
||||||
}.reduce(0, +)
|
}.reduce(0, +)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension PermutationsSequence: Sequence {
|
extension Permutations: Sequence {
|
||||||
/// The iterator for a `PermutationsSequence` instance.
|
/// The iterator for a `Permutations` instance.
|
||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let baseCount: Int
|
internal let baseCount: Int
|
||||||
|
|
||||||
/// The current range of accepted sizes of permutations.
|
/// The current range of accepted sizes of permutations.
|
||||||
/// - Note: The range is contracted until empty while iterating over
|
/// - Note: The range is contracted until empty while iterating over
|
||||||
/// permutations of different sizes. When the range is empty, iteration is
|
/// permutations of different sizes. When the range is empty, iteration is
|
||||||
/// finished.
|
/// finished.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var kRange: Range<Int>
|
internal var kRange: Range<Int>
|
||||||
|
|
||||||
/// Whether or not iteration is finished (`kRange` is empty)
|
/// Whether or not iteration is finished (`kRange` is empty)
|
||||||
@inlinable
|
@inlinable
|
||||||
internal var isFinished: Bool {
|
internal var isFinished: Bool {
|
||||||
return kRange.isEmpty
|
return kRange.isEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var indexes: [Base.Index]
|
internal var indexes: [Base.Index]
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(_ permutations: PermutationsSequence) {
|
internal init(_ permutations: Permutations) {
|
||||||
self.base = permutations.base
|
self.base = permutations.base
|
||||||
self.baseCount = permutations.baseCount
|
self.baseCount = permutations.baseCount
|
||||||
self.kRange = permutations.kRange
|
self.kRange = permutations.kRange
|
||||||
self.indexes = Array(permutations.base.indices)
|
self.indexes = Array(permutations.base.indices)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Advances the `indexes` array such that the first `countToChoose`
|
/// Advances the `indexes` array such that the first `countToChoose`
|
||||||
/// elements contain the next lexicographic ordering of elements.
|
/// elements contain the next lexicographic ordering of elements.
|
||||||
///
|
///
|
||||||
@@ -186,44 +181,44 @@ extension PermutationsSequence: Sequence {
|
|||||||
internal mutating func nextState() -> Bool {
|
internal mutating func nextState() -> Bool {
|
||||||
let countToChoose = self.kRange.lowerBound
|
let countToChoose = self.kRange.lowerBound
|
||||||
let edge = countToChoose - 1
|
let edge = countToChoose - 1
|
||||||
|
|
||||||
// Find first index greater than the one at `edge`.
|
// Find first index greater than the one at `edge`.
|
||||||
if let i = indexes[countToChoose...].firstIndex(where: { indexes[edge] < $0 }) {
|
if let i = indexes[countToChoose...].firstIndex(where: { indexes[edge] < $0 }) {
|
||||||
indexes.swapAt(edge, i)
|
indexes.swapAt(edge, i)
|
||||||
} else {
|
} else {
|
||||||
indexes.reverse(subrange: countToChoose ..< indexes.endIndex)
|
indexes.reverse(subrange: countToChoose..<indexes.endIndex)
|
||||||
|
|
||||||
// Find last increasing pair below `edge`.
|
// Find last increasing pair below `edge`.
|
||||||
// TODO: This could be indexes[..<edge].adjacentPairs().lastIndex(where: ...)
|
// TODO: This could be indexes[..<edge].adjacentPairs().lastIndex(where: ...)
|
||||||
var lastAscent = edge - 1
|
var lastAscent = edge - 1
|
||||||
while (lastAscent >= 0 && indexes[lastAscent] >= indexes[lastAscent + 1]) {
|
while lastAscent >= 0 && indexes[lastAscent] >= indexes[lastAscent + 1] {
|
||||||
lastAscent -= 1
|
lastAscent -= 1
|
||||||
}
|
}
|
||||||
if lastAscent < 0 {
|
if lastAscent < 0 {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find rightmost index less than that at `lastAscent`.
|
// Find rightmost index less than that at `lastAscent`.
|
||||||
if let i = indexes[lastAscent...].lastIndex(where: { indexes[lastAscent] < $0 }) {
|
if let i = indexes[lastAscent...].lastIndex(where: { indexes[lastAscent] < $0 }) {
|
||||||
indexes.swapAt(lastAscent, i)
|
indexes.swapAt(lastAscent, i)
|
||||||
}
|
}
|
||||||
indexes.reverse(subrange: (lastAscent + 1) ..< indexes.endIndex)
|
indexes.reverse(subrange: (lastAscent + 1)..<indexes.endIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public mutating func next() -> [Base.Element]? {
|
public mutating func next() -> [Base.Element]? {
|
||||||
guard !isFinished else { return nil }
|
guard !isFinished else { return nil }
|
||||||
|
|
||||||
/// Advances `kRange` by incrementing its `lowerBound` until the range is
|
/// Advances `kRange` by incrementing its `lowerBound` until the range is
|
||||||
/// empty, when iteration is finished.
|
/// empty, when iteration is finished.
|
||||||
func advanceKRange() {
|
func advanceKRange() {
|
||||||
kRange.removeFirst()
|
kRange.removeFirst()
|
||||||
indexes = Array(base.indices)
|
indexes = Array(base.indices)
|
||||||
}
|
}
|
||||||
|
|
||||||
let countToChoose = self.kRange.lowerBound
|
let countToChoose = self.kRange.lowerBound
|
||||||
if countToChoose == 0 {
|
if countToChoose == 0 {
|
||||||
defer {
|
defer {
|
||||||
@@ -231,7 +226,7 @@ extension PermutationsSequence: Sequence {
|
|||||||
}
|
}
|
||||||
return []
|
return []
|
||||||
}
|
}
|
||||||
|
|
||||||
let permutesFullCollection = (countToChoose == baseCount)
|
let permutesFullCollection = (countToChoose == baseCount)
|
||||||
if permutesFullCollection {
|
if permutesFullCollection {
|
||||||
// If we're permuting the full collection, each iteration is just a
|
// If we're permuting the full collection, each iteration is just a
|
||||||
@@ -256,15 +251,14 @@ extension PermutationsSequence: Sequence {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func makeIterator() -> Iterator {
|
public func makeIterator() -> Iterator {
|
||||||
Iterator(self)
|
Iterator(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension PermutationsSequence: LazySequenceProtocol
|
extension Permutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||||
where Base: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// permutations(ofCount:)
|
// permutations(ofCount:)
|
||||||
@@ -325,15 +319,15 @@ extension Collection {
|
|||||||
/// results in an empty sequence.
|
/// results in an empty sequence.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||||
/// is the number of elements in the base collection, since
|
/// is the number of elements in the base collection, since `Permutations`
|
||||||
/// `PermutationsSequence` accesses the `count` of the base collection.
|
/// accesses the `count` of the base collection.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func permutations<R: RangeExpression>(
|
public func permutations<R: RangeExpression>(
|
||||||
ofCount kRange: R
|
ofCount kRange: R
|
||||||
) -> PermutationsSequence<Self> where R.Bound == Int {
|
) -> Permutations<Self> where R.Bound == Int {
|
||||||
PermutationsSequence(self, kRange: kRange)
|
return Permutations(self, kRange: kRange)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a collection of the permutations of this collection of the
|
/// Returns a collection of the permutations of this collection of the
|
||||||
/// specified length.
|
/// specified length.
|
||||||
///
|
///
|
||||||
@@ -381,14 +375,14 @@ extension Collection {
|
|||||||
/// this collection, the resulting sequence is empty.
|
/// this collection, the resulting sequence is empty.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||||
/// is the number of elements in the base collection, since
|
/// is the number of elements in the base collection, since `Permutations`
|
||||||
/// `PermutationsSequence` accesses the `count` of the base collection.
|
/// accesses the `count` of the base collection.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func permutations(ofCount k: Int? = nil) -> PermutationsSequence<Self> {
|
public func permutations(ofCount k: Int? = nil) -> Permutations<Self> {
|
||||||
precondition(
|
precondition(
|
||||||
k ?? 0 >= 0,
|
k ?? 0 >= 0,
|
||||||
"Can't have permutations with a negative number of elements.")
|
"Can't have permutations with a negative number of elements.")
|
||||||
return PermutationsSequence(self, k: k)
|
return Permutations(self, k: k)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -399,61 +393,60 @@ extension Collection {
|
|||||||
/// A sequence of the unique permutations of the elements of a sequence or
|
/// A sequence of the unique permutations of the elements of a sequence or
|
||||||
/// collection.
|
/// collection.
|
||||||
///
|
///
|
||||||
/// To create a `UniquePermutationsSequence` instance, call one of the
|
/// To create a `UniquePermutations` instance, call one of the
|
||||||
/// `uniquePermutations` methods on your collection.
|
/// `uniquePermutations` methods on your collection.
|
||||||
public struct UniquePermutationsSequence<Base: Collection> {
|
public struct UniquePermutations<Base: Collection> {
|
||||||
/// The base collection to iterate over for permutations.
|
/// The base collection to iterate over for permutations.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var indexes: [Base.Index]
|
internal var indexes: [Base.Index]
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let kRange: Range<Int>
|
internal let kRange: Range<Int>
|
||||||
}
|
}
|
||||||
|
|
||||||
extension UniquePermutationsSequence where Base.Element: Hashable {
|
extension UniquePermutations where Base.Element: Hashable {
|
||||||
@inlinable
|
@inlinable
|
||||||
internal static func _indexes(_ base: Base) -> [Base.Index] {
|
internal static func _indexes(_ base: Base) -> [Base.Index] {
|
||||||
let firstIndexesAndCountsByElement = Dictionary(
|
let firstIndexesAndCountsByElement = Dictionary(
|
||||||
base.indices.lazy.map { (base[$0], ($0, 1)) },
|
base.indices.lazy.map { (base[$0], ($0, 1)) },
|
||||||
uniquingKeysWith: { indexAndCount, _ in (indexAndCount.0, indexAndCount.1 + 1) })
|
uniquingKeysWith: { indexAndCount, _ in (indexAndCount.0, indexAndCount.1 + 1) })
|
||||||
|
|
||||||
return firstIndexesAndCountsByElement
|
return firstIndexesAndCountsByElement
|
||||||
.values.sorted(by: { $0.0 < $1.0 })
|
.values.sorted(by: { $0.0 < $1.0 })
|
||||||
.flatMap { index, count in repeatElement(index, count: count) }
|
.flatMap { index, count in repeatElement(index, count: count) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(_ elements: Base) {
|
internal init(_ elements: Base) {
|
||||||
self.indexes = Self._indexes(elements)
|
self.indexes = Self._indexes(elements)
|
||||||
self.base = elements
|
self.base = elements
|
||||||
self.kRange = self.indexes.count ..< (self.indexes.count + 1)
|
self.kRange = self.indexes.count..<(self.indexes.count + 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init<R: RangeExpression>(_ base: Base, _ range: R)
|
internal init<R: RangeExpression>(_ base: Base, _ range: R)
|
||||||
where R.Bound == Int
|
where R.Bound == Int {
|
||||||
{
|
|
||||||
self.indexes = Self._indexes(base)
|
self.indexes = Self._indexes(base)
|
||||||
self.base = base
|
self.base = base
|
||||||
|
|
||||||
let upperBound = self.indexes.count + 1
|
let upperBound = self.indexes.count + 1
|
||||||
self.kRange = range.relative(to: 0 ..< .max)
|
self.kRange = range.relative(to: 0 ..< .max)
|
||||||
.clamped(to: 0 ..< upperBound)
|
.clamped(to: 0..<upperBound)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension UniquePermutationsSequence: Sequence {
|
extension UniquePermutations: Sequence {
|
||||||
/// The iterator for a `UniquePermutationsSequence` instance.
|
/// The iterator for a `UniquePermutations` instance.
|
||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var indexes: [Base.Index]
|
internal var indexes: [Base.Index]
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var lengths: Range<Int>
|
internal var lengths: Range<Int>
|
||||||
|
|
||||||
@@ -466,14 +459,14 @@ extension UniquePermutationsSequence: Sequence {
|
|||||||
self.indexes = indexes
|
self.indexes = indexes
|
||||||
self.lengths = lengths
|
self.lengths = lengths
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public mutating func next() -> [Base.Element]? {
|
public mutating func next() -> [Base.Element]? {
|
||||||
// In the end case, `lengths` is an empty range.
|
// In the end case, `lengths` is an empty range.
|
||||||
if lengths.isEmpty {
|
if lengths.isEmpty {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// The first iteration must produce the original sorted array, before any
|
// The first iteration must produce the original sorted array, before any
|
||||||
// permutations. We skip the permutation the first time so that we can
|
// permutations. We skip the permutation the first time so that we can
|
||||||
// always mutate the array _before_ returning a slice, which avoids
|
// always mutate the array _before_ returning a slice, which avoids
|
||||||
@@ -490,19 +483,18 @@ extension UniquePermutationsSequence: Sequence {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return indexes[..<lengths.lowerBound].map { base[$0] }
|
return indexes[..<lengths.lowerBound].map { base[$0] }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func makeIterator() -> Iterator {
|
public func makeIterator() -> Iterator {
|
||||||
Iterator(base, indexes: indexes, lengths: kRange)
|
Iterator(base, indexes: indexes, lengths: kRange)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension UniquePermutationsSequence: LazySequenceProtocol
|
extension UniquePermutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||||
where Base: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
extension Collection where Element: Hashable {
|
extension Collection where Element: Hashable {
|
||||||
/// Returns a sequence of the unique permutations of this sequence of the
|
/// Returns a sequence of the unique permutations of this sequence of the
|
||||||
@@ -543,14 +535,11 @@ extension Collection where Element: Hashable {
|
|||||||
///
|
///
|
||||||
/// - Complexity: O(*n*), where *n* is the number of elements in this
|
/// - Complexity: O(*n*), where *n* is the number of elements in this
|
||||||
/// collection.
|
/// collection.
|
||||||
@inlinable
|
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self> {
|
||||||
public func uniquePermutations(ofCount k: Int? = nil)
|
|
||||||
-> UniquePermutationsSequence<Self>
|
|
||||||
{
|
|
||||||
if let k = k {
|
if let k = k {
|
||||||
return UniquePermutationsSequence(self, k ..< (k + 1))
|
return UniquePermutations(self, k..<(k + 1))
|
||||||
} else {
|
} else {
|
||||||
return UniquePermutationsSequence(self)
|
return UniquePermutations(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -583,10 +572,8 @@ extension Collection where Element: Hashable {
|
|||||||
///
|
///
|
||||||
/// - Complexity: O(*n*), where *n* is the number of elements in this
|
/// - Complexity: O(*n*), where *n* is the number of elements in this
|
||||||
/// collection.
|
/// collection.
|
||||||
@inlinable
|
public func uniquePermutations<R: RangeExpression>(ofCount kRange: R) -> UniquePermutations<Self>
|
||||||
public func uniquePermutations<R: RangeExpression>(
|
where R.Bound == Int {
|
||||||
ofCount kRange: R
|
UniquePermutations(self, kRange)
|
||||||
) -> UniquePermutationsSequence<Self> where R.Bound == Int {
|
|
||||||
UniquePermutationsSequence(self, kRange)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,15 +10,15 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
/// A sequence that represents the product of two sequences' elements.
|
/// A sequence that represents the product of two sequences' elements.
|
||||||
public struct Product2Sequence<Base1: Sequence, Base2: Collection> {
|
public struct Product2<Base1: Sequence, Base2: Collection> {
|
||||||
/// The outer sequence in the product.
|
/// The outer sequence in the product.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base1: Base1
|
internal let base1: Base1
|
||||||
|
|
||||||
/// The inner sequence in the product.
|
/// The inner sequence in the product.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base2: Base2
|
internal let base2: Base2
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(_ base1: Base1, _ base2: Base2) {
|
internal init(_ base1: Base1, _ base2: Base2) {
|
||||||
self.base1 = base1
|
self.base1 = base1
|
||||||
@@ -26,10 +26,10 @@ public struct Product2Sequence<Base1: Sequence, Base2: Collection> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Product2Sequence: Sequence {
|
extension Product2: Sequence {
|
||||||
public typealias Element = (Base1.Element, Base2.Element)
|
public typealias Element = (Base1.Element, Base2.Element)
|
||||||
|
|
||||||
/// The iterator for a `Product2Sequence` sequence.
|
/// The iterator for a `Product2` sequence.
|
||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var i1: Base1.Iterator
|
internal var i1: Base1.Iterator
|
||||||
@@ -41,16 +41,18 @@ extension Product2Sequence: Sequence {
|
|||||||
internal let base2: Base2
|
internal let base2: Base2
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(_ c: Product2Sequence) {
|
internal init(_ c: Product2) {
|
||||||
self.base2 = c.base2
|
self.base2 = c.base2
|
||||||
self.i1 = c.base1.makeIterator()
|
self.i1 = c.base1.makeIterator()
|
||||||
self.i2 = c.base2.makeIterator()
|
self.i2 = c.base2.makeIterator()
|
||||||
self.element1 = nil
|
self.element1 = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public mutating func next() -> (Base1.Element,
|
public mutating func next() -> (
|
||||||
Base2.Element)? {
|
Base1.Element,
|
||||||
|
Base2.Element
|
||||||
|
)? {
|
||||||
// This is the initial state, where i1.next() has never
|
// This is the initial state, where i1.next() has never
|
||||||
// been called, or the final state, where i1.next() has
|
// been called, or the final state, where i1.next() has
|
||||||
// already returned nil.
|
// already returned nil.
|
||||||
@@ -59,21 +61,21 @@ extension Product2Sequence: Sequence {
|
|||||||
// once Base1 is exhausted, return `nil` forever
|
// once Base1 is exhausted, return `nil` forever
|
||||||
if element1 == nil { return nil }
|
if element1 == nil { return nil }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the next element from the second sequence, if not
|
// Get the next element from the second sequence, if not
|
||||||
// at end.
|
// at end.
|
||||||
if let element2 = i2.next() {
|
if let element2 = i2.next() {
|
||||||
return (element1!, element2)
|
return (element1!, element2)
|
||||||
}
|
}
|
||||||
|
|
||||||
// We've reached the end of the second sequence, so:
|
// We've reached the end of the second sequence, so:
|
||||||
// 1) Get the next element of the first sequence, if exists
|
// 1) Get the next element of the first sequence, if exists
|
||||||
// 2) Restart iteration of the second sequence
|
// 2) Restart iteration of the second sequence
|
||||||
// 3) Get the first element of the second sequence, if exists
|
// 3) Get the first element of the second sequence, if exists
|
||||||
element1 = i1.next()
|
element1 = i1.next()
|
||||||
guard let element1 = element1
|
guard let element1 = element1
|
||||||
else { return nil }
|
else { return nil }
|
||||||
|
|
||||||
i2 = base2.makeIterator()
|
i2 = base2.makeIterator()
|
||||||
if let element2 = i2.next() {
|
if let element2 = i2.next() {
|
||||||
return (element1, element2)
|
return (element1, element2)
|
||||||
@@ -83,56 +85,57 @@ extension Product2Sequence: Sequence {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public func makeIterator() -> Iterator {
|
public func makeIterator() -> Iterator {
|
||||||
Iterator(self)
|
return Iterator(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Product2Sequence: Collection where Base1: Collection {
|
extension Product2: Collection where Base1: Collection {
|
||||||
/// The index type for a `Product2Sequence` collection.
|
/// The index type for a `Product2` collection.
|
||||||
public struct Index: Comparable {
|
public struct Index: Comparable {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var i1: Base1.Index
|
internal var i1: Base1.Index
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var i2: Base2.Index
|
internal var i2: Base2.Index
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(i1: Base1.Index, i2: Base2.Index) {
|
internal init(i1: Base1.Index, i2: Base2.Index) {
|
||||||
self.i1 = i1
|
self.i1 = i1
|
||||||
self.i2 = i2
|
self.i2 = i2
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||||
(lhs.i1, lhs.i2) < (rhs.i1, rhs.i2)
|
(lhs.i1, lhs.i2) < (rhs.i1, rhs.i2)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var count: Int {
|
public var count: Int {
|
||||||
base1.count * base2.count
|
base1.count * base2.count
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var startIndex: Index {
|
public var startIndex: Index {
|
||||||
Index(
|
Index(
|
||||||
i1: base2.isEmpty ? base1.endIndex : base1.startIndex,
|
i1: base2.isEmpty ? base1.endIndex : base1.startIndex,
|
||||||
i2: base2.startIndex)
|
i2: base2.startIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var endIndex: Index {
|
public var endIndex: Index {
|
||||||
// `base2.startIndex` simplifies index calculations.
|
// `base2.startIndex` simplifies index calculations.
|
||||||
Index(i1: base1.endIndex, i2: base2.startIndex)
|
Index(i1: base1.endIndex, i2: base2.startIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public subscript(position: Index) -> (Base1.Element,
|
public subscript(position: Index) -> (
|
||||||
Base2.Element) {
|
Base1.Element,
|
||||||
|
Base2.Element
|
||||||
|
) {
|
||||||
(base1[position.i1], base2[position.i2])
|
(base1[position.i1], base2[position.i2])
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Forms an index from a pair of base indices, normalizing
|
/// Forms an index from a pair of base indices, normalizing
|
||||||
/// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if
|
/// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if
|
||||||
/// necessary.
|
/// necessary.
|
||||||
@@ -142,24 +145,24 @@ extension Product2Sequence: Collection where Base1: Collection {
|
|||||||
? Index(i1: base1.index(after: i1), i2: base2.startIndex)
|
? Index(i1: base1.index(after: i1), i2: base2.startIndex)
|
||||||
: Index(i1: i1, i2: i2)
|
: Index(i1: i1, i2: i2)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(after i: Index) -> Index {
|
public func index(after i: Index) -> Index {
|
||||||
precondition(i.i1 != base1.endIndex, "Can't advance past endIndex")
|
precondition(i.i1 != base1.endIndex, "Can't advance past endIndex")
|
||||||
return normalizeIndex(i.i1, base2.index(after: i.i2))
|
return normalizeIndex(i.i1, base2.index(after: i.i2))
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func distance(from start: Index, to end: Index) -> Int {
|
public func distance(from start: Index, to end: Index) -> Int {
|
||||||
guard start.i1 <= end.i1
|
guard start.i1 <= end.i1
|
||||||
else { return -distance(from: end, to: start) }
|
else { return -distance(from: end, to: start) }
|
||||||
guard start.i1 != end.i1
|
guard start.i1 != end.i1
|
||||||
else { return base2.distance(from: start.i2, to: end.i2) }
|
else { return base2.distance(from: start.i2, to: end.i2) }
|
||||||
|
|
||||||
// The number of full cycles through `base2` between `start` and `end`,
|
// The number of full cycles through `base2` between `start` and `end`,
|
||||||
// excluding the cycles that `start` and `end` are on.
|
// excluding the cycles that `start` and `end` are on.
|
||||||
let fullBase2Cycles = base1[start.i1..<end.i1].count - 1
|
let fullBase2Cycles = base1[start.i1..<end.i1].count - 1
|
||||||
|
|
||||||
if start.i2 <= end.i2 {
|
if start.i2 <= end.i2 {
|
||||||
// start.i2
|
// start.i2
|
||||||
// v
|
// v
|
||||||
@@ -170,11 +173,11 @@ extension Product2Sequence: Collection where Base1: Collection {
|
|||||||
// end.i1 > [l l l c c c c c c|r r r]
|
// end.i1 > [l l l c c c c c c|r r r]
|
||||||
// ^
|
// ^
|
||||||
// end.i2
|
// end.i2
|
||||||
|
|
||||||
let left = base2[..<start.i2].count
|
let left = base2[..<start.i2].count
|
||||||
let center = base2[start.i2..<end.i2].count
|
let center = base2[start.i2..<end.i2].count
|
||||||
let right = base2[end.i2...].count
|
let right = base2[end.i2...].count
|
||||||
|
|
||||||
return center + right
|
return center + right
|
||||||
+ fullBase2Cycles * (left + center + right)
|
+ fullBase2Cycles * (left + center + right)
|
||||||
+ left + center
|
+ left + center
|
||||||
@@ -188,30 +191,30 @@ extension Product2Sequence: Collection where Base1: Collection {
|
|||||||
// end.i1 > [l l l|c c c c c c r r r]
|
// end.i1 > [l l l|c c c c c c r r r]
|
||||||
// ^
|
// ^
|
||||||
// end.i2
|
// end.i2
|
||||||
|
|
||||||
let left = base2[..<end.i2].count
|
let left = base2[..<end.i2].count
|
||||||
let right = base2[start.i2...].count
|
let right = base2[start.i2...].count
|
||||||
|
|
||||||
// We can avoid traversing `base2[end.i2..<start.i2]` if `start` and `end`
|
// We can avoid traversing `base2[end.i2..<start.i2]` if `start` and `end`
|
||||||
// are on consecutive cycles.
|
// are on consecutive cycles.
|
||||||
guard fullBase2Cycles > 0 else { return right + left }
|
guard fullBase2Cycles > 0 else { return right + left }
|
||||||
|
|
||||||
let center = base2[end.i2..<start.i2].count
|
let center = base2[end.i2..<start.i2].count
|
||||||
return right
|
return right
|
||||||
+ fullBase2Cycles * (left + center + right)
|
+ fullBase2Cycles * (left + center + right)
|
||||||
+ left
|
+ left
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||||
guard distance != 0 else { return i }
|
guard distance != 0 else { return i }
|
||||||
|
|
||||||
return distance > 0
|
return distance > 0
|
||||||
? offsetForward(i, by: distance)
|
? offsetForward(i, by: distance)
|
||||||
: offsetBackward(i, by: -distance)
|
: offsetBackward(i, by: -distance)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(
|
public func index(
|
||||||
_ i: Index,
|
_ i: Index,
|
||||||
@@ -232,36 +235,35 @@ extension Product2Sequence: Collection where Base1: Collection {
|
|||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||||
else { fatalError("Index is out of bounds") }
|
else { fatalError("Index is out of bounds") }
|
||||||
return index
|
return index
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
||||||
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
||||||
else { fatalError("Index is out of bounds") }
|
else { fatalError("Index is out of bounds") }
|
||||||
return index
|
return index
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetForward(
|
internal func offsetForward(
|
||||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||||
) -> Index? {
|
) -> Index? {
|
||||||
assert(distance >= 0)
|
assert(distance >= 0)
|
||||||
assert(limit >= i)
|
assert(limit >= i)
|
||||||
|
|
||||||
if limit.i1 == i.i1 {
|
if limit.i1 == i.i1 {
|
||||||
// Delegate to `base2` if the offset is limited to `i.i1`.
|
// Delegate to `base2` if the offset is limited to `i.i1`.
|
||||||
//
|
//
|
||||||
// i.i2 limit.i2
|
// i.i2 limit.i2
|
||||||
// v v
|
// v v
|
||||||
// i.i1 > [x x x|x x x x x x|x x x]
|
// i.i1 > [x x x|x x x x x x|x x x]
|
||||||
|
|
||||||
return base2.index(i.i2, offsetBy: distance, limitedBy: limit.i2)
|
return base2.index(i.i2, offsetBy: distance, limitedBy: limit.i2)
|
||||||
.map { i2 in Index(i1: i.i1, i2: i2) }
|
.map { i2 in Index(i1: i.i1, i2: i2) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
if let i2 = base2.index(i.i2, offsetBy: distance, limitedBy: base2.endIndex) {
|
if let i2 = base2.index(i.i2, offsetBy: distance, limitedBy: base2.endIndex) {
|
||||||
// `distance` does not overflow `base2[i.i2...]`.
|
// `distance` does not overflow `base2[i.i2...]`.
|
||||||
//
|
//
|
||||||
@@ -269,14 +271,14 @@ extension Product2Sequence: Collection where Base1: Collection {
|
|||||||
// v v
|
// v v
|
||||||
// i.i1 > [x x x|x x x x x x|x x x]
|
// i.i1 > [x x x|x x x x x x|x x x]
|
||||||
// [ |> > > > > >| ] (`distance`)
|
// [ |> > > > > >| ] (`distance`)
|
||||||
|
|
||||||
return normalizeIndex(i.i1, i2)
|
return normalizeIndex(i.i1, i2)
|
||||||
}
|
}
|
||||||
|
|
||||||
let suffixCount = base2[i.i2...].count
|
let suffixCount = base2[i.i2...].count
|
||||||
let remaining = distance - suffixCount
|
let remaining = distance - suffixCount
|
||||||
let nextI1 = base1.index(after: i.i1)
|
let nextI1 = base1.index(after: i.i1)
|
||||||
|
|
||||||
if limit.i1 == nextI1 {
|
if limit.i1 == nextI1 {
|
||||||
// Delegate to `base2` if the offset is limited to `nextI1`.
|
// Delegate to `base2` if the offset is limited to `nextI1`.
|
||||||
//
|
//
|
||||||
@@ -286,11 +288,11 @@ extension Product2Sequence: Collection where Base1: Collection {
|
|||||||
// nextI1 > [x x x x x x x x x|x x x]
|
// nextI1 > [x x x x x x x x x|x x x]
|
||||||
// ^
|
// ^
|
||||||
// limit.i2
|
// limit.i2
|
||||||
|
|
||||||
return base2.index(base2.startIndex, offsetBy: remaining, limitedBy: limit.i2)
|
return base2.index(base2.startIndex, offsetBy: remaining, limitedBy: limit.i2)
|
||||||
.map { i2 in Index(i1: nextI1, i2: i2) }
|
.map { i2 in Index(i1: nextI1, i2: i2) }
|
||||||
}
|
}
|
||||||
|
|
||||||
if let i2 = base2.index(base2.startIndex, offsetBy: remaining, limitedBy: i.i2) {
|
if let i2 = base2.index(base2.startIndex, offsetBy: remaining, limitedBy: i.i2) {
|
||||||
// `remaining` does not overflow `base2[..<i.i2]`.
|
// `remaining` does not overflow `base2[..<i.i2]`.
|
||||||
//
|
//
|
||||||
@@ -302,20 +304,20 @@ extension Product2Sequence: Collection where Base1: Collection {
|
|||||||
// nextI1 > [x x x|x x x x x x x x x]
|
// nextI1 > [x x x|x x x x x x x x x]
|
||||||
// ^
|
// ^
|
||||||
// i2
|
// i2
|
||||||
|
|
||||||
return Index(i1: nextI1, i2: i2)
|
return Index(i1: nextI1, i2: i2)
|
||||||
}
|
}
|
||||||
|
|
||||||
let prefixCount = base2[..<i.i2].count
|
let prefixCount = base2[..<i.i2].count
|
||||||
let base2Count = prefixCount + suffixCount
|
let base2Count = prefixCount + suffixCount
|
||||||
let base1Distance = remaining / base2Count
|
let base1Distance = remaining / base2Count
|
||||||
|
|
||||||
guard let i1 = base1.index(nextI1, offsetBy: base1Distance, limitedBy: limit.i1)
|
guard let i1 = base1.index(nextI1, offsetBy: base1Distance, limitedBy: limit.i1)
|
||||||
else { return nil }
|
else { return nil }
|
||||||
|
|
||||||
// The distance from `base2.startIndex` to the target.
|
// The distance from `base2.startIndex` to the target.
|
||||||
let base2Distance = remaining % base2Count
|
let base2Distance = remaining % base2Count
|
||||||
|
|
||||||
let base2Limit = limit.i1 == i1 ? limit.i2 : base2.endIndex
|
let base2Limit = limit.i1 == i1 ? limit.i2 : base2.endIndex
|
||||||
return base2.index(base2.startIndex, offsetBy: base2Distance, limitedBy: base2Limit)
|
return base2.index(base2.startIndex, offsetBy: base2Distance, limitedBy: base2Limit)
|
||||||
.map { i2 in Index(i1: i1, i2: i2) }
|
.map { i2 in Index(i1: i1, i2: i2) }
|
||||||
@@ -327,18 +329,18 @@ extension Product2Sequence: Collection where Base1: Collection {
|
|||||||
) -> Index? {
|
) -> Index? {
|
||||||
assert(distance >= 0)
|
assert(distance >= 0)
|
||||||
assert(limit <= i)
|
assert(limit <= i)
|
||||||
|
|
||||||
if limit.i1 == i.i1 {
|
if limit.i1 == i.i1 {
|
||||||
// Delegate to `base2` if the offset is limited to `i.i1`.
|
// Delegate to `base2` if the offset is limited to `i.i1`.
|
||||||
//
|
//
|
||||||
// limit.i2 i.i2
|
// limit.i2 i.i2
|
||||||
// v v
|
// v v
|
||||||
// i.i1 > [x x x|x x x x x x|x x x]
|
// i.i1 > [x x x|x x x x x x|x x x]
|
||||||
|
|
||||||
return base2.index(i.i2, offsetBy: -distance, limitedBy: limit.i2)
|
return base2.index(i.i2, offsetBy: -distance, limitedBy: limit.i2)
|
||||||
.map { i2 in Index(i1: i.i1, i2: i2) }
|
.map { i2 in Index(i1: i.i1, i2: i2) }
|
||||||
}
|
}
|
||||||
|
|
||||||
if let i2 = base2.index(i.i2, offsetBy: -distance, limitedBy: base2.startIndex) {
|
if let i2 = base2.index(i.i2, offsetBy: -distance, limitedBy: base2.startIndex) {
|
||||||
// `distance` does not underflow `base2[..<i.i2]`.
|
// `distance` does not underflow `base2[..<i.i2]`.
|
||||||
//
|
//
|
||||||
@@ -346,14 +348,14 @@ extension Product2Sequence: Collection where Base1: Collection {
|
|||||||
// v v
|
// v v
|
||||||
// i.i1 > [x x x|x x x x x x|x x x]
|
// i.i1 > [x x x|x x x x x x|x x x]
|
||||||
// [ |< < < < < <| ] (`distance`)
|
// [ |< < < < < <| ] (`distance`)
|
||||||
|
|
||||||
return Index(i1: i.i1, i2: i2)
|
return Index(i1: i.i1, i2: i2)
|
||||||
}
|
}
|
||||||
|
|
||||||
let prefixCount = base2[..<i.i2].count
|
let prefixCount = base2[..<i.i2].count
|
||||||
let remaining = distance - prefixCount
|
let remaining = distance - prefixCount
|
||||||
let previousI1 = base1.index(i.i1, offsetBy: -1)
|
let previousI1 = base1.index(i.i1, offsetBy: -1)
|
||||||
|
|
||||||
if limit.i1 == previousI1 {
|
if limit.i1 == previousI1 {
|
||||||
// Delegate to `base2` if the offset is limited to `previousI1`.
|
// Delegate to `base2` if the offset is limited to `previousI1`.
|
||||||
//
|
//
|
||||||
@@ -363,11 +365,11 @@ extension Product2Sequence: Collection where Base1: Collection {
|
|||||||
// i.i1 > [x x x x x x x x x|x x x]
|
// i.i1 > [x x x x x x x x x|x x x]
|
||||||
// ^
|
// ^
|
||||||
// i.i2
|
// i.i2
|
||||||
|
|
||||||
return base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: limit.i2)
|
return base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: limit.i2)
|
||||||
.map { i2 in Index(i1: previousI1, i2: i2) }
|
.map { i2 in Index(i1: previousI1, i2: i2) }
|
||||||
}
|
}
|
||||||
|
|
||||||
if let i2 = base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: i.i2) {
|
if let i2 = base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: i.i2) {
|
||||||
// `remaining` does not underflow `base2[i.i2...]`.
|
// `remaining` does not underflow `base2[i.i2...]`.
|
||||||
//
|
//
|
||||||
@@ -379,17 +381,17 @@ extension Product2Sequence: Collection where Base1: Collection {
|
|||||||
// i.i1 > [x x x|x x x x x x x x x]
|
// i.i1 > [x x x|x x x x x x x x x]
|
||||||
// ^
|
// ^
|
||||||
// i.i2
|
// i.i2
|
||||||
|
|
||||||
return Index(i1: previousI1, i2: i2)
|
return Index(i1: previousI1, i2: i2)
|
||||||
}
|
}
|
||||||
|
|
||||||
let suffixCount = base2[i.i2...].count
|
let suffixCount = base2[i.i2...].count
|
||||||
let base2Count = prefixCount + suffixCount
|
let base2Count = prefixCount + suffixCount
|
||||||
let base1Distance = remaining / base2Count
|
let base1Distance = remaining / base2Count
|
||||||
|
|
||||||
// The distance from `base2.endIndex` to the target.
|
// The distance from `base2.endIndex` to the target.
|
||||||
let base2Distance = remaining % base2Count
|
let base2Distance = remaining % base2Count
|
||||||
|
|
||||||
if base2Distance == 0 {
|
if base2Distance == 0 {
|
||||||
// We end up exactly between two cycles, so `base1Distance` would
|
// We end up exactly between two cycles, so `base1Distance` would
|
||||||
// overshoot the target by 1.
|
// overshoot the target by 1.
|
||||||
@@ -402,7 +404,7 @@ extension Product2Sequence: Collection where Base1: Collection {
|
|||||||
// i.i1 > [x x x|x x x x x x x x x]
|
// i.i1 > [x x x|x x x x x x x x x]
|
||||||
// ^
|
// ^
|
||||||
// i.i2
|
// i.i2
|
||||||
|
|
||||||
if let i1 = base1.index(previousI1, offsetBy: -(base1Distance - 1), limitedBy: limit.i1) {
|
if let i1 = base1.index(previousI1, offsetBy: -(base1Distance - 1), limitedBy: limit.i1) {
|
||||||
let index = Index(i1: i1, i2: base2.startIndex)
|
let index = Index(i1: i1, i2: base2.startIndex)
|
||||||
return index < limit ? nil : index
|
return index < limit ? nil : index
|
||||||
@@ -410,23 +412,23 @@ extension Product2Sequence: Collection where Base1: Collection {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
guard let i1 = base1.index(previousI1, offsetBy: -base1Distance, limitedBy: limit.i1)
|
guard let i1 = base1.index(previousI1, offsetBy: -base1Distance, limitedBy: limit.i1)
|
||||||
else { return nil }
|
else { return nil }
|
||||||
|
|
||||||
let base2Limit = limit.i1 == i1 ? limit.i2 : base2.startIndex
|
let base2Limit = limit.i1 == i1 ? limit.i2 : base2.startIndex
|
||||||
return base2.index(base2.endIndex, offsetBy: -base2Distance, limitedBy: base2Limit)
|
return base2.index(base2.endIndex, offsetBy: -base2Distance, limitedBy: base2Limit)
|
||||||
.map { i2 in Index(i1: i1, i2: i2) }
|
.map { i2 in Index(i1: i1, i2: i2) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Product2Sequence: BidirectionalCollection
|
extension Product2: BidirectionalCollection
|
||||||
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
|
where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
|
||||||
{
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(before i: Index) -> Index {
|
public func index(before i: Index) -> Index {
|
||||||
precondition(i != startIndex,
|
precondition(
|
||||||
"Can't move before startIndex")
|
i != startIndex,
|
||||||
|
"Can't move before startIndex")
|
||||||
if i.i2 == base2.startIndex {
|
if i.i2 == base2.startIndex {
|
||||||
return Index(
|
return Index(
|
||||||
i1: base1.index(before: i.i1),
|
i1: base1.index(before: i.i1),
|
||||||
@@ -437,11 +439,10 @@ extension Product2Sequence: BidirectionalCollection
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Product2Sequence: RandomAccessCollection
|
extension Product2: RandomAccessCollection
|
||||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||||
|
|
||||||
extension Product2Sequence.Index: Hashable
|
extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {}
|
||||||
where Base1.Index: Hashable, Base2.Index: Hashable {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// product(_:_:)
|
// product(_:_:)
|
||||||
@@ -483,6 +484,6 @@ extension Product2Sequence.Index: Hashable
|
|||||||
@inlinable
|
@inlinable
|
||||||
public func product<Base1: Sequence, Base2: Collection>(
|
public func product<Base1: Sequence, Base2: Collection>(
|
||||||
_ s1: Base1, _ s2: Base2
|
_ s1: Base1, _ s2: Base2
|
||||||
) -> Product2Sequence<Base1, Base2> {
|
) -> Product2<Base1, Base2> {
|
||||||
Product2Sequence(s1, s2)
|
return Product2(s1, s2)
|
||||||
}
|
}
|
||||||
@@ -10,8 +10,7 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
// For log(_:) and root(_:_:)
|
// For log(_:) and root(_:_:)
|
||||||
@_implementationOnly
|
@_implementationOnly import RealModule
|
||||||
import RealModule
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// randomStableSample(count:)
|
// randomStableSample(count:)
|
||||||
@@ -33,13 +32,13 @@ extension Collection {
|
|||||||
count k: Int, using rng: inout G
|
count k: Int, using rng: inout G
|
||||||
) -> [Element] {
|
) -> [Element] {
|
||||||
guard k > 0 else { return [] }
|
guard k > 0 else { return [] }
|
||||||
|
|
||||||
var remainingCount = count
|
var remainingCount = count
|
||||||
guard k < remainingCount else { return Array(self) }
|
guard k < remainingCount else { return Array(self) }
|
||||||
|
|
||||||
var result: [Element] = []
|
var result: [Element] = []
|
||||||
result.reserveCapacity(k)
|
result.reserveCapacity(k)
|
||||||
|
|
||||||
var i = startIndex
|
var i = startIndex
|
||||||
var countToSelect = k
|
var countToSelect = k
|
||||||
while countToSelect > 0 {
|
while countToSelect > 0 {
|
||||||
@@ -52,17 +51,18 @@ extension Collection {
|
|||||||
formIndex(after: &i)
|
formIndex(after: &i)
|
||||||
remainingCount -= 1
|
remainingCount -= 1
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Randomly selects the specified number of elements from this collection,
|
/// Randomly selects the specified number of elements from this collection,
|
||||||
/// maintaining their relative order.
|
/// maintaining their relative order.
|
||||||
///
|
///
|
||||||
/// This method is equivalent to calling `randomStableSample(k:using:)`,
|
/// This method is equivalent to calling `randomStableSample(k:using:)`,
|
||||||
/// passing in the system's default random generator.
|
/// passing in the system's default random generator.
|
||||||
///
|
///
|
||||||
/// - Parameter k: The number of elements to randomly select.
|
/// - Parameters:
|
||||||
|
/// - k: The number of elements to randomly select.
|
||||||
/// - Returns: An array of `k` random elements. If `k` is greater than this
|
/// - Returns: An array of `k` random elements. If `k` is greater than this
|
||||||
/// collection's count, then this method returns the full collection.
|
/// collection's count, then this method returns the full collection.
|
||||||
///
|
///
|
||||||
@@ -119,41 +119,42 @@ extension Collection {
|
|||||||
var w = 1.0
|
var w = 1.0
|
||||||
var result: [Element] = []
|
var result: [Element] = []
|
||||||
result.reserveCapacity(k)
|
result.reserveCapacity(k)
|
||||||
|
|
||||||
// Fill the reservoir with the first `k` elements.
|
// Fill the reservoir with the first `k` elements.
|
||||||
var i = startIndex
|
var i = startIndex
|
||||||
while i != endIndex, result.count < k {
|
while i < endIndex, result.count < k {
|
||||||
result.append(self[i])
|
result.append(self[i])
|
||||||
formIndex(after: &i)
|
formIndex(after: &i)
|
||||||
}
|
}
|
||||||
|
|
||||||
while i != endIndex {
|
while i < endIndex {
|
||||||
// Calculate the next value of w.
|
// Calculate the next value of w.
|
||||||
w *= nextW(k: k, using: &rng)
|
w *= nextW(k: k, using: &rng)
|
||||||
|
|
||||||
// Find index of the next element to swap into the reservoir.
|
// Find index of the next element to swap into the reservoir.
|
||||||
let offset = nextOffset(w: w, using: &rng)
|
let offset = nextOffset(w: w, using: &rng)
|
||||||
i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex
|
i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex
|
||||||
|
|
||||||
if i != endIndex {
|
if i < endIndex {
|
||||||
// Swap selected element with a randomly chosen one in the reservoir.
|
// Swap selected element with a randomly chosen one in the reservoir.
|
||||||
let j = Int.random(in: 0..<result.count, using: &rng)
|
let j = Int.random(in: 0..<result.count, using: &rng)
|
||||||
result[j] = self[i]
|
result[j] = self[i]
|
||||||
formIndex(after: &i)
|
formIndex(after: &i)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// FIXME: necessary?
|
// FIXME: necessary?
|
||||||
result.shuffle(using: &rng)
|
result.shuffle(using: &rng)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Randomly selects the specified number of elements from this collection.
|
/// Randomly selects the specified number of elements from this collection.
|
||||||
///
|
///
|
||||||
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
|
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
|
||||||
/// the system's default random generator.
|
/// the system's default random generator.
|
||||||
///
|
///
|
||||||
/// - Parameter k: The number of elements to randomly select.
|
/// - Parameters:
|
||||||
|
/// - k: The number of elements to randomly select.
|
||||||
/// - Returns: An array of `k` random elements. The returned elements may be
|
/// - Returns: An array of `k` random elements. The returned elements may be
|
||||||
/// in any order. If `k` is greater than this collection's count, then this
|
/// in any order. If `k` is greater than this collection's count, then this
|
||||||
/// method returns the full collection.
|
/// method returns the full collection.
|
||||||
@@ -184,11 +185,11 @@ extension Sequence {
|
|||||||
count k: Int, using rng: inout G
|
count k: Int, using rng: inout G
|
||||||
) -> [Element] {
|
) -> [Element] {
|
||||||
guard k > 0 else { return [] }
|
guard k > 0 else { return [] }
|
||||||
|
|
||||||
var w = 1.0
|
var w = 1.0
|
||||||
var result: [Element] = []
|
var result: [Element] = []
|
||||||
result.reserveCapacity(k)
|
result.reserveCapacity(k)
|
||||||
|
|
||||||
// Fill the reservoir with the first `k` elements.
|
// Fill the reservoir with the first `k` elements.
|
||||||
var iterator = makeIterator()
|
var iterator = makeIterator()
|
||||||
while result.count < k, let el = iterator.next() {
|
while result.count < k, let el = iterator.next() {
|
||||||
@@ -198,32 +199,33 @@ extension Sequence {
|
|||||||
while true {
|
while true {
|
||||||
// Calculate the next value of w.
|
// Calculate the next value of w.
|
||||||
w *= nextW(k: k, using: &rng)
|
w *= nextW(k: k, using: &rng)
|
||||||
|
|
||||||
// Find the offset of the next element to swap into the reservoir.
|
// Find the offset of the next element to swap into the reservoir.
|
||||||
var offset = nextOffset(w: w, using: &rng)
|
var offset = nextOffset(w: w, using: &rng)
|
||||||
|
|
||||||
// Skip over `offset` elements to find the selected element.
|
// Skip over `offset` elements to find the selected element.
|
||||||
while offset > 0, let _ = iterator.next() {
|
while offset > 0, let _ = iterator.next() {
|
||||||
offset -= 1
|
offset -= 1
|
||||||
}
|
}
|
||||||
guard let nextElement = iterator.next() else { break }
|
guard let nextElement = iterator.next() else { break }
|
||||||
|
|
||||||
// Swap selected element with a randomly chosen one in the reservoir.
|
// Swap selected element with a randomly chosen one in the reservoir.
|
||||||
let j = Int.random(in: 0..<result.count, using: &rng)
|
let j = Int.random(in: 0..<result.count, using: &rng)
|
||||||
result[j] = nextElement
|
result[j] = nextElement
|
||||||
}
|
}
|
||||||
|
|
||||||
// FIXME: necessary?
|
// FIXME: necessary?
|
||||||
result.shuffle(using: &rng)
|
result.shuffle(using: &rng)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Randomly selects the specified number of elements from this sequence.
|
/// Randomly selects the specified number of elements from this sequence.
|
||||||
///
|
///
|
||||||
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
|
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
|
||||||
/// the system's default random generator.
|
/// the system's default random generator.
|
||||||
///
|
///
|
||||||
/// - Parameter k: The number of elements to randomly select.
|
/// - Parameters:
|
||||||
|
/// - k: The number of elements to randomly select.
|
||||||
/// - Returns: An array of `k` random elements. The returned elements may be
|
/// - Returns: An array of `k` random elements. The returned elements may be
|
||||||
/// in any order. If `k` is greater than this sequence's count, then this
|
/// in any order. If `k` is greater than this sequence's count, then this
|
||||||
/// method returns the full sequence.
|
/// method returns the full sequence.
|
||||||
@@ -235,61 +237,3 @@ extension Sequence {
|
|||||||
return randomSample(count: k, using: &g)
|
return randomSample(count: k, using: &g)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// randomElement()
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
// This method is a single-element specialization of `randomSample(count:)`,
|
|
||||||
// and extends the stdlib's `randomElement()` functionality (which is available
|
|
||||||
// for collections) down to sequences.
|
|
||||||
|
|
||||||
extension Sequence {
|
|
||||||
/// Randomly selects an element from this sequence, using the given generator
|
|
||||||
/// as the source of randomness.
|
|
||||||
///
|
|
||||||
/// - Parameter rng: The random number generator to use for sampling.
|
|
||||||
/// - Returns: A random element. If the sequence has no elements, this method
|
|
||||||
/// returns `nil`.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
|
||||||
@inlinable
|
|
||||||
public func randomElement<G: RandomNumberGenerator>(
|
|
||||||
using rng: inout G
|
|
||||||
) -> Element? {
|
|
||||||
var iterator = makeIterator()
|
|
||||||
guard var result = iterator.next() else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var w = 1.0
|
|
||||||
while true {
|
|
||||||
w *= nextW(k: 1, using: &rng)
|
|
||||||
var offset = nextOffset(w: w, using: &rng)
|
|
||||||
while offset > 0, let _ = iterator.next() {
|
|
||||||
offset -= 1
|
|
||||||
}
|
|
||||||
guard let nextElement = iterator.next()
|
|
||||||
else { break }
|
|
||||||
|
|
||||||
result = nextElement
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Randomly selects an element from this sequence.
|
|
||||||
///
|
|
||||||
/// This method is equivalent to calling `randomSample(using:)`, passing in
|
|
||||||
/// the system's default random generator.
|
|
||||||
///
|
|
||||||
/// - Returns: A random element. If the sequence has no elements, this method
|
|
||||||
/// returns `nil`.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
|
||||||
@inlinable
|
|
||||||
public func randomElement() -> Element? {
|
|
||||||
var g = SystemRandomNumberGenerator()
|
|
||||||
return randomElement(using: &g)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+160
-135
@@ -12,6 +12,7 @@
|
|||||||
// MARK: - Exclusive Reductions
|
// MARK: - Exclusive Reductions
|
||||||
|
|
||||||
extension LazySequenceProtocol {
|
extension LazySequenceProtocol {
|
||||||
|
|
||||||
/// Returns a sequence containing the accumulated results of combining the
|
/// Returns a sequence containing the accumulated results of combining the
|
||||||
/// elements of the sequence using the given closure.
|
/// elements of the sequence using the given closure.
|
||||||
///
|
///
|
||||||
@@ -28,17 +29,17 @@ extension LazySequenceProtocol {
|
|||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - initial: The value to use as the initial value.
|
/// - initial: The value to use as the initial value.
|
||||||
/// - transform: A closure that combines the previously reduced result and
|
/// - transform: A closure that combines the previously reduced result and
|
||||||
/// the next element in the receiving sequence.
|
/// the next element in the receiving sequence.
|
||||||
/// - Returns: A sequence of the initial value followed by the reduced
|
/// - Returns: A sequence of the initial value followed by the reduced
|
||||||
/// elements.
|
/// elements.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(1)
|
/// - Complexity: O(1)
|
||||||
@inlinable
|
@inlinable
|
||||||
public func reductions<Result>(
|
public func reductions<Result>(
|
||||||
_ initial: Result,
|
_ initial: Result,
|
||||||
_ transform: @escaping (Result, Element) -> Result
|
_ transform: @escaping (Result, Element) -> Result
|
||||||
) -> ExclusiveReductionsSequence<Elements, Result> {
|
) -> ExclusiveReductions<Result, Self> {
|
||||||
reductions(into: initial) { result, element in
|
return reductions(into: initial) { result, element in
|
||||||
result = transform(result, element)
|
result = transform(result, element)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -59,7 +60,7 @@ extension LazySequenceProtocol {
|
|||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - initial: The value to use as the initial value.
|
/// - initial: The value to use as the initial value.
|
||||||
/// - transform: A closure that combines the previously reduced result and
|
/// - transform: A closure that combines the previously reduced result and
|
||||||
/// the next element in the receiving sequence.
|
/// the next element in the receiving sequence.
|
||||||
/// - Returns: A sequence of the initial value followed by the reduced
|
/// - Returns: A sequence of the initial value followed by the reduced
|
||||||
/// elements.
|
/// elements.
|
||||||
///
|
///
|
||||||
@@ -68,15 +69,13 @@ extension LazySequenceProtocol {
|
|||||||
public func reductions<Result>(
|
public func reductions<Result>(
|
||||||
into initial: Result,
|
into initial: Result,
|
||||||
_ transform: @escaping (inout Result, Element) -> Void
|
_ transform: @escaping (inout Result, Element) -> Void
|
||||||
) -> ExclusiveReductionsSequence<Elements, Result> {
|
) -> ExclusiveReductions<Result, Self> {
|
||||||
ExclusiveReductionsSequence(
|
ExclusiveReductions(base: self, initial: initial, transform: transform)
|
||||||
base: elements,
|
|
||||||
initial: initial,
|
|
||||||
transform: transform)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Sequence {
|
extension Sequence {
|
||||||
|
|
||||||
/// Returns an array containing the accumulated results of combining the
|
/// Returns an array containing the accumulated results of combining the
|
||||||
/// elements of the sequence using the given closure.
|
/// elements of the sequence using the given closure.
|
||||||
///
|
///
|
||||||
@@ -107,7 +106,7 @@ extension Sequence {
|
|||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - initial: The value to use as the initial value.
|
/// - initial: The value to use as the initial value.
|
||||||
/// - transform: A closure that combines the previously reduced result and
|
/// - transform: A closure that combines the previously reduced result and
|
||||||
/// the next element in the receiving sequence.
|
/// the next element in the receiving sequence.
|
||||||
/// - Returns: An array of the initial value followed by the reduced elements.
|
/// - Returns: An array of the initial value followed by the reduced elements.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||||
@@ -116,7 +115,7 @@ extension Sequence {
|
|||||||
_ initial: Result,
|
_ initial: Result,
|
||||||
_ transform: (Result, Element) throws -> Result
|
_ transform: (Result, Element) throws -> Result
|
||||||
) rethrows -> [Result] {
|
) rethrows -> [Result] {
|
||||||
try reductions(into: initial) { result, element in
|
return try reductions(into: initial) { result, element in
|
||||||
result = try transform(result, element)
|
result = try transform(result, element)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -151,7 +150,7 @@ extension Sequence {
|
|||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - initial: The value to use as the initial value.
|
/// - initial: The value to use as the initial value.
|
||||||
/// - transform: A closure that combines the previously reduced result and
|
/// - transform: A closure that combines the previously reduced result and
|
||||||
/// the next element in the receiving sequence.
|
/// the next element in the receiving sequence.
|
||||||
/// - Returns: An array of the initial value followed by the reduced elements.
|
/// - Returns: An array of the initial value followed by the reduced elements.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||||
@@ -177,7 +176,7 @@ extension Sequence {
|
|||||||
|
|
||||||
/// A sequence of applying a transform to the element of a sequence and the
|
/// A sequence of applying a transform to the element of a sequence and the
|
||||||
/// previously transformed result.
|
/// previously transformed result.
|
||||||
public struct ExclusiveReductionsSequence<Base: Sequence, Result> {
|
public struct ExclusiveReductions<Result, Base: Sequence> {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@@ -199,7 +198,7 @@ public struct ExclusiveReductionsSequence<Base: Sequence, Result> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ExclusiveReductionsSequence: Sequence {
|
extension ExclusiveReductions: Sequence {
|
||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var iterator: Base.Iterator
|
internal var iterator: Base.Iterator
|
||||||
@@ -242,75 +241,52 @@ extension ExclusiveReductionsSequence: Sequence {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ExclusiveReductionsSequence: Collection where Base: Collection {
|
extension ExclusiveReductions: Collection where Base: Collection {
|
||||||
public struct Index: Comparable {
|
public struct Index: Comparable {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal enum Representation {
|
internal let representation: ReductionsIndexRepresentation<Base.Index, Result>
|
||||||
case base(Base.Index, Result)
|
|
||||||
case end
|
|
||||||
}
|
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let representation: Representation
|
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(_ representation: Representation) {
|
internal init(
|
||||||
|
_ representation: ReductionsIndexRepresentation<Base.Index, Result>
|
||||||
|
) {
|
||||||
self.representation = representation
|
self.representation = representation
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
|
||||||
switch (lhs.representation, rhs.representation) {
|
|
||||||
case (.base(let lhs, _), .base(let rhs, _)):
|
|
||||||
return lhs == rhs
|
|
||||||
case (.end, .end):
|
|
||||||
return true
|
|
||||||
case (.base, .end), (.end, .base):
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||||
switch (lhs.representation, rhs.representation) {
|
lhs.representation < rhs.representation
|
||||||
case (.end, _):
|
|
||||||
return false
|
|
||||||
case (_, .end):
|
|
||||||
return true
|
|
||||||
case (.base(let lhs, _), .base(let rhs, _)):
|
|
||||||
return lhs < rhs
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var startIndex: Index {
|
public var startIndex: Index { Index(.start) }
|
||||||
Index(.base(base.startIndex, initial))
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var endIndex: Index {
|
public var endIndex: Index { Index(.end) }
|
||||||
Index(.end)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public subscript(position: Index) -> Result {
|
public subscript(position: Index) -> Result {
|
||||||
switch position.representation {
|
switch position.representation {
|
||||||
case .base(_, let result):
|
case .start: return initial
|
||||||
return result
|
case .base(_, let result): return result
|
||||||
case .end:
|
case .end: fatalError("Cannot get element of end index.")
|
||||||
fatalError("Cannot get element of end index.")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(after index: Index) -> Index {
|
public func index(after i: Index) -> Index {
|
||||||
switch index.representation {
|
func index(base index: Base.Index, previous: Result) -> Index {
|
||||||
case .base(base.endIndex, _):
|
guard index != base.endIndex else { return endIndex }
|
||||||
return Index(.end)
|
var previous = previous
|
||||||
case .base(let index, var result):
|
transform(&previous, base[index])
|
||||||
transform(&result, base[index])
|
return Index(.base(index: index, result: previous))
|
||||||
return Index(.base(base.index(after: index), result))
|
}
|
||||||
|
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:
|
case .end:
|
||||||
fatalError("Cannot get index after end index.")
|
fatalError("Cannot get index after end index.")
|
||||||
}
|
}
|
||||||
@@ -319,40 +295,38 @@ extension ExclusiveReductionsSequence: Collection where Base: Collection {
|
|||||||
@inlinable
|
@inlinable
|
||||||
public func distance(from start: Index, to end: Index) -> Int {
|
public func distance(from start: Index, to end: Index) -> Int {
|
||||||
switch (start.representation, end.representation) {
|
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, _)):
|
case let (.base(start, _), .base(end, _)):
|
||||||
return base.distance(from: start, to: end)
|
return base.distance(from: start, to: end)
|
||||||
case let (.base(index, _), .end):
|
case let (.base(index, _), .end):
|
||||||
return base.distance(from: index, to: base.endIndex) + 1
|
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, _)):
|
case let (.end, .base(index, _)):
|
||||||
return base.distance(from: base.endIndex, to: index) - 1
|
return base.distance(from: base.endIndex, to: index)
|
||||||
case (.end, .end):
|
case (.end, .end):
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ExclusiveReductionsSequence: LazySequenceProtocol {}
|
extension ExclusiveReductions: LazySequenceProtocol
|
||||||
|
where Base: LazySequenceProtocol {}
|
||||||
|
|
||||||
extension ExclusiveReductionsSequence: LazyCollectionProtocol
|
extension ExclusiveReductions: LazyCollectionProtocol
|
||||||
where Base: Collection {}
|
where Base: LazyCollectionProtocol {}
|
||||||
|
|
||||||
extension ExclusiveReductionsSequence.Index: Hashable
|
|
||||||
where Base.Index: Hashable
|
|
||||||
{
|
|
||||||
@inlinable
|
|
||||||
public func hash(into hasher: inout Hasher) {
|
|
||||||
switch representation {
|
|
||||||
case .base(let base, _):
|
|
||||||
hasher.combine(base)
|
|
||||||
case .end:
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Inclusive Reductions
|
// MARK: - Inclusive Reductions
|
||||||
|
|
||||||
extension LazySequenceProtocol {
|
extension LazySequenceProtocol {
|
||||||
|
|
||||||
/// Returns a sequence containing the accumulated results of combining the
|
/// Returns a sequence containing the accumulated results of combining the
|
||||||
/// elements of the sequence using the given closure.
|
/// elements of the sequence using the given closure.
|
||||||
///
|
///
|
||||||
@@ -366,20 +340,22 @@ extension LazySequenceProtocol {
|
|||||||
/// // prints [1, 3, 6, 10]
|
/// // prints [1, 3, 6, 10]
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// - Parameter transform: A closure that combines the previously reduced
|
/// - Parameters:
|
||||||
/// result and the next element in the receiving sequence.
|
/// - transform: A closure that combines the previously reduced result and
|
||||||
|
/// the next element in the receiving sequence.
|
||||||
/// - Returns: A sequence of the reduced elements.
|
/// - Returns: A sequence of the reduced elements.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(1)
|
/// - Complexity: O(1)
|
||||||
@inlinable
|
@inlinable
|
||||||
public func reductions(
|
public func reductions(
|
||||||
_ transform: @escaping (Element, Element) -> Element
|
_ transform: @escaping (Element, Element) -> Element
|
||||||
) -> InclusiveReductionsSequence<Elements> {
|
) -> InclusiveReductions<Self> {
|
||||||
InclusiveReductionsSequence(base: elements, transform: transform)
|
InclusiveReductions(base: self, transform: transform)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Sequence {
|
extension Sequence {
|
||||||
|
|
||||||
/// Returns an array containing the accumulated results of combining the
|
/// Returns an array containing the accumulated results of combining the
|
||||||
/// elements of the sequence using the given closure.
|
/// elements of the sequence using the given closure.
|
||||||
///
|
///
|
||||||
@@ -409,8 +385,9 @@ extension Sequence {
|
|||||||
/// If the sequence has one element, `transform` is never executed and
|
/// If the sequence has one element, `transform` is never executed and
|
||||||
/// an array containing only that first element is returned.
|
/// an array containing only that first element is returned.
|
||||||
///
|
///
|
||||||
/// - Parameter transform: A closure that combines the previously reduced
|
/// - Parameters:
|
||||||
/// result and the next element in the receiving sequence.
|
/// - transform: A closure that combines the previously reduced result and
|
||||||
|
/// the next element in the receiving sequence.
|
||||||
/// - Returns: An array of the reduced elements.
|
/// - Returns: An array of the reduced elements.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||||
@@ -424,7 +401,7 @@ extension Sequence {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public struct InclusiveReductionsSequence<Base: Sequence> {
|
public struct InclusiveReductions<Base: Sequence> {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@@ -441,7 +418,7 @@ public struct InclusiveReductionsSequence<Base: Sequence> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension InclusiveReductionsSequence: Sequence {
|
extension InclusiveReductions: Sequence {
|
||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var iterator: Base.Iterator
|
internal var iterator: Base.Iterator
|
||||||
@@ -455,9 +432,11 @@ extension InclusiveReductionsSequence: Sequence {
|
|||||||
@inlinable
|
@inlinable
|
||||||
internal init(
|
internal init(
|
||||||
iterator: Base.Iterator,
|
iterator: Base.Iterator,
|
||||||
|
element: Base.Element? = nil,
|
||||||
transform: @escaping (Base.Element, Base.Element) -> Base.Element
|
transform: @escaping (Base.Element, Base.Element) -> Base.Element
|
||||||
) {
|
) {
|
||||||
self.iterator = iterator
|
self.iterator = iterator
|
||||||
|
self.element = element
|
||||||
self.transform = transform
|
self.transform = transform
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -475,97 +454,140 @@ extension InclusiveReductionsSequence: Sequence {
|
|||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func makeIterator() -> Iterator {
|
public func makeIterator() -> Iterator {
|
||||||
Iterator(iterator: base.makeIterator(), transform: transform)
|
Iterator(
|
||||||
|
iterator: base.makeIterator(),
|
||||||
|
transform: transform)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension InclusiveReductionsSequence: Collection where Base: Collection {
|
extension InclusiveReductions: Collection where Base: Collection {
|
||||||
public struct Index: Comparable {
|
public struct Index: Comparable {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base.Index
|
internal let representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
internal let result: Element?
|
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(base: Base.Index, result: Element?) {
|
internal init(
|
||||||
self.base = base
|
_ representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
|
||||||
self.result = result
|
) {
|
||||||
|
self.representation = representation
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||||
lhs.base < rhs.base
|
lhs.representation < rhs.representation
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
|
||||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
|
||||||
lhs.base == rhs.base
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var startIndex: Index {
|
public var startIndex: Index {
|
||||||
Index(base: base.startIndex, result: base.first)
|
guard base.startIndex != base.endIndex else { return endIndex }
|
||||||
|
return Index(.start)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var endIndex: Index {
|
public var endIndex: Index { Index(.end) }
|
||||||
Index(base: base.endIndex, result: nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public subscript(index: Index) -> Base.Element {
|
public subscript(position: Index) -> Base.Element {
|
||||||
guard let result = index.result else {
|
switch position.representation {
|
||||||
fatalError("Can't subscript using endIndex")
|
case .start: return base[base.startIndex]
|
||||||
|
case .base(_, let result): return result
|
||||||
|
case .end: fatalError("Cannot get element of end index.")
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(after index: Index) -> Index {
|
public func index(after i: Index) -> Index {
|
||||||
guard let result = index.result else {
|
func index(after i: Base.Index, previous: Base.Element) -> Index {
|
||||||
fatalError("Can't advance past endIndex")
|
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.")
|
||||||
}
|
}
|
||||||
|
|
||||||
let index = base.index(after: index.base)
|
|
||||||
let nextResult = index == base.endIndex
|
|
||||||
? nil
|
|
||||||
: transform(result, base[index])
|
|
||||||
|
|
||||||
return Index(base: index, result: nextResult)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func distance(from start: Index, to end: Index) -> Int {
|
public func distance(from start: Index, to end: Index) -> Int {
|
||||||
base.distance(from: start.base, to: end.base)
|
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 InclusiveReductionsSequence: LazySequenceProtocol {}
|
extension InclusiveReductions: LazySequenceProtocol
|
||||||
|
where Base: LazySequenceProtocol {}
|
||||||
|
|
||||||
extension InclusiveReductionsSequence: LazyCollectionProtocol
|
extension InclusiveReductions: LazyCollectionProtocol
|
||||||
where Base: Collection {}
|
where Base: LazyCollectionProtocol {}
|
||||||
|
|
||||||
extension InclusiveReductionsSequence.Index: Hashable
|
// MARK: - ReductionsIndexRepresentation
|
||||||
where Base.Index: Hashable
|
|
||||||
{
|
@usableFromInline
|
||||||
|
enum ReductionsIndexRepresentation<BaseIndex: Comparable, Result> {
|
||||||
|
case start
|
||||||
|
case base(index: BaseIndex, result: Result)
|
||||||
|
case end
|
||||||
|
}
|
||||||
|
|
||||||
|
extension ReductionsIndexRepresentation: Equatable {
|
||||||
@inlinable
|
@inlinable
|
||||||
public func hash(into hasher: inout Hasher) {
|
static func == (lhs: Self, rhs: Self) -> Bool {
|
||||||
hasher.combine(base)
|
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
|
// MARK: - Scan
|
||||||
|
|
||||||
extension LazySequenceProtocol {
|
extension LazySequenceProtocol {
|
||||||
|
|
||||||
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
|
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
|
||||||
@inlinable
|
@inlinable
|
||||||
public func scan<Result>(
|
public func scan<Result>(
|
||||||
_ initial: Result,
|
_ initial: Result,
|
||||||
_ transform: @escaping (Result, Element) -> Result
|
_ transform: @escaping (Result, Element) -> Result
|
||||||
) -> ExclusiveReductionsSequence<Elements, Result> {
|
) -> ExclusiveReductions<Result, Self> {
|
||||||
reductions(initial, transform)
|
reductions(initial, transform)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -574,12 +596,13 @@ extension LazySequenceProtocol {
|
|||||||
public func scan<Result>(
|
public func scan<Result>(
|
||||||
into initial: Result,
|
into initial: Result,
|
||||||
_ transform: @escaping (inout Result, Element) -> Void
|
_ transform: @escaping (inout Result, Element) -> Void
|
||||||
) -> ExclusiveReductionsSequence<Elements, Result> {
|
) -> ExclusiveReductions<Result, Self> {
|
||||||
reductions(into: initial, transform)
|
reductions(into: initial, transform)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Sequence {
|
extension Sequence {
|
||||||
|
|
||||||
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
|
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
|
||||||
@inlinable
|
@inlinable
|
||||||
public func scan<Result>(
|
public func scan<Result>(
|
||||||
@@ -600,16 +623,18 @@ extension Sequence {
|
|||||||
}
|
}
|
||||||
|
|
||||||
extension LazySequenceProtocol {
|
extension LazySequenceProtocol {
|
||||||
|
|
||||||
@available(*, deprecated, message: "Use reductions(_:) instead.")
|
@available(*, deprecated, message: "Use reductions(_:) instead.")
|
||||||
@inlinable
|
@inlinable
|
||||||
public func scan(
|
public func scan(
|
||||||
_ transform: @escaping (Element, Element) -> Element
|
_ transform: @escaping (Element, Element) -> Element
|
||||||
) -> InclusiveReductionsSequence<Elements> {
|
) -> InclusiveReductions<Self> {
|
||||||
reductions(transform)
|
reductions(transform)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Sequence {
|
extension Sequence {
|
||||||
|
|
||||||
@available(*, deprecated, message: "Use reductions(_:) instead.")
|
@available(*, deprecated, message: "Use reductions(_:) instead.")
|
||||||
@inlinable
|
@inlinable
|
||||||
public func scan(
|
public func scan(
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ extension MutableCollection where Self: BidirectionalCollection {
|
|||||||
}
|
}
|
||||||
return (lower, upper)
|
return (lower, upper)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reverses the elements within the given subrange.
|
/// Reverses the elements within the given subrange.
|
||||||
///
|
///
|
||||||
/// This example reverses the numbers within the subrange at the start of the
|
/// This example reverses the numbers within the subrange at the start of the
|
||||||
@@ -75,8 +75,8 @@ extension MutableCollection where Self: BidirectionalCollection {
|
|||||||
|
|
||||||
extension MutableCollection {
|
extension MutableCollection {
|
||||||
/// Swaps the elements of the two given subranges, up to the upper bound of
|
/// Swaps the elements of the two given subranges, up to the upper bound of
|
||||||
/// the smaller subrange. The returned indices are the ends of the two ranges
|
/// the smaller subrange. The returned indices are the ends of the two
|
||||||
/// that were actually swapped.
|
/// ranges that were actually swapped.
|
||||||
///
|
///
|
||||||
/// Input:
|
/// Input:
|
||||||
/// [a b c d e f g h i j k l m n o p]
|
/// [a b c d e f g h i j k l m n o p]
|
||||||
@@ -100,20 +100,19 @@ extension MutableCollection {
|
|||||||
) -> (Index, Index) {
|
) -> (Index, Index) {
|
||||||
assert(!lhs.isEmpty)
|
assert(!lhs.isEmpty)
|
||||||
assert(!rhs.isEmpty)
|
assert(!rhs.isEmpty)
|
||||||
|
|
||||||
var p = lhs.lowerBound
|
var p = lhs.lowerBound
|
||||||
var q = rhs.lowerBound
|
var q = rhs.lowerBound
|
||||||
repeat {
|
repeat {
|
||||||
swapAt(p, q)
|
swapAt(p, q)
|
||||||
formIndex(after: &p)
|
formIndex(after: &p)
|
||||||
formIndex(after: &q)
|
formIndex(after: &q)
|
||||||
}
|
} while p != lhs.upperBound && q != rhs.upperBound
|
||||||
while p != lhs.upperBound && q != rhs.upperBound
|
|
||||||
return (p, q)
|
return (p, q)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rotates the elements within the given subrange so that the element at the
|
/// Rotates the elements within the given subrange so that the element
|
||||||
/// specified index becomes the start of the subrange.
|
/// at the specified index becomes the start of the subrange.
|
||||||
///
|
///
|
||||||
/// Rotating a collection is equivalent to breaking the collection into two
|
/// Rotating a collection is equivalent to breaking the collection into two
|
||||||
/// sections at the index `newStart`, and then swapping those two sections.
|
/// sections at the index `newStart`, and then swapping those two sections.
|
||||||
@@ -139,25 +138,27 @@ extension MutableCollection {
|
|||||||
subrange: Range<Index>,
|
subrange: Range<Index>,
|
||||||
toStartAt newStart: Index
|
toStartAt newStart: Index
|
||||||
) -> Index {
|
) -> Index {
|
||||||
var m = newStart, s = subrange.lowerBound
|
var m = newStart
|
||||||
|
var s = subrange.lowerBound
|
||||||
let e = subrange.upperBound
|
let e = subrange.upperBound
|
||||||
|
|
||||||
// Handle the trivial cases
|
// Handle the trivial cases
|
||||||
if s == m { return e }
|
if s == m { return e }
|
||||||
if m == e { return s }
|
if m == e { return s }
|
||||||
|
|
||||||
// We have two regions of possibly-unequal length that need to be exchanged.
|
// We have two regions of possibly-unequal length that need to be
|
||||||
// The return value of this method is going to be the position following
|
// exchanged. The return value of this method is going to be the
|
||||||
// that of the element that is currently last (element j).
|
// position following that of the element that is currently last
|
||||||
|
// (element j).
|
||||||
//
|
//
|
||||||
// [a b c d e f g|h i j] or [a b c|d e f g h i j]
|
// [a b c d e f g|h i j] or [a b c|d e f g h i j]
|
||||||
// ^ ^ ^ ^ ^ ^
|
// ^ ^ ^ ^ ^ ^
|
||||||
// s m e s m e
|
// s m e s m e
|
||||||
//
|
//
|
||||||
var ret = e // start with a known incorrect result.
|
var ret = e // start with a known incorrect result.
|
||||||
while true {
|
while true {
|
||||||
// Exchange the leading elements of each region (up to the length of the
|
// Exchange the leading elements of each region (up to the
|
||||||
// shorter region).
|
// length of the shorter region).
|
||||||
//
|
//
|
||||||
// [a b c d e f g|h i j] or [a b c|d e f g h i j]
|
// [a b c d e f g|h i j] or [a b c|d e f g h i j]
|
||||||
// ^^^^^ ^^^^^ ^^^^^ ^^^^^
|
// ^^^^^ ^^^^^ ^^^^^ ^^^^^
|
||||||
@@ -166,22 +167,23 @@ extension MutableCollection {
|
|||||||
// s s1 m m1/e s s1/m m1 e
|
// s s1 m m1/e s s1/m m1 e
|
||||||
//
|
//
|
||||||
let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e)
|
let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e)
|
||||||
|
|
||||||
if m1 == e {
|
if m1 == e {
|
||||||
// Left-hand case: we have moved element j into position. If we haven't
|
// Left-hand case: we have moved element j into position. if
|
||||||
// already, we can capture the return value which is in s1.
|
// we haven't already, we can capture the return value which
|
||||||
|
// is in s1.
|
||||||
//
|
//
|
||||||
// Note: the STL breaks the loop into two just to avoid this comparison
|
// Note: the STL breaks the loop into two just to avoid this
|
||||||
// once the return value is known. I'm not sure it's a worthwhile
|
// comparison once the return value is known. I'm not sure
|
||||||
// optimization, though.
|
// it's a worthwhile optimization, though.
|
||||||
if ret == e { ret = s1 }
|
if ret == e { ret = s1 }
|
||||||
|
|
||||||
// If both regions were the same size, we're done.
|
// If both regions were the same size, we're done.
|
||||||
if s1 == m { break }
|
if s1 == m { break }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Now we have a smaller problem that is also a rotation, so we can adjust
|
// Now we have a smaller problem that is also a rotation, so we
|
||||||
// our bounds and repeat.
|
// can adjust our bounds and repeat.
|
||||||
//
|
//
|
||||||
// h i j[d e f g|a b c] or d e f[a b c|g h i j]
|
// h i j[d e f g|a b c] or d e f[a b c|g h i j]
|
||||||
// ^ ^ ^ ^ ^ ^
|
// ^ ^ ^ ^ ^ ^
|
||||||
@@ -189,12 +191,12 @@ extension MutableCollection {
|
|||||||
s = s1
|
s = s1
|
||||||
if s == m { m = m1 }
|
if s == m { m = m1 }
|
||||||
}
|
}
|
||||||
|
|
||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rotates the elements of this collection so that the element at the
|
/// Rotates the elements of this collection so that the element
|
||||||
/// specified index becomes the start of the collection.
|
/// at the specified index becomes the start of the collection.
|
||||||
///
|
///
|
||||||
/// Rotating a collection is equivalent to breaking the collection into two
|
/// Rotating a collection is equivalent to breaking the collection into two
|
||||||
/// sections at the index `newStart`, and then swapping those two sections.
|
/// sections at the index `newStart`, and then swapping those two sections.
|
||||||
@@ -219,8 +221,8 @@ extension MutableCollection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
extension MutableCollection where Self: BidirectionalCollection {
|
extension MutableCollection where Self: BidirectionalCollection {
|
||||||
/// Rotates the elements within the given subrange so that the element at the
|
/// Rotates the elements within the given subrange so that the element
|
||||||
/// specified index becomes the start of the subrange.
|
/// at the specified index becomes the start of the subrange.
|
||||||
///
|
///
|
||||||
/// Rotating a collection is equivalent to breaking the collection into two
|
/// Rotating a collection is equivalent to breaking the collection into two
|
||||||
/// sections at the index `newStart`, and then swapping those two sections.
|
/// sections at the index `newStart`, and then swapping those two sections.
|
||||||
@@ -253,13 +255,13 @@ extension MutableCollection where Self: BidirectionalCollection {
|
|||||||
return newStart == p ? q : p
|
return newStart == p ? q : p
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rotates the elements of this collection so that the element at the
|
/// Rotates the elements of this collection so that the element
|
||||||
/// specified index becomes the start of the collection.
|
/// at the specified index becomes the start of the collection.
|
||||||
///
|
///
|
||||||
/// Rotating a collection is equivalent to breaking the collection into two
|
/// Rotating a collection is equivalent to breaking the collection into two
|
||||||
/// sections at the index `newStart`, and then swapping those two sections. In
|
/// sections at the index `newStart`, and then swapping those two sections.
|
||||||
/// this example, the `numbers` array is rotated so that the element at index
|
/// In this example, the `numbers` array is rotated so that the element at
|
||||||
/// `3` (`40`) is first:
|
/// index `3` (`40`) is first:
|
||||||
///
|
///
|
||||||
/// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
/// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||||
/// let oldStart = numbers.rotate(toStartAt: 3)
|
/// let oldStart = numbers.rotate(toStartAt: 3)
|
||||||
@@ -277,3 +279,22 @@ extension MutableCollection where Self: BidirectionalCollection {
|
|||||||
rotate(subrange: startIndex..<endIndex, toStartAt: newStart)
|
rotate(subrange: startIndex..<endIndex, toStartAt: newStart)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Deprecations
|
||||||
|
|
||||||
|
extension MutableCollection {
|
||||||
|
@available(*, deprecated, renamed: "rotate(subrange:toStartAt:)")
|
||||||
|
@discardableResult
|
||||||
|
public mutating func rotate(
|
||||||
|
subrange: Range<Index>,
|
||||||
|
at newStart: Index
|
||||||
|
) -> Index {
|
||||||
|
rotate(subrange: subrange, toStartAt: newStart)
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, deprecated, renamed: "rotate(toStartAt:)")
|
||||||
|
@discardableResult
|
||||||
|
public mutating func rotate(at newStart: Index) -> Index {
|
||||||
|
rotate(toStartAt: newStart)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,85 +14,80 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
extension Sequence {
|
extension Sequence {
|
||||||
/// Returns a sequence stepping through the elements every `step` starting at
|
/// Returns a sequence stepping through the elements every `step` starting
|
||||||
/// the first value. Any remainders of the stride will be trimmed.
|
/// 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: 2) // == [0, 2, 4, 6, 8, 10]
|
||||||
/// (0...10).striding(by: 3) // == [0, 3, 6, 9]
|
/// (0...10).striding(by: 3) // == [0, 3, 6, 9]
|
||||||
///
|
///
|
||||||
/// - Complexity: O(1). Access to successive values is O(k) where _k_ is the
|
/// - Complexity: O(1). Access to successive values is O(k) where
|
||||||
/// striding `step`.
|
/// _k_ is the striding `step`.
|
||||||
///
|
///
|
||||||
/// - Parameter step: The amount to step with each iteration.
|
/// - Parameter step: The amount to step with each iteration.
|
||||||
/// - Returns: Returns a sequence for stepping through the elements by the
|
/// - Returns: Returns a sequence for stepping through the
|
||||||
/// specified amount.
|
/// elements by the specified amount.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func striding(by step: Int) -> StridingSequence<Self> {
|
public func striding(by step: Int) -> StrideSequence<Self> {
|
||||||
StridingSequence(base: self, stride: step)
|
StrideSequence(base: self, stride: step)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Collection {
|
extension Collection {
|
||||||
/// Returns a sequence stepping through the elements every `step` starting at
|
/// Returns a sequence stepping through the elements every `step` starting
|
||||||
/// the first value. Any remainders of the stride will be trimmed.
|
/// 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: 2) // == [0, 2, 4, 6, 8, 10]
|
||||||
/// (0...10).striding(by: 3) // == [0, 3, 6, 9]
|
/// (0...10).striding(by: 3) // == [0, 3, 6, 9]
|
||||||
///
|
///
|
||||||
/// - Complexity: O(1). Access to successive values is O(1) if the collection
|
/// - Complexity: O(1). Access to successive values is O(1) if the
|
||||||
/// conforms to `RandomAccessCollection`; otherwise, O(_k_), where _k_ is
|
/// collection conforms to `RandomAccessCollection`; otherwise,
|
||||||
/// the striding `step`.
|
/// O(_k_), where _k_ is the striding `step`.
|
||||||
///
|
///
|
||||||
/// - Parameter step: The amount to step with each iteration.
|
/// - Parameter step: The amount to step with each iteration.
|
||||||
/// - Returns: Returns a collection for stepping through the elements by the
|
/// - Returns: Returns a collection for stepping through the
|
||||||
/// specified amount.
|
/// elements by the specified amount.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func striding(by step: Int) -> StridingCollection<Self> {
|
public func striding(by step: Int) -> StrideCollection<Self> {
|
||||||
StridingCollection(base: self, stride: step)
|
StrideCollection(base: self, stride: step)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A wrapper that strides over a base sequence.
|
/// A wrapper that strides over a base sequence.
|
||||||
public struct StridingSequence<Base: Sequence> {
|
public struct StrideSequence<Base: Sequence>: Sequence {
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let stride: Int
|
internal let stride: Int
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(base: Base, stride: Int) {
|
internal init(base: Base, stride: Int) {
|
||||||
precondition(stride > 0, "Stride must be greater than zero")
|
precondition(stride > 0, "striding must be greater than zero")
|
||||||
self.base = base
|
self.base = base
|
||||||
self.stride = stride
|
self.stride = stride
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension StridingSequence {
|
extension StrideSequence {
|
||||||
@inlinable
|
|
||||||
public func striding(by step: Int) -> Self {
|
|
||||||
Self(base: base, stride: stride * step)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension StridingSequence: Sequence {
|
/// An iterator over a `Stride` sequence.
|
||||||
/// An iterator over a `StridingSequence` instance.
|
|
||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var iterator: Base.Iterator
|
internal var iterator: Base.Iterator
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let stride: Int
|
internal let stride: Int
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var striding: Bool = false
|
internal var striding: Bool = false
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(iterator: Base.Iterator, stride: Int) {
|
internal init(iterator: Base.Iterator, stride: Int) {
|
||||||
self.iterator = iterator
|
self.iterator = iterator
|
||||||
self.stride = stride
|
self.stride = stride
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public mutating func next() -> Base.Element? {
|
public mutating func next() -> Base.Element? {
|
||||||
guard striding else {
|
guard striding else {
|
||||||
@@ -105,24 +100,28 @@ extension StridingSequence: Sequence {
|
|||||||
return iterator.next()
|
return iterator.next()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func makeIterator() -> Iterator {
|
public func makeIterator() -> Iterator {
|
||||||
Iterator(iterator: base.makeIterator(), stride: stride)
|
Iterator(iterator: base.makeIterator(), stride: stride)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension StridingSequence: LazySequenceProtocol
|
extension StrideSequence {
|
||||||
where Base: LazySequenceProtocol {}
|
@inlinable
|
||||||
|
public func striding(by step: Int) -> Self {
|
||||||
|
Self(base: base, stride: stride * step)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A wrapper that strides over a base collection.
|
/// A wrapper that strides over a base collection.
|
||||||
public struct StridingCollection<Base: Collection> {
|
public struct StrideCollection<Base: Collection> {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let stride: Int
|
internal let stride: Int
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(base: Base, stride: Int) {
|
internal init(base: Base, stride: Int) {
|
||||||
precondition(stride > 0, "striding must be greater than zero")
|
precondition(stride > 0, "striding must be greater than zero")
|
||||||
@@ -131,51 +130,52 @@ public struct StridingCollection<Base: Collection> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension StridingCollection {
|
extension StrideCollection {
|
||||||
@inlinable
|
@inlinable
|
||||||
public func striding(by step: Int) -> Self {
|
public func striding(by step: Int) -> Self {
|
||||||
Self(base: base, stride: stride * step)
|
Self(base: base, stride: stride * step)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension StridingCollection: Collection {
|
extension StrideCollection: Collection {
|
||||||
/// A position in a `StridingCollection` instance.
|
|
||||||
|
/// A position in a `Stride` collection.
|
||||||
public struct Index: Comparable {
|
public struct Index: Comparable {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base.Index
|
internal let base: Base.Index
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal init(_ base: Base.Index) {
|
internal init(_ base: Base.Index) {
|
||||||
self.base = base
|
self.base = base
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||||
lhs.base < rhs.base
|
lhs.base < rhs.base
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var startIndex: Index {
|
public var startIndex: Index {
|
||||||
Index(base.startIndex)
|
Index(base.startIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var endIndex: Index {
|
public var endIndex: Index {
|
||||||
Index(base.endIndex)
|
Index(base.endIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public subscript(i: Index) -> Base.Element {
|
public subscript(i: Index) -> Base.Element {
|
||||||
base[i.base]
|
base[i.base]
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(after i: Index) -> Index {
|
public func index(after i: Index) -> Index {
|
||||||
precondition(i.base != base.endIndex, "Advancing past end index")
|
precondition(i.base < base.endIndex, "Advancing past end index")
|
||||||
return index(i, offsetBy: 1)
|
return index(i, offsetBy: 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(
|
public func index(
|
||||||
_ i: Index,
|
_ i: Index,
|
||||||
@@ -184,12 +184,12 @@ extension StridingCollection: Collection {
|
|||||||
) -> Index? {
|
) -> Index? {
|
||||||
guard n != 0 else { return i }
|
guard n != 0 else { return i }
|
||||||
guard limit != i else { return nil }
|
guard limit != i else { return nil }
|
||||||
|
|
||||||
return n > 0
|
return n > 0
|
||||||
? offsetForward(i, offsetBy: n, limitedBy: limit)
|
? offsetForward(i, offsetBy: n, limitedBy: limit)
|
||||||
: offsetBackward(i, offsetBy: -n, limitedBy: limit)
|
: offsetBackward(i, offsetBy: -n, limitedBy: limit)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetForward(
|
internal func offsetForward(
|
||||||
_ i: Index,
|
_ i: Index,
|
||||||
@@ -219,44 +219,39 @@ extension StridingCollection: Collection {
|
|||||||
: nil
|
: nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetBackward(
|
internal func offsetBackward(
|
||||||
_ i: Index,
|
_ i: Index,
|
||||||
offsetBy n: Int,
|
offsetBy n: Int,
|
||||||
limitedBy limit: Index
|
limitedBy limit: Index
|
||||||
) -> Index? {
|
) -> Index? {
|
||||||
// We typically use the ternary operator but this significantly increases
|
let distance =
|
||||||
// compile times when using Swift 5.3.2
|
i == endIndex
|
||||||
// https://github.com/apple/swift-algorithms/issues/146
|
? -((base.count - 1) % stride + 1) + (n - 1) * -stride
|
||||||
let distance: Int
|
: n * -stride
|
||||||
if i == endIndex {
|
|
||||||
distance = -((base.count - 1) % stride + 1) + (n - 1) * -stride
|
|
||||||
} else {
|
|
||||||
distance = n * -stride
|
|
||||||
}
|
|
||||||
return base.index(
|
return base.index(
|
||||||
i.base,
|
i.base,
|
||||||
offsetBy: distance,
|
offsetBy: distance,
|
||||||
limitedBy: limit.base
|
limitedBy: limit.base
|
||||||
).map(Index.init)
|
).map(Index.init)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var count: Int {
|
public var count: Int {
|
||||||
base.isEmpty ? 0 : (base.count - 1) / stride + 1
|
base.isEmpty ? 0 : (base.count - 1) / stride + 1
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func distance(from start: Index, to end: Index) -> Int {
|
public func distance(from start: Index, to end: Index) -> Int {
|
||||||
let distance = base.distance(from: start.base, to: end.base)
|
let distance = base.distance(from: start.base, to: end.base)
|
||||||
return distance / stride + (distance % stride).signum()
|
return distance / stride + (distance % stride).signum()
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||||
precondition(distance <= 0 || i.base != base.endIndex, "Advancing past end index")
|
precondition(distance <= 0 || i.base < base.endIndex, "Advancing past end index")
|
||||||
precondition(distance >= 0 || i.base != base.startIndex, "Incrementing past start index")
|
precondition(distance >= 0 || i.base > base.startIndex, "Incrementing past start index")
|
||||||
let limit = distance > 0 ? endIndex : startIndex
|
let limit = distance > 0 ? endIndex : startIndex
|
||||||
let idx = index(i, offsetBy: distance, limitedBy: limit)
|
let idx = index(i, offsetBy: distance, limitedBy: limit)
|
||||||
precondition(idx != nil, "The distance \(distance) is not valid for this collection")
|
precondition(idx != nil, "The distance \(distance) is not valid for this collection")
|
||||||
@@ -264,20 +259,15 @@ extension StridingCollection: Collection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension StridingCollection: BidirectionalCollection
|
extension StrideCollection: BidirectionalCollection
|
||||||
where Base: RandomAccessCollection {
|
where Base: RandomAccessCollection {
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(before i: Index) -> Index {
|
public func index(before i: Index) -> Index {
|
||||||
precondition(i.base != base.startIndex, "Incrementing past start index")
|
precondition(i.base > base.startIndex, "Incrementing past start index")
|
||||||
return index(i, offsetBy: -1)
|
return index(i, offsetBy: -1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension StridingCollection: RandomAccessCollection
|
extension StrideCollection: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||||
where Base: RandomAccessCollection {}
|
extension StrideCollection.Index: Hashable where Base.Index: Hashable {}
|
||||||
|
|
||||||
extension StridingCollection: LazySequenceProtocol, LazyCollectionProtocol
|
|
||||||
where Base: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
extension StridingCollection.Index: Hashable where Base.Index: Hashable {}
|
|
||||||
@@ -17,10 +17,10 @@ extension BidirectionalCollection {
|
|||||||
/// Returns a subsequence containing the elements from the end until
|
/// Returns a subsequence containing the elements from the end until
|
||||||
/// `predicate` returns `false` and skipping the remaining elements.
|
/// `predicate` returns `false` and skipping the remaining elements.
|
||||||
///
|
///
|
||||||
/// - Parameter predicate: A closure that takes an element of the sequence as
|
/// - Parameter predicate: A closure that takes an element of the
|
||||||
/// its argument and returns `true` if the element should be included or
|
/// sequence as its argument and returns `true` if the element should
|
||||||
/// `false` if it should be excluded. Once the predicate returns `false` it
|
/// be included or `false` if it should be excluded. Once the predicate
|
||||||
/// will not be called again.
|
/// returns `false` it will not be called again.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||||
@inlinable
|
@inlinable
|
||||||
|
|||||||
@@ -7,91 +7,6 @@
|
|||||||
//
|
//
|
||||||
// See https://swift.org/LICENSE.txt for license information
|
// See https://swift.org/LICENSE.txt for license information
|
||||||
//
|
//
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// trimmingPrefix(while:)
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
extension Collection {
|
|
||||||
/// Returns a `SubSequence` formed by discarding all elements at the start of
|
|
||||||
/// the collection which satisfy the given predicate.
|
|
||||||
///
|
|
||||||
/// This example uses `trimmingPrefix(while:)` to get a substring without the
|
|
||||||
/// white space at the beginning of the string:
|
|
||||||
///
|
|
||||||
/// let myString = " hello, world "
|
|
||||||
/// print(myString.trimmingPrefix(while: \.isWhitespace)) // "hello, world "
|
|
||||||
///
|
|
||||||
/// - Parameter predicate: A closure which determines if the element should be
|
|
||||||
/// omitted from the resulting slice.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
|
||||||
///
|
|
||||||
@inlinable
|
|
||||||
public func trimmingPrefix(
|
|
||||||
while predicate: (Element) throws -> Bool
|
|
||||||
) rethrows -> SubSequence {
|
|
||||||
let start = try endOfPrefix(while: predicate)
|
|
||||||
return self[start...]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// trimPrefix(while:)
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
extension Collection where Self: RangeReplaceableCollection {
|
|
||||||
/// Mutates a `Collection` by discarding all elements at the start of it which
|
|
||||||
/// satisfy the given predicate.
|
|
||||||
///
|
|
||||||
/// This example uses `trimPrefix(while:)` to remove the white space at the
|
|
||||||
/// beginning of the string:
|
|
||||||
///
|
|
||||||
/// let myString = " hello, world "
|
|
||||||
/// myString.trimPrefix(while: \.isWhitespace)
|
|
||||||
/// print(myString) // "hello, world "
|
|
||||||
///
|
|
||||||
/// - Parameter predicate: A closure which determines if the element should be
|
|
||||||
/// removed from the string.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
|
||||||
///
|
|
||||||
@inlinable
|
|
||||||
@_disfavoredOverload
|
|
||||||
public mutating func trimPrefix(
|
|
||||||
while predicate: (Element) throws -> Bool
|
|
||||||
) rethrows {
|
|
||||||
let end = try endOfPrefix(while: predicate)
|
|
||||||
removeSubrange(startIndex..<end)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Collection where Self == Self.SubSequence {
|
|
||||||
/// Mutates a `Collection` by discarding all elements at the start of it which
|
|
||||||
/// satisfy the given predicate.
|
|
||||||
///
|
|
||||||
/// This example uses `trimPrefix(while:)` to remove the white space at the
|
|
||||||
/// beginning of the string:
|
|
||||||
///
|
|
||||||
/// let myString = " hello, world "
|
|
||||||
/// myString.trimPrefix(while: \.isWhitespace)
|
|
||||||
/// print(myString) // "hello, world "
|
|
||||||
///
|
|
||||||
/// - Parameters predicate: A closure which determines if the element should
|
|
||||||
/// be removed from the string.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
|
||||||
///
|
|
||||||
@inlinable
|
|
||||||
public mutating func trimPrefix(
|
|
||||||
while predicate: (Element) throws -> Bool
|
|
||||||
) rethrows {
|
|
||||||
self = try trimmingPrefix(while: predicate)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// trimming(while:) / trimmingSuffix(while:)
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
extension BidirectionalCollection {
|
extension BidirectionalCollection {
|
||||||
@@ -104,8 +19,9 @@ extension BidirectionalCollection {
|
|||||||
/// let myString = " hello, world "
|
/// let myString = " hello, world "
|
||||||
/// print(myString.trimming(while: \.isWhitespace)) // "hello, world"
|
/// print(myString.trimming(while: \.isWhitespace)) // "hello, world"
|
||||||
///
|
///
|
||||||
/// - Parameter predicate: A closure which determines if the element should be
|
/// - Parameters:
|
||||||
/// omitted from the resulting slice.
|
/// - predicate: A closure which determines if the element should be
|
||||||
|
/// omitted from the resulting slice.
|
||||||
///
|
///
|
||||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||||
///
|
///
|
||||||
@@ -113,128 +29,8 @@ extension BidirectionalCollection {
|
|||||||
public func trimming(
|
public func trimming(
|
||||||
while predicate: (Element) throws -> Bool
|
while predicate: (Element) throws -> Bool
|
||||||
) rethrows -> SubSequence {
|
) rethrows -> SubSequence {
|
||||||
try trimmingPrefix(while: predicate).trimmingSuffix(while: predicate)
|
let start = try endOfPrefix(while: predicate)
|
||||||
}
|
let end = try self[start...].startOfSuffix(while: predicate)
|
||||||
|
return self[start..<end]
|
||||||
/// Returns a `SubSequence` formed by discarding all elements at the end of
|
|
||||||
/// the collection which satisfy the given predicate.
|
|
||||||
///
|
|
||||||
/// This example uses `trimmingSuffix(while:)` to get a substring without the
|
|
||||||
/// white space at the end of the string:
|
|
||||||
///
|
|
||||||
/// let myString = " hello, world "
|
|
||||||
/// print(myString.trimmingSuffix(while: \.isWhitespace)) // " hello, world"
|
|
||||||
///
|
|
||||||
/// - Parameter predicate: A closure which determines if the element should be
|
|
||||||
/// omitted from the resulting slice.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
|
||||||
///
|
|
||||||
@inlinable
|
|
||||||
public func trimmingSuffix(
|
|
||||||
while predicate: (Element) throws -> Bool
|
|
||||||
) rethrows -> SubSequence {
|
|
||||||
let end = try startOfSuffix(while: predicate)
|
|
||||||
return self[..<end]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
// trim(while:) / trimSuffix(while:)
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
extension BidirectionalCollection where Self: RangeReplaceableCollection {
|
|
||||||
/// Mutates a `BidirectionalCollection` by discarding all elements at the
|
|
||||||
/// start and at the end of it which satisfy the given predicate.
|
|
||||||
///
|
|
||||||
/// This example uses `trim(while:)` to remove the white space at the
|
|
||||||
/// beginning of the string:
|
|
||||||
///
|
|
||||||
/// let myString = " hello, world "
|
|
||||||
/// myString.trim(while: \.isWhitespace)
|
|
||||||
/// print(myString) // "hello, world"
|
|
||||||
///
|
|
||||||
/// - Parameter predicate: A closure which determines if the element should be
|
|
||||||
/// removed from the string.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
|
||||||
///
|
|
||||||
@inlinable
|
|
||||||
@_disfavoredOverload
|
|
||||||
public mutating func trim(
|
|
||||||
while predicate: (Element) throws -> Bool
|
|
||||||
) rethrows {
|
|
||||||
try trimSuffix(while: predicate)
|
|
||||||
try trimPrefix(while: predicate)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mutates a `BidirectionalCollection` by discarding all elements at the end
|
|
||||||
/// of it which satisfy the given predicate.
|
|
||||||
///
|
|
||||||
/// This example uses `trimSuffix(while:)` to remove the white space at the
|
|
||||||
/// beginning of the string:
|
|
||||||
///
|
|
||||||
/// let myString = " hello, world "
|
|
||||||
/// myString.trimSuffix(while: \.isWhitespace)
|
|
||||||
/// print(myString) // " hello, world"
|
|
||||||
///
|
|
||||||
/// - Parameter predicate: A closure which determines if the element should be
|
|
||||||
/// removed from the string.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
|
||||||
///
|
|
||||||
@inlinable
|
|
||||||
@_disfavoredOverload
|
|
||||||
public mutating func trimSuffix(
|
|
||||||
while predicate: (Element) throws -> Bool
|
|
||||||
) rethrows {
|
|
||||||
let start = try startOfSuffix(while: predicate)
|
|
||||||
removeSubrange(start..<endIndex)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension BidirectionalCollection where Self == Self.SubSequence {
|
|
||||||
/// Mutates a `BidirectionalCollection` by discarding all elements at the
|
|
||||||
/// start and at the end of it which satisfy the given predicate.
|
|
||||||
///
|
|
||||||
/// This example uses `trim(while:)` to remove the white space at the
|
|
||||||
/// beginning of the string:
|
|
||||||
///
|
|
||||||
/// let myString = " hello, world "
|
|
||||||
/// myString.trim(while: \.isWhitespace)
|
|
||||||
/// print(myString) // "hello, world"
|
|
||||||
///
|
|
||||||
/// - Parameter predicate: A closure which determines if the element should be
|
|
||||||
/// removed from the string.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
|
||||||
///
|
|
||||||
@inlinable
|
|
||||||
public mutating func trim(
|
|
||||||
while predicate: (Element) throws -> Bool
|
|
||||||
) rethrows {
|
|
||||||
self = try trimming(while: predicate)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mutates a `BidirectionalCollection` by discarding all elements at the end
|
|
||||||
/// of it which satisfy the given predicate.
|
|
||||||
///
|
|
||||||
/// This example uses `trimSuffix(while:)` to remove the white space at the
|
|
||||||
/// beginning of the string:
|
|
||||||
///
|
|
||||||
/// let myString = " hello, world "
|
|
||||||
/// myString.trimSuffix(while: \.isWhitespace)
|
|
||||||
/// print(myString) // " hello, world"
|
|
||||||
///
|
|
||||||
/// - Parameter predicate: A closure which determines if the element should be
|
|
||||||
/// removed from the string.
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
|
||||||
///
|
|
||||||
@inlinable
|
|
||||||
public mutating func trimSuffix(
|
|
||||||
while predicate: (Element) throws -> Bool
|
|
||||||
) rethrows {
|
|
||||||
self = try trimmingSuffix(while: predicate)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,15 +10,15 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
/// A sequence wrapper that leaves out duplicate elements of a base sequence.
|
/// A sequence wrapper that leaves out duplicate elements of a base sequence.
|
||||||
public struct UniquedSequence<Base: Sequence, Subject: Hashable> {
|
public struct Uniqued<Base: Sequence, Subject: Hashable> {
|
||||||
/// The base collection.
|
/// The base collection.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
/// The projection function.
|
/// The projection function.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let projection: (Base.Element) -> Subject
|
internal let projection: (Base.Element) -> Subject
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {
|
internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {
|
||||||
self.base = base
|
self.base = base
|
||||||
@@ -26,18 +26,18 @@ public struct UniquedSequence<Base: Sequence, Subject: Hashable> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension UniquedSequence: Sequence {
|
extension Uniqued: Sequence {
|
||||||
/// The iterator for a `UniquedSequence` instance.
|
/// The iterator for a `Uniqued` sequence.
|
||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var base: Base.Iterator
|
internal var base: Base.Iterator
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let projection: (Base.Element) -> Subject
|
internal let projection: (Base.Element) -> Subject
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var seen: Set<Subject> = []
|
internal var seen: Set<Subject> = []
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal init(
|
internal init(
|
||||||
base: Base.Iterator,
|
base: Base.Iterator,
|
||||||
@@ -46,7 +46,7 @@ extension UniquedSequence: Sequence {
|
|||||||
self.base = base
|
self.base = base
|
||||||
self.projection = projection
|
self.projection = projection
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public mutating func next() -> Base.Element? {
|
public mutating func next() -> Base.Element? {
|
||||||
while let element = base.next() {
|
while let element = base.next() {
|
||||||
@@ -57,15 +57,14 @@ extension UniquedSequence: Sequence {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func makeIterator() -> Iterator {
|
public func makeIterator() -> Iterator {
|
||||||
Iterator(base: base.makeIterator(), projection: projection)
|
Iterator(base: base.makeIterator(), projection: projection)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension UniquedSequence: LazySequenceProtocol
|
extension Uniqued: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||||
where Base: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// uniqued()
|
// uniqued()
|
||||||
@@ -84,8 +83,8 @@ extension Sequence where Element: Hashable {
|
|||||||
/// .
|
/// .
|
||||||
/// - Complexity: O(1).
|
/// - Complexity: O(1).
|
||||||
@inlinable
|
@inlinable
|
||||||
public func uniqued() -> UniquedSequence<Self, Element> {
|
public func uniqued() -> Uniqued<Self, Element> {
|
||||||
UniquedSequence(base: self, projection: { $0 })
|
Uniqued(base: self, projection: { $0 })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,9 +102,9 @@ extension Sequence {
|
|||||||
/// // Prints '["dog", "pig", "cat", "ox"]'
|
/// // Prints '["dog", "pig", "cat", "ox"]'
|
||||||
///
|
///
|
||||||
/// - Parameter projection: A closure that transforms an element into the
|
/// - Parameter projection: A closure that transforms an element into the
|
||||||
/// value to use for uniqueness. If `projection` returns the same value for
|
/// value to use for uniqueness. If `projection` returns the same value
|
||||||
/// two different elements, the second element will be excluded from the
|
/// for two different elements, the second element will be excluded
|
||||||
/// resulting array.
|
/// from the resulting array.
|
||||||
///
|
///
|
||||||
/// - Returns: An array with only the unique elements of this sequence, as
|
/// - Returns: An array with only the unique elements of this sequence, as
|
||||||
/// determined by the result of `projection` for each element.
|
/// determined by the result of `projection` for each element.
|
||||||
@@ -139,7 +138,7 @@ extension LazySequenceProtocol {
|
|||||||
@inlinable
|
@inlinable
|
||||||
public func uniqued<Subject: Hashable>(
|
public func uniqued<Subject: Hashable>(
|
||||||
on projection: @escaping (Element) -> Subject
|
on projection: @escaping (Element) -> Subject
|
||||||
) -> UniquedSequence<Self, Subject> {
|
) -> Uniqued<Self, Subject> {
|
||||||
UniquedSequence(base: self, projection: projection)
|
Uniqued(base: self, projection: projection)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+101
-105
@@ -39,73 +39,73 @@ extension Collection {
|
|||||||
/// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`.
|
/// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`.
|
||||||
/// Access to successive windows is O(1).
|
/// Access to successive windows is O(1).
|
||||||
@inlinable
|
@inlinable
|
||||||
public func windows(ofCount count: Int) -> WindowsOfCountCollection<Self> {
|
public func windows(ofCount count: Int) -> Windows<Self> {
|
||||||
WindowsOfCountCollection(base: self, windowSize: count)
|
Windows(base: self, size: count)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A collection wrapper that presents a sliding window over the elements of
|
/// A collection wrapper that presents a sliding window over the elements of
|
||||||
/// a collection.
|
/// a collection.
|
||||||
public struct WindowsOfCountCollection<Base: Collection> {
|
public struct Windows<Base: Collection> {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let windowSize: Int
|
internal let size: Int
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var endOfFirstWindow: Base.Index?
|
internal var firstUpperBound: Base.Index?
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(base: Base, windowSize: Int) {
|
internal init(base: Base, size: Int) {
|
||||||
precondition(windowSize > 0, "Windows size must be greater than zero")
|
precondition(size > 0, "Windows size must be greater than zero")
|
||||||
self.base = base
|
self.base = base
|
||||||
self.windowSize = windowSize
|
self.size = size
|
||||||
self.endOfFirstWindow =
|
self.firstUpperBound =
|
||||||
base.index(base.startIndex, offsetBy: windowSize, limitedBy: base.endIndex)
|
base.index(base.startIndex, offsetBy: size, limitedBy: base.endIndex)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension WindowsOfCountCollection: Collection {
|
extension Windows: Collection {
|
||||||
/// A position in a `WindowsOfCountCollection` instance.
|
/// A position in a `Windows` collection.
|
||||||
public struct Index: Comparable {
|
public struct Index: Comparable {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var lowerBound: Base.Index
|
internal var lowerBound: Base.Index
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var upperBound: Base.Index
|
internal var upperBound: Base.Index
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(lowerBound: Base.Index, upperBound: Base.Index) {
|
internal init(lowerBound: Base.Index, upperBound: Base.Index) {
|
||||||
self.lowerBound = lowerBound
|
self.lowerBound = lowerBound
|
||||||
self.upperBound = upperBound
|
self.upperBound = upperBound
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public static func == (lhs: Index, rhs: Index) -> Bool {
|
public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||||
lhs.lowerBound == rhs.lowerBound
|
lhs.lowerBound == rhs.lowerBound
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||||
lhs.lowerBound < rhs.lowerBound
|
lhs.lowerBound < rhs.lowerBound
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var startIndex: Index {
|
public var startIndex: Index {
|
||||||
if let upperBound = endOfFirstWindow {
|
if let upperBound = firstUpperBound {
|
||||||
return Index(lowerBound: base.startIndex, upperBound: upperBound)
|
return Index(lowerBound: base.startIndex, upperBound: upperBound)
|
||||||
} else {
|
} else {
|
||||||
return endIndex
|
return endIndex
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public var endIndex: Index {
|
public var endIndex: Index {
|
||||||
Index(lowerBound: base.endIndex, upperBound: base.endIndex)
|
Index(lowerBound: base.endIndex, upperBound: base.endIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public subscript(index: Index) -> Base.SubSequence {
|
public subscript(index: Index) -> Base.SubSequence {
|
||||||
precondition(
|
precondition(
|
||||||
@@ -113,28 +113,26 @@ extension WindowsOfCountCollection: Collection {
|
|||||||
"Windows index is out of range")
|
"Windows index is out of range")
|
||||||
return base[index.lowerBound..<index.upperBound]
|
return base[index.lowerBound..<index.upperBound]
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(after index: Index) -> Index {
|
public func index(after index: Index) -> Index {
|
||||||
precondition(index != endIndex, "Advancing past end index")
|
precondition(index < endIndex, "Advancing past end index")
|
||||||
guard index.upperBound < base.endIndex else { return endIndex }
|
guard index.upperBound < base.endIndex else { return endIndex }
|
||||||
|
return Index(
|
||||||
let lowerBound = windowSize == 1
|
lowerBound: base.index(after: index.lowerBound),
|
||||||
? index.upperBound
|
upperBound: base.index(after: index.upperBound)
|
||||||
: base.index(after: index.lowerBound)
|
)
|
||||||
let upperBound = base.index(after: index.upperBound)
|
|
||||||
return Index(lowerBound: lowerBound, upperBound: upperBound)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||||
guard distance != 0 else { return i }
|
guard distance != 0 else { return i }
|
||||||
|
|
||||||
return distance > 0
|
return distance > 0
|
||||||
? offsetForward(i, by: distance)
|
? offsetForward(i, by: distance)
|
||||||
: offsetBackward(i, by: -distance)
|
: offsetBackward(i, by: -distance)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(
|
public func index(
|
||||||
_ i: Index,
|
_ i: Index,
|
||||||
@@ -143,7 +141,7 @@ extension WindowsOfCountCollection: Collection {
|
|||||||
) -> Index? {
|
) -> Index? {
|
||||||
guard distance != 0 else { return i }
|
guard distance != 0 else { return i }
|
||||||
guard limit != i else { return nil }
|
guard limit != i else { return nil }
|
||||||
|
|
||||||
if distance > 0 {
|
if distance > 0 {
|
||||||
return limit > i
|
return limit > i
|
||||||
? offsetForward(i, by: distance, limitedBy: limit)
|
? offsetForward(i, by: distance, limitedBy: limit)
|
||||||
@@ -154,28 +152,28 @@ extension WindowsOfCountCollection: Collection {
|
|||||||
: offsetBackward(i, by: -distance)
|
: offsetBackward(i, by: -distance)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||||
else { fatalError("Index is out of bounds") }
|
else { fatalError("Index is out of bounds") }
|
||||||
return index
|
return index
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
||||||
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
||||||
else { fatalError("Index is out of bounds") }
|
else { fatalError("Index is out of bounds") }
|
||||||
return index
|
return index
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetForward(
|
internal func offsetForward(
|
||||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||||
) -> Index? {
|
) -> Index? {
|
||||||
assert(distance > 0)
|
assert(distance > 0)
|
||||||
assert(limit > i)
|
assert(limit > i)
|
||||||
|
|
||||||
// `endIndex` and the index before it both have `base.endIndex` as their
|
// `endIndex` and the index before it both have `base.endIndex` as their
|
||||||
// upper bound, so we first advance to the base index _before_ the upper
|
// upper bound, so we first advance to the base index _before_ the upper
|
||||||
// bound of the output, in order to avoid advancing past the end of `base`
|
// bound of the output, in order to avoid advancing past the end of `base`
|
||||||
@@ -186,31 +184,31 @@ extension WindowsOfCountCollection: Collection {
|
|||||||
// input: [x|x x x x x|x x x x] [x x|x x x x x|x x x]
|
// input: [x|x x x x x|x x x x] [x x|x x x x x|x x x]
|
||||||
// |> > >|>| or |> > >|
|
// |> > >|>| or |> > >|
|
||||||
// output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`)
|
// output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`)
|
||||||
|
|
||||||
if distance >= windowSize {
|
if distance >= size {
|
||||||
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the lower
|
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the lower
|
||||||
// bound of the output is greater than or equal to the upper bound of the
|
// bound of the output is greater than or equal to the upper bound of the
|
||||||
// input.
|
// input.
|
||||||
|
|
||||||
// input: [x|x x x x|x x x x x x x]
|
// input: [x|x x x x|x x x x x x x]
|
||||||
// |> >|> > >|>|
|
// |> >|> > >|>|
|
||||||
// output: [x x x x x x x|x x x x|x]
|
// output: [x x x x x x x|x x x x|x]
|
||||||
|
|
||||||
guard limit.lowerBound >= i.upperBound,
|
guard limit.lowerBound >= i.upperBound,
|
||||||
let lowerBound = base.index(
|
let lowerBound = base.index(
|
||||||
i.upperBound,
|
i.upperBound,
|
||||||
offsetBy: distance - windowSize,
|
offsetBy: distance - size,
|
||||||
limitedBy: limit.lowerBound),
|
limitedBy: limit.lowerBound),
|
||||||
let indexBeforeUpperBound = base.index(
|
let indexBeforeUpperBound = base.index(
|
||||||
lowerBound,
|
lowerBound,
|
||||||
offsetBy: windowSize - 1,
|
offsetBy: size - 1,
|
||||||
limitedBy: limit.upperBound)
|
limitedBy: limit.upperBound)
|
||||||
else { return nil }
|
else { return nil }
|
||||||
|
|
||||||
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
|
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
|
||||||
// `endIndex`.
|
// `endIndex`.
|
||||||
guard indexBeforeUpperBound != base.endIndex else { return endIndex }
|
guard indexBeforeUpperBound != base.endIndex else { return endIndex }
|
||||||
|
|
||||||
return Index(
|
return Index(
|
||||||
lowerBound: lowerBound,
|
lowerBound: lowerBound,
|
||||||
upperBound: base.index(after: indexBeforeUpperBound))
|
upperBound: base.index(after: indexBeforeUpperBound))
|
||||||
@@ -218,35 +216,36 @@ extension WindowsOfCountCollection: Collection {
|
|||||||
// input: [x|x x x x x x|x x x x x]
|
// input: [x|x x x x x x|x x x x x]
|
||||||
// |> > > >| |> > >|>|
|
// |> > > >| |> > >|>|
|
||||||
// output: [x x x x x|x x x x x x|x]
|
// output: [x x x x x|x x x x x x|x]
|
||||||
|
|
||||||
guard let indexBeforeUpperBound = base.index(
|
guard
|
||||||
i.upperBound,
|
let indexBeforeUpperBound = base.index(
|
||||||
offsetBy: distance - 1,
|
i.upperBound,
|
||||||
limitedBy: limit.upperBound)
|
offsetBy: distance - 1,
|
||||||
|
limitedBy: limit.upperBound)
|
||||||
else { return nil }
|
else { return nil }
|
||||||
|
|
||||||
// If `indexBeforeUpperBound` equals the limit, the upper bound itself
|
// If `indexBeforeUpperBound` equals the limit, the upper bound itself
|
||||||
// exceeds it.
|
// exceeds it.
|
||||||
guard indexBeforeUpperBound != limit.upperBound || limit == endIndex
|
guard indexBeforeUpperBound != limit.upperBound || limit == endIndex
|
||||||
else { return nil }
|
else { return nil }
|
||||||
|
|
||||||
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
|
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
|
||||||
// `endIndex`.
|
// `endIndex`.
|
||||||
guard indexBeforeUpperBound != base.endIndex else { return endIndex }
|
guard indexBeforeUpperBound != base.endIndex else { return endIndex }
|
||||||
|
|
||||||
return Index(
|
return Index(
|
||||||
lowerBound: base.index(i.lowerBound, offsetBy: distance),
|
lowerBound: base.index(i.lowerBound, offsetBy: distance),
|
||||||
upperBound: base.index(after: indexBeforeUpperBound))
|
upperBound: base.index(after: indexBeforeUpperBound))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetBackward(
|
internal func offsetBackward(
|
||||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||||
) -> Index? {
|
) -> Index? {
|
||||||
assert(distance > 0)
|
assert(distance > 0)
|
||||||
assert(limit < i)
|
assert(limit < i)
|
||||||
|
|
||||||
if i == endIndex {
|
if i == endIndex {
|
||||||
// Advance `base.endIndex` by `distance - 1`, because the index before
|
// Advance `base.endIndex` by `distance - 1`, because the index before
|
||||||
// `endIndex` also has `base.endIndex` as its upper bound.
|
// `endIndex` also has `base.endIndex` as its upper bound.
|
||||||
@@ -256,17 +255,18 @@ extension WindowsOfCountCollection: Collection {
|
|||||||
// input: [x x x x x x x x x x] (`endIndex`)
|
// input: [x x x x x x x x x x] (`endIndex`)
|
||||||
// |< < < < <|< < <|
|
// |< < < < <|< < <|
|
||||||
// output: [x x|x x x x x|x x x]
|
// output: [x x|x x x x x|x x x]
|
||||||
|
|
||||||
guard let upperBound = base.index(
|
guard
|
||||||
base.endIndex,
|
let upperBound = base.index(
|
||||||
offsetBy: -(distance - 1),
|
base.endIndex,
|
||||||
limitedBy: limit.upperBound)
|
offsetBy: -(distance - 1),
|
||||||
|
limitedBy: limit.upperBound)
|
||||||
else { return nil }
|
else { return nil }
|
||||||
|
|
||||||
return Index(
|
return Index(
|
||||||
lowerBound: base.index(upperBound, offsetBy: -windowSize),
|
lowerBound: base.index(upperBound, offsetBy: -size),
|
||||||
upperBound: upperBound)
|
upperBound: upperBound)
|
||||||
} else if distance >= windowSize {
|
} else if distance >= size {
|
||||||
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the upper
|
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the upper
|
||||||
// bound of the output is less than or equal to the lower bound of the
|
// bound of the output is less than or equal to the lower bound of the
|
||||||
// input.
|
// input.
|
||||||
@@ -274,39 +274,40 @@ extension WindowsOfCountCollection: Collection {
|
|||||||
// input: [x x x x x x x|x x x x|x]
|
// input: [x x x x x x x|x x x x|x]
|
||||||
// |< < < <|< <|
|
// |< < < <|< <|
|
||||||
// output: [x|x x x x|x x x x x x x]
|
// output: [x|x x x x|x x x x x x x]
|
||||||
|
|
||||||
guard limit.upperBound <= i.lowerBound,
|
guard limit.upperBound <= i.lowerBound,
|
||||||
let upperBound = base.index(
|
let upperBound = base.index(
|
||||||
i.lowerBound,
|
i.lowerBound,
|
||||||
offsetBy: -(distance - windowSize),
|
offsetBy: -(distance - size),
|
||||||
limitedBy: limit.upperBound)
|
limitedBy: limit.upperBound)
|
||||||
else { return nil }
|
else { return nil }
|
||||||
|
|
||||||
return Index(
|
return Index(
|
||||||
lowerBound: base.index(upperBound, offsetBy: -windowSize),
|
lowerBound: base.index(upperBound, offsetBy: -size),
|
||||||
upperBound: upperBound)
|
upperBound: upperBound)
|
||||||
} else {
|
} else {
|
||||||
// input: [x x x x x|x x x x x x|x]
|
// input: [x x x x x|x x x x x x|x]
|
||||||
// |< < < <| |< < < <|
|
// |< < < <| |< < < <|
|
||||||
// output: [x|x x x x x x|x x x x x]
|
// output: [x|x x x x x x|x x x x x]
|
||||||
|
|
||||||
guard let lowerBound = base.index(
|
guard
|
||||||
i.lowerBound,
|
let lowerBound = base.index(
|
||||||
offsetBy: -distance,
|
i.lowerBound,
|
||||||
limitedBy: limit.lowerBound)
|
offsetBy: -distance,
|
||||||
|
limitedBy: limit.lowerBound)
|
||||||
else { return nil }
|
else { return nil }
|
||||||
|
|
||||||
return Index(
|
return Index(
|
||||||
lowerBound: lowerBound,
|
lowerBound: lowerBound,
|
||||||
upperBound: base.index(i.lowerBound, offsetBy: -distance))
|
upperBound: base.index(i.lowerBound, offsetBy: -distance))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func distance(from start: Index, to end: Index) -> Int {
|
public func distance(from start: Index, to end: Index) -> Int {
|
||||||
guard start <= end else { return -distance(from: end, to: start) }
|
guard start <= end else { return -distance(from: end, to: start) }
|
||||||
guard start != end else { return 0 }
|
guard start != end else { return 0 }
|
||||||
guard end != endIndex else {
|
guard end < endIndex else {
|
||||||
// We add 1 here because the index before `endIndex` also has
|
// We add 1 here because the index before `endIndex` also has
|
||||||
// `base.endIndex` as its upper bound.
|
// `base.endIndex` as its upper bound.
|
||||||
return base[start.upperBound...].count + 1
|
return base[start.upperBound...].count + 1
|
||||||
@@ -319,27 +320,25 @@ extension WindowsOfCountCollection: Collection {
|
|||||||
// start: [x|x x x x|x x x x x x x]
|
// start: [x|x x x x|x x x x x x x]
|
||||||
// |- - - -|> >|
|
// |- - - -|> >|
|
||||||
// end: [x x x x x x x|x x x x|x]
|
// end: [x x x x x x x|x x x x|x]
|
||||||
|
|
||||||
return windowSize + base[start.upperBound..<end.lowerBound].count
|
return size + base[start.upperBound..<end.lowerBound].count
|
||||||
} else {
|
} else {
|
||||||
// start: [x|x x x x x x|x x x x x]
|
// start: [x|x x x x x x|x x x x x]
|
||||||
// |> > > >|
|
// |> > > >|
|
||||||
// end: [x x x x x|x x x x x x|x]
|
// end: [x x x x x|x x x x x x|x]
|
||||||
|
|
||||||
return base[start.lowerBound..<end.lowerBound].count
|
return base[start.lowerBound..<end.lowerBound].count
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension WindowsOfCountCollection: BidirectionalCollection
|
extension Windows: BidirectionalCollection where Base: BidirectionalCollection {
|
||||||
where Base: BidirectionalCollection
|
|
||||||
{
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(before index: Index) -> Index {
|
public func index(before index: Index) -> Index {
|
||||||
precondition(index != startIndex, "Incrementing past start index")
|
precondition(index > startIndex, "Incrementing past start index")
|
||||||
if index == endIndex {
|
if index == endIndex {
|
||||||
return Index(
|
return Index(
|
||||||
lowerBound: base.index(index.lowerBound, offsetBy: -windowSize),
|
lowerBound: base.index(index.lowerBound, offsetBy: -size),
|
||||||
upperBound: index.upperBound
|
upperBound: index.upperBound
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
@@ -351,10 +350,7 @@ extension WindowsOfCountCollection: BidirectionalCollection
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension WindowsOfCountCollection: RandomAccessCollection
|
extension Windows: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||||
where Base: RandomAccessCollection {}
|
extension Windows: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
||||||
|
extension Windows: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||||
extension WindowsOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol
|
extension Windows.Index: Hashable where Base.Index: Hashable {}
|
||||||
where Base: LazySequenceProtocol {}
|
|
||||||
|
|
||||||
extension WindowsOfCountCollection.Index: Hashable where Base.Index: Hashable {}
|
|
||||||
@@ -11,9 +11,9 @@
|
|||||||
|
|
||||||
#error("""
|
#error("""
|
||||||
|
|
||||||
-----------------------------------------------------
|
-----------------------------------------------------
|
||||||
|
|
||||||
Please test with `swift test --enable-test-discovery`
|
Please test with `swift test --enable-test-discovery`
|
||||||
|
|
||||||
-----------------------------------------------------
|
-----------------------------------------------------
|
||||||
""")
|
""")
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
|
||||||
//
|
|
||||||
// This source file is part of the Swift Algorithms open source project
|
|
||||||
//
|
|
||||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
|
||||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
|
||||||
//
|
|
||||||
// See https://swift.org/LICENSE.txt for license information
|
|
||||||
//
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
import XCTest
|
|
||||||
import Algorithms
|
|
||||||
|
|
||||||
final class AdjacentPairsTests: XCTestCase {
|
|
||||||
func testEmptySequence() {
|
|
||||||
let pairs = (0...).prefix(0).adjacentPairs()
|
|
||||||
XCTAssertEqualSequences(pairs, [], by: ==)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testOneElementSequence() {
|
|
||||||
let pairs = (0...).prefix(1).adjacentPairs()
|
|
||||||
XCTAssertEqualSequences(pairs, [], by: ==)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testTwoElementSequence() {
|
|
||||||
let pairs = (0...).prefix(2).adjacentPairs()
|
|
||||||
XCTAssertEqualSequences(pairs, [(0, 1)], by: ==)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testThreeElementSequence() {
|
|
||||||
let pairs = (0...).prefix(3).adjacentPairs()
|
|
||||||
XCTAssertEqualSequences(pairs, [(0, 1), (1, 2)], by: ==)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testManySequences() {
|
|
||||||
for n in 4...100 {
|
|
||||||
let pairs = (0...).prefix(n).adjacentPairs()
|
|
||||||
XCTAssertEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testZeroElements() {
|
|
||||||
let pairs = (0..<0).adjacentPairs()
|
|
||||||
XCTAssertEqual(pairs.startIndex, pairs.endIndex)
|
|
||||||
XCTAssertEqualSequences(pairs, [], by: ==)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testOneElement() {
|
|
||||||
let pairs = (0..<1).adjacentPairs()
|
|
||||||
XCTAssertEqual(pairs.startIndex, pairs.endIndex)
|
|
||||||
XCTAssertEqualSequences(pairs, [], by: ==)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testTwoElements() {
|
|
||||||
let pairs = (0..<2).adjacentPairs()
|
|
||||||
XCTAssertEqualSequences(pairs, [(0, 1)], by: ==)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testThreeElements() {
|
|
||||||
let pairs = (0..<3).adjacentPairs()
|
|
||||||
XCTAssertEqualSequences(pairs, [(0, 1), (1, 2)], by: ==)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testManyElements() {
|
|
||||||
for n in 4...100 {
|
|
||||||
let pairs = (0..<n).adjacentPairs()
|
|
||||||
XCTAssertEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testIndexTraversals() {
|
|
||||||
let validator = IndexValidator<AdjacentPairsCollection<Range<Int>>>()
|
|
||||||
validator.validate((0..<0).adjacentPairs(), expectedCount: 0)
|
|
||||||
validator.validate((0..<1).adjacentPairs(), expectedCount: 0)
|
|
||||||
validator.validate((0..<2).adjacentPairs(), expectedCount: 1)
|
|
||||||
validator.validate((0..<5).adjacentPairs(), expectedCount: 4)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testLaziness() {
|
|
||||||
XCTAssertLazySequence((0...).lazy.adjacentPairs())
|
|
||||||
XCTAssertLazyCollection((0..<100).lazy.adjacentPairs())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
import XCTest
|
||||||
|
|
||||||
@testable import Algorithms
|
@testable import Algorithms
|
||||||
|
|
||||||
final class ChainTests: XCTestCase {
|
final class ChainTests: XCTestCase {
|
||||||
@@ -17,52 +18,51 @@ final class ChainTests: XCTestCase {
|
|||||||
let run = chain((1...).prefix(10), 20...)
|
let run = chain((1...).prefix(10), 20...)
|
||||||
XCTAssertEqualSequences(run.prefix(20), Array(1...10) + (20..<30))
|
XCTAssertEqualSequences(run.prefix(20), Array(1...10) + (20..<30))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testChainForwardCollection() {
|
func testChainForwardCollection() {
|
||||||
let s1 = Set(0...10)
|
let s1 = Set(0...10)
|
||||||
let s2 = Set(20...30)
|
let s2 = Set(20...30)
|
||||||
let c = chain(s1, s2)
|
let c = chain(s1, s2)
|
||||||
XCTAssertEqualSequences(c, Array(s1) + Array(s2))
|
XCTAssertEqualSequences(c, Array(s1) + Array(s2))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testChainBidirectionalCollection() {
|
func testChainBidirectionalCollection() {
|
||||||
let s1 = "ABCDEFGHIJ"
|
let s1 = "ABCDEFGHIJ"
|
||||||
let s2 = "klmnopqrstuv"
|
let s2 = "klmnopqrstuv"
|
||||||
let c = chain(s1, s2)
|
let c = chain(s1, s2)
|
||||||
|
|
||||||
XCTAssertEqualSequences(c, "ABCDEFGHIJklmnopqrstuv")
|
XCTAssertEqualSequences(c, "ABCDEFGHIJklmnopqrstuv")
|
||||||
XCTAssertEqualSequences(c.reversed(), "ABCDEFGHIJklmnopqrstuv".reversed())
|
XCTAssertEqualSequences(c.reversed(), "ABCDEFGHIJklmnopqrstuv".reversed())
|
||||||
XCTAssertEqualSequences(chain(s1.reversed(), s2), "JIHGFEDCBAklmnopqrstuv")
|
XCTAssertEqualSequences(chain(s1.reversed(), s2), "JIHGFEDCBAklmnopqrstuv")
|
||||||
}
|
}
|
||||||
|
|
||||||
func testChainIndexTraversals() {
|
func testChainIndexTraversals() {
|
||||||
let validator = IndexValidator<Chain2Sequence<String, String>>(
|
validateIndexTraversals(
|
||||||
indicesIncludingEnd: { chain in
|
chain("abcd", "XYZ"),
|
||||||
|
chain("abcd", ""),
|
||||||
|
chain("", "XYZ"),
|
||||||
|
chain("", ""),
|
||||||
|
indices: { chain in
|
||||||
chain.base1.indices.map { .init(first: $0) }
|
chain.base1.indices.map { .init(first: $0) }
|
||||||
+ chain.base2.indices.map { .init(second: $0) }
|
+ chain.base2.indices.map { .init(second: $0) }
|
||||||
+ [.init(second: chain.base2.endIndex)]
|
+ [.init(second: chain.base2.endIndex)]
|
||||||
})
|
})
|
||||||
|
|
||||||
validator.validate(chain("abcd", "XYZ"), expectedCount: 4 + 3)
|
|
||||||
validator.validate(chain("abcd", ""), expectedCount: 4 + 0)
|
|
||||||
validator.validate(chain("", "XYZ"), expectedCount: 0 + 3)
|
|
||||||
validator.validate(chain("", ""), expectedCount: 0 + 0)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func testChainIndexOffsetAcrossBoundary() {
|
func testChainIndexOffsetAcrossBoundary() {
|
||||||
let c = chain("abc", "XYZ")
|
let c = chain("abc", "XYZ")
|
||||||
|
|
||||||
do {
|
do {
|
||||||
let i = c.index(c.startIndex, offsetBy: 3, limitedBy: c.startIndex)
|
let i = c.index(c.startIndex, offsetBy: 3, limitedBy: c.startIndex)
|
||||||
XCTAssertNil(i)
|
XCTAssertNil(i)
|
||||||
}
|
}
|
||||||
|
|
||||||
do {
|
do {
|
||||||
let i = c.index(c.startIndex, offsetBy: 4)
|
let i = c.index(c.startIndex, offsetBy: 4)
|
||||||
let j = c.index(i, offsetBy: -2)
|
let j = c.index(i, offsetBy: -2)
|
||||||
XCTAssertEqual(c[j], "c")
|
XCTAssertEqual(c[j], "c")
|
||||||
}
|
}
|
||||||
|
|
||||||
do {
|
do {
|
||||||
let i = c.index(c.startIndex, offsetBy: 3)
|
let i = c.index(c.startIndex, offsetBy: 3)
|
||||||
let j = c.index(i, offsetBy: -1, limitedBy: i)
|
let j = c.index(i, offsetBy: -1, limitedBy: i)
|
||||||
|
|||||||
@@ -9,23 +9,22 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
|
||||||
import Algorithms
|
import Algorithms
|
||||||
|
import XCTest
|
||||||
|
|
||||||
final class ChunkedTests: XCTestCase {
|
final class ChunkedTests: XCTestCase {
|
||||||
let fruits = [
|
let fruits = [
|
||||||
"Apple", "Apricot", "Avocado", "Banana",
|
"Apple", "Apricot", "Avocado", "Banana",
|
||||||
"Bilberry", "Blackberry", "Blackcurrant", "Blueberry",
|
"Bilberry", "Blackberry", "Blackcurrant", "Blueberry",
|
||||||
"Currant", "Cherry", "Cherimoya", "Clementine",
|
"Currant", "Cherry", "Cherimoya", "Clementine",
|
||||||
"Date", "Damson", "Dragonfruit", "Durian",
|
"Date", "Damson", "Dragonfruit", "Durian",
|
||||||
"Eggplant", "Elderberry", "Feijoa",
|
"Eggplant", "Elderberry", "Feijoa",
|
||||||
"Grape", "Grapefruit", "Guava",
|
"Grape", "Grapefruit", "Guava",
|
||||||
]
|
]
|
||||||
|
|
||||||
func validateFruitChunks<C: BidirectionalCollection>(_ fruitChunks: C)
|
func validateFruitChunks<C: BidirectionalCollection>(_ fruitChunks: C)
|
||||||
where C.Element == ArraySlice<String>
|
where C.Element == ArraySlice<String> {
|
||||||
{
|
let expectedChunks: [ArraySlice<String>] = [
|
||||||
let expectedChunks: Array<ArraySlice<String>> = [
|
|
||||||
fruits[0..<3],
|
fruits[0..<3],
|
||||||
fruits[3..<8],
|
fruits[3..<8],
|
||||||
fruits[8..<12],
|
fruits[8..<12],
|
||||||
@@ -35,25 +34,21 @@ final class ChunkedTests: XCTestCase {
|
|||||||
fruits[19..<22],
|
fruits[19..<22],
|
||||||
]
|
]
|
||||||
XCTAssertEqualSequences(expectedChunks, fruitChunks, by: ==)
|
XCTAssertEqualSequences(expectedChunks, fruitChunks, by: ==)
|
||||||
|
|
||||||
XCTAssertEqual(fruits[19..<22], fruitChunks.last)
|
XCTAssertEqual(fruits[19..<22], fruitChunks.last)
|
||||||
|
|
||||||
XCTAssertEqual("Currant", fruitChunks.first(where: { $0.count == 4 })?.first)
|
XCTAssertEqual("Currant", fruitChunks.first(where: { $0.count == 4 })?.first)
|
||||||
XCTAssertEqual("Date", fruitChunks.last(where: { $0.count == 4 })?.first)
|
XCTAssertEqual("Date", fruitChunks.last(where: { $0.count == 4 })?.first)
|
||||||
XCTAssertNil(fruitChunks.first(where: { $0.count == 0 }))
|
XCTAssertNil(fruitChunks.first(where: { $0.count == 0 }))
|
||||||
XCTAssertNil(fruitChunks.last(where: { $0.count == 0 }))
|
XCTAssertNil(fruitChunks.last(where: { $0.count == 0 }))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testSimple() {
|
func testSimple() {
|
||||||
// Example
|
// Example
|
||||||
let names = ["David", "Kyle", "Karoy", "Nate"]
|
let names = ["David", "Kyle", "Karoy", "Nate"]
|
||||||
let chunks = names.chunked(on: { $0.first! })
|
let chunks = names.chunked(on: { $0.first })
|
||||||
let expected: [(Character, ArraySlice<String>)] = [
|
XCTAssertEqualSequences([["David"], ["Kyle", "Karoy"], ["Nate"]], chunks)
|
||||||
("D", ["David"]),
|
|
||||||
("K", ["Kyle", "Karoy"]),
|
|
||||||
("N", ["Nate"])]
|
|
||||||
XCTAssertEqualSequences(expected, chunks, by: ==)
|
|
||||||
|
|
||||||
// Empty sequence
|
// Empty sequence
|
||||||
XCTAssertEqual(0, names.prefix(0).chunked(on: { $0.first }).count)
|
XCTAssertEqual(0, names.prefix(0).chunked(on: { $0.first }).count)
|
||||||
|
|
||||||
@@ -61,87 +56,75 @@ final class ChunkedTests: XCTestCase {
|
|||||||
let namesStartingWithD = ["David", "Don", "Darren"]
|
let namesStartingWithD = ["David", "Don", "Darren"]
|
||||||
XCTAssertEqual(1, namesStartingWithD.chunked(on: { $0.first }).count)
|
XCTAssertEqual(1, namesStartingWithD.chunked(on: { $0.first }).count)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testChunkedOn() {
|
func testChunkedOn() {
|
||||||
validateFruitChunks(fruits.chunked(on: { $0.first }).map { $1 })
|
validateFruitChunks(fruits.chunked(on: { $0.first }))
|
||||||
|
|
||||||
let lazyChunks = fruits.lazy.chunked(on: { $0.first })
|
let lazyChunks = fruits.lazy.chunked(on: { $0.first })
|
||||||
validateFruitChunks(lazyChunks.map { $1 })
|
validateFruitChunks(lazyChunks)
|
||||||
IndexValidator().validate(lazyChunks)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func testChunkedBy() {
|
func testChunkedBy() {
|
||||||
validateFruitChunks(fruits.chunked(by: { $0.first == $1.first }))
|
validateFruitChunks(fruits.chunked(by: { $0.first == $1.first }))
|
||||||
|
|
||||||
let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first })
|
let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first })
|
||||||
validateFruitChunks(lazyChunks)
|
validateFruitChunks(lazyChunks)
|
||||||
IndexValidator().validate(lazyChunks)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func testChunkedByComparesConsecutiveElements() {
|
|
||||||
XCTAssertEqualSequences(
|
|
||||||
[1, 2, 3, 4, 6, 7, 8, 9].chunked(by: { $1 - $0 == 1 }),
|
|
||||||
[[1, 2, 3, 4], [6, 7, 8, 9]])
|
|
||||||
|
|
||||||
XCTAssertEqualSequences(
|
|
||||||
[1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }),
|
|
||||||
[[1, 2, 3, 4], [6, 7, 8, 9]])
|
|
||||||
|
|
||||||
print(Array([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 })))
|
|
||||||
print(Array([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 }).reversed()))
|
|
||||||
|
|
||||||
XCTAssertEqualSequences(
|
|
||||||
[1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }).reversed(),
|
|
||||||
[[6, 7, 8, 9], [1, 2, 3, 4]])
|
|
||||||
|
|
||||||
IndexValidator().validate([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 }))
|
|
||||||
}
|
|
||||||
|
|
||||||
func testChunkedLazy() {
|
func testChunkedLazy() {
|
||||||
XCTAssertLazySequence(fruits.lazy.chunked(by: { $0.first == $1.first }))
|
XCTAssertLazySequence(fruits.lazy.chunked(by: { $0.first == $1.first }))
|
||||||
XCTAssertLazySequence(fruits.lazy.chunked(on: { $0.first }))
|
XCTAssertLazySequence(fruits.lazy.chunked(on: { $0.first }))
|
||||||
}
|
}
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// Tests for `chunks(ofCount:)`
|
// Tests for `chunks(ofCount:)`
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
func testChunksOfCount() {
|
func testChunksOfCount() {
|
||||||
XCTAssertEqualSequences([Int]().chunks(ofCount: 1), [])
|
XCTAssertEqualSequences([Int]().chunks(ofCount: 1), [])
|
||||||
XCTAssertEqualSequences([Int]().chunks(ofCount: 5), [])
|
XCTAssertEqualSequences([Int]().chunks(ofCount: 5), [])
|
||||||
|
|
||||||
let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||||
XCTAssertEqualSequences(collection1.chunks(ofCount: 1),
|
XCTAssertEqualSequences(
|
||||||
[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
|
collection1.chunks(ofCount: 1),
|
||||||
XCTAssertEqualSequences(collection1.chunks(ofCount: 3),
|
[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
|
||||||
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]])
|
XCTAssertEqualSequences(
|
||||||
XCTAssertEqualSequences(collection1.chunks(ofCount: 5),
|
collection1.chunks(ofCount: 3),
|
||||||
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
|
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]])
|
||||||
XCTAssertEqualSequences(collection1.chunks(ofCount: 11),
|
XCTAssertEqualSequences(
|
||||||
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
|
collection1.chunks(ofCount: 5),
|
||||||
|
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
|
||||||
|
XCTAssertEqualSequences(
|
||||||
|
collection1.chunks(ofCount: 11),
|
||||||
|
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
|
||||||
|
|
||||||
let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
|
let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
|
||||||
XCTAssertEqualSequences(collection2.chunks(ofCount: 3),
|
XCTAssertEqualSequences(
|
||||||
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]])
|
collection2.chunks(ofCount: 3),
|
||||||
|
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testChunksOfCountBidirectional() {
|
func testChunksOfCountBidirectional() {
|
||||||
let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||||
|
|
||||||
XCTAssertEqualSequences(collection1.chunks(ofCount: 1).reversed(),
|
XCTAssertEqualSequences(
|
||||||
[[10], [9], [8], [7], [6], [5], [4], [3], [2], [1]])
|
collection1.chunks(ofCount: 1).reversed(),
|
||||||
XCTAssertEqualSequences(collection1.chunks(ofCount: 3).reversed(),
|
[[10], [9], [8], [7], [6], [5], [4], [3], [2], [1]])
|
||||||
[[10], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
|
XCTAssertEqualSequences(
|
||||||
XCTAssertEqualSequences(collection1.chunks(ofCount: 5).reversed(),
|
collection1.chunks(ofCount: 3).reversed(),
|
||||||
[[6, 7, 8, 9, 10], [1, 2, 3, 4, 5]])
|
[[10], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
|
||||||
XCTAssertEqualSequences(collection1.chunks(ofCount: 11).reversed(),
|
XCTAssertEqualSequences(
|
||||||
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
|
collection1.chunks(ofCount: 5).reversed(),
|
||||||
|
[[6, 7, 8, 9, 10], [1, 2, 3, 4, 5]])
|
||||||
|
XCTAssertEqualSequences(
|
||||||
|
collection1.chunks(ofCount: 11).reversed(),
|
||||||
|
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
|
||||||
|
|
||||||
let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
|
let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
|
||||||
XCTAssertEqualSequences(collection2.chunks(ofCount: 3).reversed(),
|
XCTAssertEqualSequences(
|
||||||
[[10, 11], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
|
collection2.chunks(ofCount: 3).reversed(),
|
||||||
|
[[10, 11], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testChunksOfCountCount() {
|
func testChunksOfCountCount() {
|
||||||
XCTAssertEqual([Int]().chunks(ofCount: 1).count, 0)
|
XCTAssertEqual([Int]().chunks(ofCount: 1).count, 0)
|
||||||
XCTAssertEqual([Int]().chunks(ofCount: 5).count, 0)
|
XCTAssertEqual([Int]().chunks(ofCount: 5).count, 0)
|
||||||
@@ -151,26 +134,23 @@ final class ChunkedTests: XCTestCase {
|
|||||||
XCTAssertEqual(collection1.chunks(ofCount: 3).count, 4)
|
XCTAssertEqual(collection1.chunks(ofCount: 3).count, 4)
|
||||||
XCTAssertEqual(collection1.chunks(ofCount: 5).count, 2)
|
XCTAssertEqual(collection1.chunks(ofCount: 5).count, 2)
|
||||||
XCTAssertEqual(collection1.chunks(ofCount: 11).count, 1)
|
XCTAssertEqual(collection1.chunks(ofCount: 11).count, 1)
|
||||||
|
|
||||||
let collection2 = (1...50).map { $0 }
|
let collection2 = (1...50).map { $0 }
|
||||||
XCTAssertEqual(collection2.chunks(ofCount: 9).count, 6)
|
XCTAssertEqual(collection2.chunks(ofCount: 9).count, 6)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testEmptyChunksOfCountTraversal() {
|
func testEmptyChunksOfCountTraversal() {
|
||||||
let emptyChunks = [Int]().chunks(ofCount: 1)
|
let emptyChunks = [Int]().chunks(ofCount: 1)
|
||||||
|
|
||||||
IndexValidator().validate(emptyChunks, expectedCount: 0)
|
validateIndexTraversals(emptyChunks)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testChunksOfCountTraversal() {
|
func testChunksOfCountTraversal() {
|
||||||
let validator = IndexValidator<ChunksOfCountCollection<ClosedRange<Int>>>()
|
for i in 1..<10 {
|
||||||
|
let collection = (1...50).map { $0 }
|
||||||
for i in 1...10 {
|
let chunks = collection.chunks(ofCount: i)
|
||||||
let range = 1...50
|
|
||||||
let chunks = range.chunks(ofCount: i)
|
validateIndexTraversals(chunks)
|
||||||
validator.validate(
|
|
||||||
chunks,
|
|
||||||
expectedCount: range.count / i + (range.count % i).signum())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,113 +9,131 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
|
||||||
import Algorithms
|
import Algorithms
|
||||||
|
import XCTest
|
||||||
|
|
||||||
final class CombinationsTests: XCTestCase {
|
final class CombinationsTests: XCTestCase {
|
||||||
func testCount() {
|
func testCount() {
|
||||||
let c = "ABCD"
|
let c = "ABCD"
|
||||||
|
|
||||||
let c0 = c.combinations(ofCount: 0).count
|
let c0 = c.combinations(ofCount: 0).count
|
||||||
XCTAssertEqual(c0, 1)
|
XCTAssertEqual(c0, 1)
|
||||||
|
|
||||||
let c1 = c.combinations(ofCount: 1).count
|
let c1 = c.combinations(ofCount: 1).count
|
||||||
XCTAssertEqual(c1, 4)
|
XCTAssertEqual(c1, 4)
|
||||||
|
|
||||||
let c2 = c.combinations(ofCount: 2).count
|
let c2 = c.combinations(ofCount: 2).count
|
||||||
XCTAssertEqual(c2, 6)
|
XCTAssertEqual(c2, 6)
|
||||||
|
|
||||||
let c3 = c.combinations(ofCount: 3).count
|
let c3 = c.combinations(ofCount: 3).count
|
||||||
XCTAssertEqual(c3, 4)
|
XCTAssertEqual(c3, 4)
|
||||||
|
|
||||||
let c4 = c.combinations(ofCount: 4).count
|
let c4 = c.combinations(ofCount: 4).count
|
||||||
XCTAssertEqual(c4, 1)
|
XCTAssertEqual(c4, 1)
|
||||||
|
|
||||||
let c5 = c.combinations(ofCount: 0...0).count
|
let c5 = c.combinations(ofCount: 0...0).count
|
||||||
XCTAssertEqual(c5, 1)
|
XCTAssertEqual(c5, 1)
|
||||||
|
|
||||||
let c6 = c.combinations(ofCount: 1...1).count
|
let c6 = c.combinations(ofCount: 1...1).count
|
||||||
XCTAssertEqual(c6, 4)
|
XCTAssertEqual(c6, 4)
|
||||||
|
|
||||||
let c7 = c.combinations(ofCount: 1...2).count
|
let c7 = c.combinations(ofCount: 1...2).count
|
||||||
XCTAssertEqual(c7, 10)
|
XCTAssertEqual(c7, 10)
|
||||||
|
|
||||||
let c8 = c.combinations(ofCount: 1...3).count
|
let c8 = c.combinations(ofCount: 1...3).count
|
||||||
XCTAssertEqual(c8, 14)
|
XCTAssertEqual(c8, 14)
|
||||||
|
|
||||||
let c9 = c.combinations(ofCount: 2...4).count
|
let c9 = c.combinations(ofCount: 2...4).count
|
||||||
XCTAssertEqual(c9, 11)
|
XCTAssertEqual(c9, 11)
|
||||||
|
|
||||||
// `k` greater than element count results in same number of combinations
|
// `k` greater than element count results in same number of combinations
|
||||||
let c10 = c.combinations(ofCount: 3...10).count
|
let c10 = c.combinations(ofCount: 3...10).count
|
||||||
XCTAssertEqual(c10, 5)
|
XCTAssertEqual(c10, 5)
|
||||||
|
|
||||||
// `k` greater than element count results in same number of combinations
|
// `k` greater than element count results in same number of combinations
|
||||||
let c11 = c.combinations(ofCount: 4...10).count
|
let c11 = c.combinations(ofCount: 4...10).count
|
||||||
XCTAssertEqual(c11, 1)
|
XCTAssertEqual(c11, 1)
|
||||||
|
|
||||||
// `k` entirely greater than element count results in no combinations
|
// `k` entirely greater than element count results in no combinations
|
||||||
let c12 = c.combinations(ofCount: 5...10).count
|
let c12 = c.combinations(ofCount: 5...10).count
|
||||||
XCTAssertEqual(c12, 0)
|
XCTAssertEqual(c12, 0)
|
||||||
|
|
||||||
let c13 = c.combinations(ofCount: 0...).count
|
let c13 = c.combinations(ofCount: 0...).count
|
||||||
XCTAssertEqual(c13, 16)
|
XCTAssertEqual(c13, 16)
|
||||||
|
|
||||||
let c14 = c.combinations(ofCount: ...3).count
|
let c14 = c.combinations(ofCount: ...3).count
|
||||||
XCTAssertEqual(c14, 15)
|
XCTAssertEqual(c14, 15)
|
||||||
|
|
||||||
let c15 = c.combinations(ofCount: 0...).count
|
let c15 = c.combinations(ofCount: 0...).count
|
||||||
XCTAssertEqual(c15, 16)
|
XCTAssertEqual(c15, 16)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testCombinations() {
|
func testCombinations() {
|
||||||
let c = "ABCD"
|
let c = "ABCD"
|
||||||
|
|
||||||
let c1 = c.combinations(ofCount: 1)
|
let c1 = c.combinations(ofCount: 1)
|
||||||
XCTAssertEqual(["A", "B", "C", "D"], c1.map { String($0) })
|
XCTAssertEqual(["A", "B", "C", "D"], c1.map { String($0) })
|
||||||
|
|
||||||
let c2 = c.combinations(ofCount: 2)
|
let c2 = c.combinations(ofCount: 2)
|
||||||
XCTAssertEqual(["AB", "AC", "AD", "BC", "BD", "CD"], c2.map { String($0) })
|
XCTAssertEqual(["AB", "AC", "AD", "BC", "BD", "CD"], c2.map { String($0) })
|
||||||
|
|
||||||
let c3 = c.combinations(ofCount: 3)
|
let c3 = c.combinations(ofCount: 3)
|
||||||
XCTAssertEqual(["ABC", "ABD", "ACD", "BCD"], c3.map { String($0) })
|
XCTAssertEqual(["ABC", "ABD", "ACD", "BCD"], c3.map { String($0) })
|
||||||
|
|
||||||
let c4 = c.combinations(ofCount: 4)
|
let c4 = c.combinations(ofCount: 4)
|
||||||
XCTAssertEqual(["ABCD"], c4.map { String($0) })
|
XCTAssertEqual(["ABCD"], c4.map { String($0) })
|
||||||
|
|
||||||
let c5 = c.combinations(ofCount: 2...4)
|
let c5 = c.combinations(ofCount: 2...4)
|
||||||
XCTAssertEqual(["AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c5.map { String($0) })
|
XCTAssertEqual(
|
||||||
|
["AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"],
|
||||||
|
c5.map { String($0) })
|
||||||
|
|
||||||
let c6 = c.combinations(ofCount: 0...4)
|
let c6 = c.combinations(ofCount: 0...4)
|
||||||
XCTAssertEqual(["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c6.map { String($0) })
|
XCTAssertEqual(
|
||||||
|
[
|
||||||
|
"", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD",
|
||||||
|
"ABCD",
|
||||||
|
], c6.map { String($0) })
|
||||||
|
|
||||||
let c7 = c.combinations(ofCount: 0...)
|
let c7 = c.combinations(ofCount: 0...)
|
||||||
XCTAssertEqual(["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c7.map { String($0) })
|
XCTAssertEqual(
|
||||||
|
[
|
||||||
|
"", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD",
|
||||||
|
"ABCD",
|
||||||
|
], c7.map { String($0) })
|
||||||
|
|
||||||
let c8 = c.combinations(ofCount: ...4)
|
let c8 = c.combinations(ofCount: ...4)
|
||||||
XCTAssertEqual(["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c8.map { String($0) })
|
XCTAssertEqual(
|
||||||
|
[
|
||||||
|
"", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD",
|
||||||
|
"ABCD",
|
||||||
|
], c8.map { String($0) })
|
||||||
|
|
||||||
let c9 = c.combinations(ofCount: ...3)
|
let c9 = c.combinations(ofCount: ...3)
|
||||||
XCTAssertEqual(["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD"], c9.map { String($0) })
|
XCTAssertEqual(
|
||||||
|
["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD"],
|
||||||
|
c9.map { String($0) })
|
||||||
|
|
||||||
let c10 = c.combinations(ofCount: 1...)
|
let c10 = c.combinations(ofCount: 1...)
|
||||||
XCTAssertEqual(["A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c10.map { String($0) })
|
XCTAssertEqual(
|
||||||
|
["A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"],
|
||||||
|
c10.map { String($0) })
|
||||||
}
|
}
|
||||||
|
|
||||||
func testEmpty() {
|
func testEmpty() {
|
||||||
// `k == 0` results in one zero-length combination
|
// `k == 0` results in one zero-length combination
|
||||||
XCTAssertEqualSequences([[]], "".combinations(ofCount: 0))
|
XCTAssertEqualSequences([[]], "".combinations(ofCount: 0))
|
||||||
XCTAssertEqualSequences([[]], "".combinations(ofCount: 0...0))
|
XCTAssertEqualSequences([[]], "".combinations(ofCount: 0...0))
|
||||||
XCTAssertEqualSequences([[]], "ABCD".combinations(ofCount: 0))
|
XCTAssertEqualSequences([[]], "ABCD".combinations(ofCount: 0))
|
||||||
XCTAssertEqualSequences([[]], "ABCD".combinations(ofCount: 0...0))
|
XCTAssertEqualSequences([[]], "ABCD".combinations(ofCount: 0...0))
|
||||||
|
|
||||||
// `k` greater than element count results in zero combinations
|
// `k` greater than element count results in zero combinations
|
||||||
XCTAssertEqualSequences([], "".combinations(ofCount: 5))
|
XCTAssertEqualSequences([], "".combinations(ofCount: 5))
|
||||||
XCTAssertEqualSequences([], "".combinations(ofCount: 5...10))
|
XCTAssertEqualSequences([], "".combinations(ofCount: 5...10))
|
||||||
XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5))
|
XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5))
|
||||||
XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5...10))
|
XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5...10))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testCombinationsLazy() {
|
func testCombinationsLazy() {
|
||||||
XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1))
|
XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1))
|
||||||
XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1...3))
|
XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1...3))
|
||||||
|
|||||||
@@ -9,16 +9,16 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
|
||||||
import Algorithms
|
import Algorithms
|
||||||
|
import XCTest
|
||||||
|
|
||||||
final class CompactedTests: XCTestCase {
|
final class CompactedTests: XCTestCase {
|
||||||
|
|
||||||
let tests: [[Int?]] =
|
let tests: [[Int?]] =
|
||||||
[nil, nil, nil, 0, 1, 2]
|
[nil, nil, nil, 0, 1, 2]
|
||||||
.uniquePermutations(ofCount: 0...)
|
.uniquePermutations(ofCount: 0...)
|
||||||
.map(Array.init)
|
.map(Array.init)
|
||||||
|
|
||||||
func testCompactedCompacted() {
|
func testCompactedCompacted() {
|
||||||
for collection in self.tests {
|
for collection in self.tests {
|
||||||
let seq = AnySequence(collection)
|
let seq = AnySequence(collection)
|
||||||
@@ -31,15 +31,15 @@ final class CompactedTests: XCTestCase {
|
|||||||
|
|
||||||
func testCompactedBidirectionalCollection() {
|
func testCompactedBidirectionalCollection() {
|
||||||
for array in self.tests {
|
for array in self.tests {
|
||||||
XCTAssertEqualSequences(array.compactMap({ $0 }).reversed(),
|
XCTAssertEqualSequences(
|
||||||
array.compacted().reversed())
|
array.compactMap({ $0 }).reversed(),
|
||||||
|
array.compacted().reversed())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func testCollectionTraversals() {
|
func testCollectionTraversals() {
|
||||||
let validator = IndexValidator<CompactedCollection<[Int?], Int>>()
|
|
||||||
for array in self.tests {
|
for array in self.tests {
|
||||||
validator.validate(array.compacted())
|
validateIndexTraversals(array.compacted())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,8 +9,8 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
|
||||||
import Algorithms
|
import Algorithms
|
||||||
|
import XCTest
|
||||||
|
|
||||||
final class CycleTests: XCTestCase {
|
final class CycleTests: XCTestCase {
|
||||||
func testCycle() {
|
func testCycle() {
|
||||||
@@ -73,8 +73,9 @@ final class CycleTests: XCTestCase {
|
|||||||
nextIndex = cycle.index(nextIndex, offsetBy: 2, limitedBy: cycle.endIndex)!
|
nextIndex = cycle.index(nextIndex, offsetBy: 2, limitedBy: cycle.endIndex)!
|
||||||
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 8)
|
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 8)
|
||||||
|
|
||||||
let outOfBounds = cycle.index(nextIndex, offsetBy: 1,
|
let outOfBounds = cycle.index(
|
||||||
limitedBy: cycle.endIndex)
|
nextIndex, offsetBy: 1,
|
||||||
|
limitedBy: cycle.endIndex)
|
||||||
XCTAssertNil(outOfBounds)
|
XCTAssertNil(outOfBounds)
|
||||||
|
|
||||||
let previousIndex = cycle.index(before: nextIndex)
|
let previousIndex = cycle.index(before: nextIndex)
|
||||||
|
|||||||
@@ -9,8 +9,8 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
|
||||||
import Algorithms
|
import Algorithms
|
||||||
|
import XCTest
|
||||||
|
|
||||||
final class FirstNonNilTests: XCTestCase {
|
final class FirstNonNilTests: XCTestCase {
|
||||||
func testFirstNonNil() {
|
func testFirstNonNil() {
|
||||||
|
|||||||
@@ -9,8 +9,8 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
|
||||||
import Algorithms
|
import Algorithms
|
||||||
|
import XCTest
|
||||||
|
|
||||||
final class IndexedTests: XCTestCase {
|
final class IndexedTests: XCTestCase {
|
||||||
func testIndexed() {
|
func testIndexed() {
|
||||||
@@ -27,7 +27,7 @@ final class IndexedTests: XCTestCase {
|
|||||||
let indexOfI = si.last(where: { $0.element == "I" })!.index
|
let indexOfI = si.last(where: { $0.element == "I" })!.index
|
||||||
XCTAssertEqual("I", s[indexOfI])
|
XCTAssertEqual("I", s[indexOfI])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testIndexedLazy() {
|
func testIndexedLazy() {
|
||||||
XCTAssertLazyCollection("ABCD".lazy.indexed())
|
XCTAssertLazyCollection("ABCD".lazy.indexed())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,13 +9,13 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
|
import Algorithms
|
||||||
import XCTest
|
import XCTest
|
||||||
@testable import Algorithms
|
|
||||||
|
|
||||||
final class IntersperseTests: XCTestCase {
|
final class IntersperseTests: XCTestCase {
|
||||||
func testSequence() {
|
func testSequence() {
|
||||||
let interspersed = (1...).prefix(5).interspersed(with: 0)
|
let interspersed = (1...).prefix(5).interspersed(with: 0)
|
||||||
XCTAssertEqualSequences(interspersed, [1,0,2,0,3,0,4,0,5])
|
XCTAssertEqualSequences(interspersed, [1, 0, 2, 0, 3, 0, 4, 0, 5])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testSequenceEmpty() {
|
func testSequenceEmpty() {
|
||||||
@@ -26,78 +26,40 @@ final class IntersperseTests: XCTestCase {
|
|||||||
func testString() {
|
func testString() {
|
||||||
let interspersed = "ABCDE".interspersed(with: "-")
|
let interspersed = "ABCDE".interspersed(with: "-")
|
||||||
XCTAssertEqualSequences(interspersed, "A-B-C-D-E")
|
XCTAssertEqualSequences(interspersed, "A-B-C-D-E")
|
||||||
|
validateIndexTraversals(interspersed)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testStringEmpty() {
|
func testStringEmpty() {
|
||||||
let interspersed = "".interspersed(with: "-")
|
let interspersed = "".interspersed(with: "-")
|
||||||
XCTAssertEqualSequences(interspersed, "")
|
XCTAssertEqualSequences(interspersed, "")
|
||||||
|
validateIndexTraversals(interspersed)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testArray() {
|
func testArray() {
|
||||||
let interspersed = [1,2,3,4].interspersed(with: 0)
|
let interspersed = [1, 2, 3, 4].interspersed(with: 0)
|
||||||
XCTAssertEqualSequences(interspersed, [1,0,2,0,3,0,4])
|
XCTAssertEqualSequences(interspersed, [1, 0, 2, 0, 3, 0, 4])
|
||||||
|
validateIndexTraversals(interspersed)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testArrayEmpty() {
|
func testArrayEmpty() {
|
||||||
let interspersed = [].interspersed(with: 0)
|
let interspersed = [].interspersed(with: 0)
|
||||||
XCTAssertEqualSequences(interspersed, [])
|
XCTAssertEqualSequences(interspersed, [])
|
||||||
|
validateIndexTraversals(interspersed)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testCollection() {
|
func testCollection() {
|
||||||
let interspersed = ["A","B","C","D"].interspersed(with: "-")
|
let interspersed = ["A", "B", "C", "D"].interspersed(with: "-")
|
||||||
XCTAssertEqual(interspersed.count, 7)
|
XCTAssertEqual(interspersed.count, 7)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBidirectionalCollection() {
|
func testBidirectionalCollection() {
|
||||||
let reversed = "ABCDE".interspersed(with: "-").reversed()
|
let reversed = "ABCDE".interspersed(with: "-").reversed()
|
||||||
XCTAssertEqualSequences(reversed, "E-D-C-B-A")
|
XCTAssertEqualSequences(reversed, "E-D-C-B-A")
|
||||||
}
|
validateIndexTraversals(reversed)
|
||||||
|
|
||||||
func testIndexTraversals() {
|
|
||||||
let validator = IndexValidator<InterspersedSequence<String>>()
|
|
||||||
validator.validate("".interspersed(with: "-"), expectedCount: 0)
|
|
||||||
validator.validate("A".interspersed(with: "-"), expectedCount: 1)
|
|
||||||
validator.validate("AB".interspersed(with: "-"), expectedCount: 3)
|
|
||||||
validator.validate("ABCDE".interspersed(with: "-"), expectedCount: 9)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func testIntersperseLazy() {
|
func testIntersperseLazy() {
|
||||||
XCTAssertLazySequence((1...).prefix(0).lazy.interspersed(with: 0))
|
XCTAssertLazySequence((1...).prefix(0).lazy.interspersed(with: 0))
|
||||||
XCTAssertLazyCollection("ABCDE".lazy.interspersed(with: "-"))
|
XCTAssertLazyCollection("ABCDE".lazy.interspersed(with: "-"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testInterspersedMap() {
|
|
||||||
XCTAssertEqualSequences(
|
|
||||||
(0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
|
|
||||||
[])
|
|
||||||
|
|
||||||
XCTAssertEqualSequences(
|
|
||||||
(0..<1).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
|
|
||||||
[0])
|
|
||||||
|
|
||||||
XCTAssertEqualSequences(
|
|
||||||
(0..<5).lazy.interspersedMap({ $0 }, with: { $0 + $1 + 100 }),
|
|
||||||
[0, 101, 1, 103, 2, 105, 3, 107, 4])
|
|
||||||
}
|
|
||||||
|
|
||||||
func testInterspersedMapLazy() {
|
|
||||||
XCTAssertLazySequence(AnySequence([]).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }))
|
|
||||||
XCTAssertLazyCollection((0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }))
|
|
||||||
}
|
|
||||||
|
|
||||||
func testInterspersedMapIndexTraversals() {
|
|
||||||
let validator = IndexValidator<InterspersedMapSequence<Range<Int>, Int>>()
|
|
||||||
validator.validate(
|
|
||||||
(0..<0).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }),
|
|
||||||
expectedCount: 0)
|
|
||||||
validator.validate(
|
|
||||||
(0..<1).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }),
|
|
||||||
expectedCount: 1)
|
|
||||||
validator.validate(
|
|
||||||
(0..<2).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }),
|
|
||||||
expectedCount: 3)
|
|
||||||
validator.validate(
|
|
||||||
(0..<5).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }),
|
|
||||||
expectedCount: 9)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,132 +0,0 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
|
||||||
//
|
|
||||||
// This source file is part of the Swift Algorithms open source project
|
|
||||||
//
|
|
||||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
|
||||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
|
||||||
//
|
|
||||||
// See https://swift.org/LICENSE.txt for license information
|
|
||||||
//
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
|
|
||||||
import XCTest
|
|
||||||
@testable import Algorithms
|
|
||||||
|
|
||||||
final class JoinedTests: XCTestCase {
|
|
||||||
let stringArrays = [
|
|
||||||
[],
|
|
||||||
[""],
|
|
||||||
["", ""],
|
|
||||||
["foo"],
|
|
||||||
["foo", "bar"],
|
|
||||||
["", "", "foo", "", "bar", "baz", ""],
|
|
||||||
]
|
|
||||||
|
|
||||||
func testJoined() {
|
|
||||||
let expected = ["", "", "", "foo", "foobar", "foobarbaz"]
|
|
||||||
|
|
||||||
for (strings, expected) in zip(stringArrays, expected) {
|
|
||||||
// regular sequence
|
|
||||||
XCTAssertEqualSequences(AnySequence(strings).joined(), expected)
|
|
||||||
|
|
||||||
// lazy sequence
|
|
||||||
XCTAssertEqualSequences(AnySequence(strings).lazy.joined(), expected)
|
|
||||||
|
|
||||||
// regular collection
|
|
||||||
XCTAssertEqualSequences(strings.joined(), expected)
|
|
||||||
|
|
||||||
// lazy collection
|
|
||||||
XCTAssertEqualSequences(strings.lazy.joined() as FlattenCollection, expected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testJoinedByElement() {
|
|
||||||
let separator: Character = " "
|
|
||||||
let expected = ["", "", " ", "foo", "foo bar", " foo bar baz "]
|
|
||||||
|
|
||||||
for (strings, expected) in zip(stringArrays, expected) {
|
|
||||||
XCTAssertEqualSequences(AnySequence(strings).joined(by: separator), expected)
|
|
||||||
XCTAssertEqualSequences(AnySequence(strings).lazy.joined(by: separator), expected)
|
|
||||||
XCTAssertEqualSequences(strings.joined(by: separator), expected)
|
|
||||||
XCTAssertEqualSequences(strings.lazy.joined(by: separator), expected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testJoinedBySequence() {
|
|
||||||
let separator = ", "
|
|
||||||
let expected = ["", "", ", ", "foo", "foo, bar", ", , foo, , bar, baz, "]
|
|
||||||
|
|
||||||
for (strings, expected) in zip(stringArrays, expected) {
|
|
||||||
XCTAssertEqualSequences(AnySequence(strings).joined(by: separator), expected)
|
|
||||||
XCTAssertEqualSequences(AnySequence(strings).lazy.joined(by: separator), expected)
|
|
||||||
XCTAssertEqualSequences(strings.joined(by: separator), expected)
|
|
||||||
XCTAssertEqualSequences(strings.lazy.joined(by: separator), expected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testJoinedByElementClosure() {
|
|
||||||
let separator = { (left: String, right: String) -> Character in
|
|
||||||
left.isEmpty || right.isEmpty ? " " : "-"
|
|
||||||
}
|
|
||||||
|
|
||||||
let expected = ["", "", " ", "foo", "foo-bar", " foo bar-baz "]
|
|
||||||
|
|
||||||
for (strings, expected) in zip(stringArrays, expected) {
|
|
||||||
XCTAssertEqualSequences(AnySequence(strings).joined(by: separator), expected)
|
|
||||||
XCTAssertEqualSequences(AnySequence(strings).lazy.joined(by: separator), expected)
|
|
||||||
XCTAssertEqualSequences(strings.joined(by: separator), expected)
|
|
||||||
XCTAssertEqualSequences(strings.lazy.joined(by: separator), expected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testJoinedBySequenceClosure() {
|
|
||||||
let separator = { (left: String, right: String) in
|
|
||||||
"(\(left.count), \(right.count))"
|
|
||||||
}
|
|
||||||
|
|
||||||
let expected = [
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"(0, 0)",
|
|
||||||
"foo",
|
|
||||||
"foo(3, 3)bar",
|
|
||||||
"(0, 0)(0, 3)foo(3, 0)(0, 3)bar(3, 3)baz(3, 0)"
|
|
||||||
]
|
|
||||||
|
|
||||||
for (strings, expected) in zip(stringArrays, expected) {
|
|
||||||
XCTAssertEqualSequences(AnySequence(strings).joined(by: separator), expected)
|
|
||||||
XCTAssertEqualSequences(AnySequence(strings).lazy.joined(by: separator), expected)
|
|
||||||
XCTAssertEqualSequences(strings.joined(by: separator), expected)
|
|
||||||
XCTAssertEqualSequences(strings.lazy.joined(by: separator), expected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testJoinedLazy() {
|
|
||||||
XCTAssertLazySequence(AnySequence([[1], [2]]).lazy.joined())
|
|
||||||
XCTAssertLazySequence(AnySequence([[1], [2]]).lazy.joined(by: 1))
|
|
||||||
XCTAssertLazySequence(AnySequence([[1], [2]]).lazy.joined(by: { _, _ in 1 }))
|
|
||||||
XCTAssertLazyCollection([[1], [2]].lazy.joined())
|
|
||||||
XCTAssertLazyCollection([[1], [2]].lazy.joined(by: 1))
|
|
||||||
XCTAssertLazyCollection([[1], [2]].lazy.joined(by: { _, _ in 1 }))
|
|
||||||
}
|
|
||||||
|
|
||||||
func testJoinedIndexTraversals() {
|
|
||||||
let validator = IndexValidator<FlattenCollection<[String]>>()
|
|
||||||
|
|
||||||
// the last test case takes too long to run
|
|
||||||
for strings in stringArrays.dropLast() {
|
|
||||||
validator.validate(strings.joined() as FlattenCollection)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testJoinedByIndexTraversals() {
|
|
||||||
let validator1 = IndexValidator<JoinedByCollection<[String], String>>()
|
|
||||||
let validator2 = IndexValidator<JoinedByClosureCollection<[String], String>>()
|
|
||||||
|
|
||||||
// the last test case takes too long to run
|
|
||||||
for (strings, separator) in product(stringArrays.dropLast(), ["", " ", ", "]) {
|
|
||||||
validator1.validate(strings.joined(by: separator))
|
|
||||||
validator2.validate(strings.lazy.joined(by: { _, _ in separator }))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+3
-3
@@ -13,10 +13,10 @@ import Algorithms
|
|||||||
import XCTest
|
import XCTest
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// Tests for `SplitSequence` and `SplitCollection`
|
// Tests for `LazySplitSequence` and `LazySplitCollection`
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
final class SplitTests: XCTestCase {
|
final class LazySplitTests: XCTestCase {
|
||||||
func testEmpty() {
|
func testEmpty() {
|
||||||
Validator(
|
Validator(
|
||||||
subject: [],
|
subject: [],
|
||||||
@@ -112,7 +112,7 @@ final class SplitTests: XCTestCase {
|
|||||||
|
|
||||||
func testAllEEES() {
|
func testAllEEES() {
|
||||||
let permutations = [
|
let permutations = [
|
||||||
[1, 1, 1, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1]
|
[1, 1, 1, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1],
|
||||||
]
|
]
|
||||||
|
|
||||||
for permutation in permutations {
|
for permutation in permutations {
|
||||||
@@ -9,8 +9,8 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
|
||||||
import Algorithms
|
import Algorithms
|
||||||
|
import XCTest
|
||||||
|
|
||||||
final class SortedPrefixTests: XCTestCase {
|
final class SortedPrefixTests: XCTestCase {
|
||||||
func testMinCount() {
|
func testMinCount() {
|
||||||
@@ -25,7 +25,7 @@ final class SortedPrefixTests: XCTestCase {
|
|||||||
.max(count: 5, sortedBy: { $0.element < $1.element })
|
.max(count: 5, sortedBy: { $0.element < $1.element })
|
||||||
XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
|
XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testMaxCount() {
|
func testMaxCount() {
|
||||||
// Replacement at start and end
|
// Replacement at start and end
|
||||||
let input = [0, 11, 12, 1, 13, 2, 14, 3, 4, 5, 6, 7, 8, 9, 10]
|
let input = [0, 11, 12, 1, 13, 2, 14, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||||
@@ -38,12 +38,12 @@ final class SortedPrefixTests: XCTestCase {
|
|||||||
.max(count: 5, sortedBy: { $0.element < $1.element })
|
.max(count: 5, sortedBy: { $0.element < $1.element })
|
||||||
XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
|
XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testEmpty() {
|
func testEmpty() {
|
||||||
let array = [Int]()
|
let array = [Int]()
|
||||||
XCTAssertEqual(array.min(count: 0), [])
|
XCTAssertEqual(array.min(count: 0), [])
|
||||||
XCTAssertEqual(array.min(count: 100), [])
|
XCTAssertEqual(array.min(count: 100), [])
|
||||||
|
|
||||||
XCTAssertEqual(array.max(count: 0), [])
|
XCTAssertEqual(array.max(count: 0), [])
|
||||||
XCTAssertEqual(array.max(count: 100), [])
|
XCTAssertEqual(array.max(count: 100), [])
|
||||||
}
|
}
|
||||||
@@ -51,14 +51,14 @@ final class SortedPrefixTests: XCTestCase {
|
|||||||
func testMinMaxSequences() {
|
func testMinMaxSequences() {
|
||||||
let input = (1...100).shuffled().interspersed(with: 50)
|
let input = (1...100).shuffled().interspersed(with: 50)
|
||||||
let seq = AnySequence(input)
|
let seq = AnySequence(input)
|
||||||
|
|
||||||
XCTAssertEqualSequences(seq.min(count: 0), [])
|
XCTAssertEqualSequences(seq.min(count: 0), [])
|
||||||
XCTAssertEqualSequences(seq.min(count: 5), 1...5)
|
XCTAssertEqualSequences(seq.min(count: 5), 1...5)
|
||||||
|
|
||||||
XCTAssertEqualSequences(seq.max(count: 0), [])
|
XCTAssertEqualSequences(seq.max(count: 0), [])
|
||||||
XCTAssertEqualSequences(seq.max(count: 5), 96...100)
|
XCTAssertEqualSequences(seq.max(count: 5), 96...100)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testSortedPrefixComparable() {
|
func testSortedPrefixComparable() {
|
||||||
let array: [Int] = [20, 1, 4, 70, 100, 2, 3, 7, 90]
|
let array: [Int] = [20, 1, 4, 70, 100, 2, 3, 7, 90]
|
||||||
|
|
||||||
@@ -67,7 +67,7 @@ final class SortedPrefixTests: XCTestCase {
|
|||||||
XCTAssertEqualSequences(array.min(count: 5), array.sorted().prefix(5))
|
XCTAssertEqualSequences(array.min(count: 5), array.sorted().prefix(5))
|
||||||
XCTAssertEqual(array.min(count: 10), array.sorted())
|
XCTAssertEqual(array.min(count: 10), array.sorted())
|
||||||
}
|
}
|
||||||
|
|
||||||
func testMinMaxWithHugeCount() {
|
func testMinMaxWithHugeCount() {
|
||||||
XCTAssertEqual([4, 2, 1, 3].min(count: .max), [1, 2, 3, 4])
|
XCTAssertEqual([4, 2, 1, 3].min(count: .max), [1, 2, 3, 4])
|
||||||
XCTAssertEqual([4, 2, 1, 3].max(count: .max), [1, 2, 3, 4])
|
XCTAssertEqual([4, 2, 1, 3].max(count: .max), [1, 2, 3, 4])
|
||||||
@@ -130,10 +130,10 @@ final class SortedPrefixTests: XCTestCase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func testStability() {
|
func testStability() {
|
||||||
assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 3)
|
assertStability([1, 1, 1, 2, 5, 7, 3, 6, 2, 5, 7, 3, 6], withCount: 3)
|
||||||
assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 6)
|
assertStability([1, 1, 1, 2, 5, 7, 3, 6, 2, 5, 7, 3, 6], withCount: 6)
|
||||||
assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 20)
|
assertStability([1, 1, 1, 2, 5, 7, 3, 6, 2, 5, 7, 3, 6], withCount: 20)
|
||||||
assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 1000)
|
assertStability([1, 1, 1, 2, 5, 7, 3, 6, 2, 5, 7, 3, 6], withCount: 1000)
|
||||||
assertStability(Array(repeating: 0, count: 100), withCount: 0)
|
assertStability(Array(repeating: 0, count: 100), withCount: 0)
|
||||||
assertStability(Array(repeating: 0, count: 100), withCount: 1)
|
assertStability(Array(repeating: 0, count: 100), withCount: 1)
|
||||||
assertStability(Array(repeating: 0, count: 100), withCount: 2)
|
assertStability(Array(repeating: 0, count: 100), withCount: 2)
|
||||||
@@ -144,19 +144,19 @@ final class SortedPrefixTests: XCTestCase {
|
|||||||
assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 5)
|
assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 5)
|
||||||
assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 20)
|
assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 20)
|
||||||
assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 50)
|
assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 50)
|
||||||
assertStability([0,0], withCount: 1)
|
assertStability([0, 0], withCount: 1)
|
||||||
assertStability([0,0], withCount: 2)
|
assertStability([0, 0], withCount: 2)
|
||||||
assertStability([0,1,0,1,0,1], withCount: 2)
|
assertStability([0, 1, 0, 1, 0, 1], withCount: 2)
|
||||||
assertStability([0,1,0,1,0,1], withCount: 6)
|
assertStability([0, 1, 0, 1, 0, 1], withCount: 6)
|
||||||
assertStability([0,0,0,1,1,1], withCount: 1)
|
assertStability([0, 0, 0, 1, 1, 1], withCount: 1)
|
||||||
assertStability([0,0,0,1,1,1], withCount: 3)
|
assertStability([0, 0, 0, 1, 1, 1], withCount: 3)
|
||||||
assertStability([0,0,0,1,1,1], withCount: 4)
|
assertStability([0, 0, 0, 1, 1, 1], withCount: 4)
|
||||||
assertStability([0,0,0,1,1,1], withCount: 6)
|
assertStability([0, 0, 0, 1, 1, 1], withCount: 6)
|
||||||
assertStability([1,1,1,0,0,0], withCount: 1)
|
assertStability([1, 1, 1, 0, 0, 0], withCount: 1)
|
||||||
assertStability([1,1,1,0,0,0], withCount: 3)
|
assertStability([1, 1, 1, 0, 0, 0], withCount: 3)
|
||||||
assertStability([1,1,1,0,0,0], withCount: 4)
|
assertStability([1, 1, 1, 0, 0, 0], withCount: 4)
|
||||||
assertStability([1,1,1,0,0,0], withCount: 6)
|
assertStability([1, 1, 1, 0, 0, 0], withCount: 6)
|
||||||
assertStability([1,1,1,0,0,0], withCount: 5)
|
assertStability([1, 1, 1, 0, 0, 0], withCount: 5)
|
||||||
}
|
}
|
||||||
|
|
||||||
func assertStability(
|
func assertStability(
|
||||||
@@ -165,19 +165,19 @@ final class SortedPrefixTests: XCTestCase {
|
|||||||
) {
|
) {
|
||||||
func stableOrder(
|
func stableOrder(
|
||||||
a: (offset: Int, element: Int),
|
a: (offset: Int, element: Int),
|
||||||
b: (offset: Int, element: Int)) -> Bool
|
b: (offset: Int, element: Int)
|
||||||
{
|
) -> Bool {
|
||||||
a.element == b.element
|
a.element == b.element
|
||||||
? a.offset < b.offset
|
? a.offset < b.offset
|
||||||
: a.element < b.element
|
: a.element < b.element
|
||||||
}
|
}
|
||||||
|
|
||||||
do {
|
do {
|
||||||
let sorted = actual.enumerated()
|
let sorted = actual.enumerated()
|
||||||
.min(count: count) { $0.element < $1.element }
|
.min(count: count) { $0.element < $1.element }
|
||||||
XCTAssert(sorted.isSorted(by: stableOrder))
|
XCTAssert(sorted.isSorted(by: stableOrder))
|
||||||
}
|
}
|
||||||
|
|
||||||
do {
|
do {
|
||||||
let sorted = actual.enumerated()
|
let sorted = actual.enumerated()
|
||||||
.max(count: count) { $0.element < $1.element }
|
.max(count: count) { $0.element < $1.element }
|
||||||
@@ -185,90 +185,3 @@ final class SortedPrefixTests: XCTestCase {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final class MinAndMaxTests: XCTestCase {
|
|
||||||
/// Confirms that empty sequences yield no results.
|
|
||||||
func testEmpty() {
|
|
||||||
XCTAssertNil(EmptyCollection<Int>().minAndMax())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Confirms the same element is used when there is only one.
|
|
||||||
func testSingleElement() {
|
|
||||||
let result = CollectionOfOne(2).minAndMax()
|
|
||||||
XCTAssertEqual(result?.min, 2)
|
|
||||||
XCTAssertEqual(result?.max, 2)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Confirms the same value is used when all the elements have it.
|
|
||||||
func testSingleValueMultipleElements() {
|
|
||||||
let result = repeatElement(3.3, count: 5).minAndMax()
|
|
||||||
XCTAssertEqual(result?.min, 3.3)
|
|
||||||
XCTAssertEqual(result?.max, 3.3)
|
|
||||||
|
|
||||||
// Even count
|
|
||||||
let result2 = repeatElement("c" as Character, count: 6).minAndMax()
|
|
||||||
XCTAssertEqual(result2?.min, "c")
|
|
||||||
XCTAssertEqual(result2?.max, "c")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Confirms when the minimum value is constantly updated, but the maximum
|
|
||||||
/// never is.
|
|
||||||
func testRampDown() {
|
|
||||||
let result = (1...5).reversed().minAndMax()
|
|
||||||
XCTAssertEqual(result?.min, 1)
|
|
||||||
XCTAssertEqual(result?.max, 5)
|
|
||||||
|
|
||||||
// Even count
|
|
||||||
let result2 = "fedcba".minAndMax()
|
|
||||||
XCTAssertEqual(result2?.min, "a")
|
|
||||||
XCTAssertEqual(result2?.max, "f")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Confirms when the maximum value is constantly updated, but the minimum
|
|
||||||
/// never is.
|
|
||||||
func testRampUp() {
|
|
||||||
let result = (1...5).minAndMax()
|
|
||||||
XCTAssertEqual(result?.min, 1)
|
|
||||||
XCTAssertEqual(result?.max, 5)
|
|
||||||
|
|
||||||
// Even count
|
|
||||||
let result2 = "abcdef".minAndMax()
|
|
||||||
XCTAssertEqual(result2?.min, "a")
|
|
||||||
XCTAssertEqual(result2?.max, "f")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Confirms when the maximum and minimum change during a run.
|
|
||||||
func testUpsAndDowns() {
|
|
||||||
let result = [4, 3, 3, 5, 2, 0, 7, 6].minAndMax()
|
|
||||||
XCTAssertEqual(result?.min, 0)
|
|
||||||
XCTAssertEqual(result?.max, 7)
|
|
||||||
|
|
||||||
// Odd count
|
|
||||||
let result2 = "gfabdec".minAndMax()
|
|
||||||
XCTAssertEqual(result2?.min, "a")
|
|
||||||
XCTAssertEqual(result2?.max, "g")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Confirms that the given predicate is used to find the min/max.
|
|
||||||
func testPredicate() {
|
|
||||||
let result = (1...5).minAndMax(by: >)
|
|
||||||
XCTAssertEqual(result?.min, 5)
|
|
||||||
XCTAssertEqual(result?.max, 1)
|
|
||||||
|
|
||||||
// Odd count
|
|
||||||
let result2 = "gfabdec".minAndMax(by: >)
|
|
||||||
XCTAssertEqual(result2?.min, "g")
|
|
||||||
XCTAssertEqual(result2?.max, "a")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Confirms that the min and max are "stable" as defined for minAndMax.
|
|
||||||
func testStability() {
|
|
||||||
for n in 1...10 {
|
|
||||||
let result = repeatElement(0, count: n)
|
|
||||||
.enumerated()
|
|
||||||
.minAndMax(by: { $0.element < $1.element })
|
|
||||||
XCTAssertEqual(result?.min.offset, 0)
|
|
||||||
XCTAssertEqual(result?.max.offset, n - 1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -9,8 +9,8 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
|
||||||
import Algorithms
|
import Algorithms
|
||||||
|
import XCTest
|
||||||
|
|
||||||
final class PartitionTests: XCTestCase {
|
final class PartitionTests: XCTestCase {
|
||||||
func testStablePartition() {
|
func testStablePartition() {
|
||||||
@@ -60,7 +60,7 @@ final class PartitionTests: XCTestCase {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func testStablePartitionWithSubrange() {
|
func testStablePartitionWithSubrange() {
|
||||||
for length in 10...20 {
|
for length in 10...20 {
|
||||||
let a = Array(0..<length)
|
let a = Array(0..<length)
|
||||||
@@ -72,13 +72,15 @@ final class PartitionTests: XCTestCase {
|
|||||||
let p = b.stablePartition(subrange: partitionRange, by: condition)
|
let p = b.stablePartition(subrange: partitionRange, by: condition)
|
||||||
|
|
||||||
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
||||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
XCTAssertEqualSequences(
|
||||||
XCTAssertEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
||||||
|
XCTAssertEqualSequences(
|
||||||
|
b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func testPartitioningIndex() {
|
func testPartitioningIndex() {
|
||||||
for i in 0..<7 {
|
for i in 0..<7 {
|
||||||
for j in i..<11 {
|
for j in i..<11 {
|
||||||
@@ -91,27 +93,7 @@ final class PartitionTests: XCTestCase {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func testPartitioningIndexWithEmptyInput() {
|
|
||||||
let input: [Int] = []
|
|
||||||
|
|
||||||
let a = input.partitioningIndex(where: { _ in return true })
|
|
||||||
XCTAssertEqual(a, input.startIndex)
|
|
||||||
|
|
||||||
let b = input.partitioningIndex(where: { _ in return false })
|
|
||||||
XCTAssertEqual(b, input.endIndex)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testPartitioningIndexWithOneEmptyPartition() {
|
|
||||||
let input: Range<Int> = (0 ..< 10)
|
|
||||||
|
|
||||||
let a = input.partitioningIndex(where: { $0 > 10 })
|
|
||||||
XCTAssertEqual(a, input.endIndex)
|
|
||||||
|
|
||||||
let b = input.partitioningIndex(where: { $0 >= 0 })
|
|
||||||
XCTAssertEqual(b, input.startIndex)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testPartitionWithSubrangeBidirectionalCollection() {
|
func testPartitionWithSubrangeBidirectionalCollection() {
|
||||||
for length in 10...20 {
|
for length in 10...20 {
|
||||||
let a = Array(0..<length)
|
let a = Array(0..<length)
|
||||||
@@ -121,10 +103,12 @@ final class PartitionTests: XCTestCase {
|
|||||||
let partitionRange = j..<i
|
let partitionRange = j..<i
|
||||||
let condition = { $0 < i - 1 }
|
let condition = { $0 < i - 1 }
|
||||||
let p = b.partition(subrange: partitionRange, by: condition)
|
let p = b.partition(subrange: partitionRange, by: condition)
|
||||||
|
|
||||||
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
||||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
XCTAssertEqualSequences(
|
||||||
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
||||||
|
XCTAssertUnorderedEqualSequences(
|
||||||
|
b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -141,52 +125,20 @@ final class PartitionTests: XCTestCase {
|
|||||||
let condition = { $0 < i - 1 }
|
let condition = { $0 < i - 1 }
|
||||||
let p = b.partition(subrange: partitionRange, by: condition)
|
let p = b.partition(subrange: partitionRange, by: condition)
|
||||||
let bdcp = bdc.partition(subrange: partitionRange, by: condition)
|
let bdcp = bdc.partition(subrange: partitionRange, by: condition)
|
||||||
|
|
||||||
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
||||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
XCTAssertEqualSequences(
|
||||||
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
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.
|
// Must produce the same result as the `BidirectionalCollection` specialized overload.
|
||||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], bdc[partitionRange.lowerBound..<bdcp])
|
XCTAssertEqualSequences(
|
||||||
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], bdc[bdcp..<partitionRange.upperBound])
|
b[partitionRange.lowerBound..<p], bdc[partitionRange.lowerBound..<bdcp])
|
||||||
|
XCTAssertUnorderedEqualSequences(
|
||||||
|
b[p..<partitionRange.upperBound], bdc[bdcp..<partitionRange.upperBound])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func testPartitionedWithEmptyInput() {
|
|
||||||
let input: [Int] = []
|
|
||||||
|
|
||||||
let s0 = input.partitioned(by: { _ in return true })
|
|
||||||
|
|
||||||
XCTAssertTrue(s0.0.isEmpty)
|
|
||||||
XCTAssertTrue(s0.1.isEmpty)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Test the example given in the `partitioned(by:)` documentation
|
|
||||||
func testPartitionedExample() throws {
|
|
||||||
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
|
||||||
let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
|
||||||
XCTAssertEqual(longNames, ["Vivien", "Marlon"])
|
|
||||||
XCTAssertEqual(shortNames, ["Kim", "Karl"])
|
|
||||||
}
|
|
||||||
|
|
||||||
func testPartitionedWithPredicate() throws {
|
|
||||||
let s0 = ["A", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() })
|
|
||||||
let s1 = ["a", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() })
|
|
||||||
let s2 = ["a", "B", "c", "D"].partitioned(by: { $0 == $0.lowercased() })
|
|
||||||
let s3 = ["a", "B", "c", "d"].partitioned(by: { $0 == $0.lowercased() })
|
|
||||||
|
|
||||||
XCTAssertEqual(s0.0, ["A", "B", "C", "D"])
|
|
||||||
XCTAssertEqual(s0.1, [])
|
|
||||||
|
|
||||||
XCTAssertEqual(s1.0, ["B", "C", "D"])
|
|
||||||
XCTAssertEqual(s1.1, ["a"])
|
|
||||||
|
|
||||||
XCTAssertEqual(s2.0, ["B", "D"])
|
|
||||||
XCTAssertEqual(s2.1, ["a", "c"])
|
|
||||||
|
|
||||||
XCTAssertEqual(s3.0, ["B"])
|
|
||||||
XCTAssertEqual(s3.1, ["a", "c", "d"])
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -10,15 +10,16 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
import XCTest
|
||||||
|
|
||||||
@testable import Algorithms
|
@testable import Algorithms
|
||||||
|
|
||||||
final class PermutationsTests: XCTestCase {
|
final class PermutationsTests: XCTestCase {
|
||||||
func testPermutations() {
|
func testPermutations() {
|
||||||
let c = "ABCDE"
|
let c = "ABCDE"
|
||||||
|
|
||||||
func t(count: Int?) {
|
func t(count: Int?) {
|
||||||
let p = c.permutations(ofCount: count)
|
let p = c.permutations(ofCount: count)
|
||||||
|
|
||||||
let count = count ?? c.count
|
let count = count ?? c.count
|
||||||
let permCount = c.count.factorial() / (c.count - count).factorial()
|
let permCount = c.count.factorial() / (c.count - count).factorial()
|
||||||
XCTAssertEqual(permCount, p.count)
|
XCTAssertEqual(permCount, p.count)
|
||||||
@@ -26,20 +27,20 @@ final class PermutationsTests: XCTestCase {
|
|||||||
XCTAssertTrue(p.allSatisfy { $0.count == count })
|
XCTAssertTrue(p.allSatisfy { $0.count == count })
|
||||||
XCTAssertTrue(p.isSorted(by: { $0.lexicographicallyPrecedes($1) }))
|
XCTAssertTrue(p.isSorted(by: { $0.lexicographicallyPrecedes($1) }))
|
||||||
}
|
}
|
||||||
|
|
||||||
func ts<R: RangeExpression>(count: R) where R.Bound == Int {
|
func ts<R: RangeExpression>(count: R) where R.Bound == Int {
|
||||||
let p = count.relative(to: 0 ..< .max)
|
let p = count.relative(to: 0 ..< .max)
|
||||||
.clamped(to: 0 ..< c.count + 1)
|
.clamped(to: 0..<c.count + 1)
|
||||||
.flatMap {
|
.flatMap {
|
||||||
c.permutations(ofCount: $0)
|
c.permutations(ofCount: $0)
|
||||||
}
|
}
|
||||||
|
|
||||||
let p2 = c.permutations(ofCount: count)
|
let p2 = c.permutations(ofCount: count)
|
||||||
|
|
||||||
XCTAssertEqual(p.count, p2.count)
|
XCTAssertEqual(p.count, p2.count)
|
||||||
XCTAssertEqualSequences(p, Array(p2))
|
XCTAssertEqualSequences(p, Array(p2))
|
||||||
}
|
}
|
||||||
|
|
||||||
t(count: 0)
|
t(count: 0)
|
||||||
t(count: 1)
|
t(count: 1)
|
||||||
t(count: 2)
|
t(count: 2)
|
||||||
@@ -47,7 +48,7 @@ final class PermutationsTests: XCTestCase {
|
|||||||
t(count: 4)
|
t(count: 4)
|
||||||
t(count: 5)
|
t(count: 5)
|
||||||
t(count: nil)
|
t(count: nil)
|
||||||
|
|
||||||
ts(count: 0...0)
|
ts(count: 0...0)
|
||||||
ts(count: 1...1)
|
ts(count: 1...1)
|
||||||
ts(count: 0...1)
|
ts(count: 0...1)
|
||||||
@@ -60,7 +61,7 @@ final class PermutationsTests: XCTestCase {
|
|||||||
ts(count: ...4)
|
ts(count: ...4)
|
||||||
ts(count: ...6)
|
ts(count: ...6)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testEmpty() {
|
func testEmpty() {
|
||||||
// `k == 0` results in one zero-length permutation
|
// `k == 0` results in one zero-length permutation
|
||||||
XCTAssertEqual(1, "".permutations().count)
|
XCTAssertEqual(1, "".permutations().count)
|
||||||
@@ -70,7 +71,7 @@ final class PermutationsTests: XCTestCase {
|
|||||||
XCTAssertEqual(Array("".permutations(ofCount: 0)), [[]])
|
XCTAssertEqual(Array("".permutations(ofCount: 0)), [[]])
|
||||||
XCTAssertEqual(Array("ABCD".permutations(ofCount: 0)), [[]])
|
XCTAssertEqual(Array("ABCD".permutations(ofCount: 0)), [[]])
|
||||||
XCTAssertEqual(Array("ABCD".permutations(ofCount: 0...0)), [[]])
|
XCTAssertEqual(Array("ABCD".permutations(ofCount: 0...0)), [[]])
|
||||||
|
|
||||||
// `k` greater than element count results in zero permutations
|
// `k` greater than element count results in zero permutations
|
||||||
XCTAssertEqual(0, "".permutations(ofCount: 5).count)
|
XCTAssertEqual(0, "".permutations(ofCount: 5).count)
|
||||||
XCTAssertEqual(Array("".permutations(ofCount: 5)), [])
|
XCTAssertEqual(Array("".permutations(ofCount: 5)), [])
|
||||||
@@ -79,10 +80,10 @@ final class PermutationsTests: XCTestCase {
|
|||||||
XCTAssertEqual(Array("ABCD".permutations(ofCount: 5..<7)), [])
|
XCTAssertEqual(Array("ABCD".permutations(ofCount: 5..<7)), [])
|
||||||
XCTAssertEqual(Array("ABCD".permutations(ofCount: 5...)), [])
|
XCTAssertEqual(Array("ABCD".permutations(ofCount: 5...)), [])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testNextPermutation() {
|
func testNextPermutation() {
|
||||||
var numbers = Array(1...7)
|
var numbers = Array(1...7)
|
||||||
|
|
||||||
_ = numbers.nextPermutation()
|
_ = numbers.nextPermutation()
|
||||||
XCTAssertEqual([1, 2, 3, 4, 5, 7, 6], numbers)
|
XCTAssertEqual([1, 2, 3, 4, 5, 7, 6], numbers)
|
||||||
_ = numbers.nextPermutation()
|
_ = numbers.nextPermutation()
|
||||||
@@ -95,110 +96,122 @@ final class PermutationsTests: XCTestCase {
|
|||||||
XCTAssertEqual([1, 2, 3, 4, 7, 6, 5], numbers)
|
XCTAssertEqual([1, 2, 3, 4, 7, 6, 5], numbers)
|
||||||
_ = numbers.nextPermutation()
|
_ = numbers.nextPermutation()
|
||||||
XCTAssertEqual([1, 2, 3, 5, 4, 6, 7], numbers)
|
XCTAssertEqual([1, 2, 3, 5, 4, 6, 7], numbers)
|
||||||
|
|
||||||
// Fast-forward to end of permutations.
|
// Fast-forward to end of permutations.
|
||||||
while numbers.nextPermutation() {}
|
while numbers.nextPermutation() {}
|
||||||
XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], numbers)
|
XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], numbers)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testPermutationsLazy() {
|
func testPermutationsLazy() {
|
||||||
XCTAssertLazySequence("ABCD".lazy.permutations(ofCount: 2))
|
XCTAssertLazySequence("ABCD".lazy.permutations(ofCount: 2))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testDocumentationExample1() {
|
func testDocumentationExample1() {
|
||||||
// From Guides/Permutations.md
|
// From Guides/Permutations.md
|
||||||
let numbers = [10, 20, 30]
|
let numbers = [10, 20, 30]
|
||||||
let permutations = numbers.permutations()
|
let permutations = numbers.permutations()
|
||||||
XCTAssertEqualSequences(permutations, [
|
XCTAssertEqualSequences(
|
||||||
[10, 20, 30],
|
permutations,
|
||||||
[10, 30, 20],
|
[
|
||||||
[20, 10, 30],
|
[10, 20, 30],
|
||||||
[20, 30, 10],
|
[10, 30, 20],
|
||||||
[30, 10, 20],
|
[20, 10, 30],
|
||||||
[30, 20, 10],
|
[20, 30, 10],
|
||||||
])
|
[30, 10, 20],
|
||||||
|
[30, 20, 10],
|
||||||
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testDocumentationExample2() {
|
func testDocumentationExample2() {
|
||||||
// From Guides/Permutations.md
|
// From Guides/Permutations.md
|
||||||
let numbers = [10, 20, 30]
|
let numbers = [10, 20, 30]
|
||||||
let permutations = numbers.permutations(ofCount: 2)
|
let permutations = numbers.permutations(ofCount: 2)
|
||||||
XCTAssertEqualSequences(permutations, [
|
XCTAssertEqualSequences(
|
||||||
[10, 20],
|
permutations,
|
||||||
[10, 30],
|
[
|
||||||
[20, 10],
|
[10, 20],
|
||||||
[20, 30],
|
[10, 30],
|
||||||
[30, 10],
|
[20, 10],
|
||||||
[30, 20],
|
[20, 30],
|
||||||
])
|
[30, 10],
|
||||||
|
[30, 20],
|
||||||
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testDocumentationExample3() {
|
func testDocumentationExample3() {
|
||||||
// From Guides/Permutations.md
|
// From Guides/Permutations.md
|
||||||
let numbers2 = [20, 10, 10]
|
let numbers2 = [20, 10, 10]
|
||||||
let permutations = numbers2.permutations()
|
let permutations = numbers2.permutations()
|
||||||
XCTAssertEqualSequences(permutations, [
|
XCTAssertEqualSequences(
|
||||||
[20, 10, 10],
|
permutations,
|
||||||
[20, 10, 10],
|
[
|
||||||
[10, 20, 10],
|
[20, 10, 10],
|
||||||
[10, 10, 20],
|
[20, 10, 10],
|
||||||
[10, 20, 10],
|
[10, 20, 10],
|
||||||
[10, 10, 20],
|
[10, 10, 20],
|
||||||
])
|
[10, 20, 10],
|
||||||
|
[10, 10, 20],
|
||||||
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testDocumentationExample4() {
|
func testDocumentationExample4() {
|
||||||
// From Guides/Permutations.md
|
// From Guides/Permutations.md
|
||||||
let numbers = [10, 20, 30]
|
let numbers = [10, 20, 30]
|
||||||
let permutations = numbers.permutations(ofCount: 0...)
|
let permutations = numbers.permutations(ofCount: 0...)
|
||||||
XCTAssertEqualSequences(permutations, [
|
XCTAssertEqualSequences(
|
||||||
[],
|
permutations,
|
||||||
[10],
|
[
|
||||||
[20],
|
[],
|
||||||
[30],
|
[10],
|
||||||
[10, 20],
|
[20],
|
||||||
[10, 30],
|
[30],
|
||||||
[20, 10],
|
[10, 20],
|
||||||
[20, 30],
|
[10, 30],
|
||||||
[30, 10],
|
[20, 10],
|
||||||
[30, 20],
|
[20, 30],
|
||||||
[10, 20, 30],
|
[30, 10],
|
||||||
[10, 30, 20],
|
[30, 20],
|
||||||
[20, 10, 30],
|
[10, 20, 30],
|
||||||
[20, 30, 10],
|
[10, 30, 20],
|
||||||
[30, 10, 20],
|
[20, 10, 30],
|
||||||
[30, 20, 10],
|
[20, 30, 10],
|
||||||
])
|
[30, 10, 20],
|
||||||
|
[30, 20, 10],
|
||||||
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testDocumentationExample5() {
|
func testDocumentationExample5() {
|
||||||
// From Permutations.swift
|
// From Permutations.swift
|
||||||
let names = ["Alex", "Celeste", "Davide"]
|
let names = ["Alex", "Celeste", "Davide"]
|
||||||
let permutations = names.permutations(ofCount: 2)
|
let permutations = names.permutations(ofCount: 2)
|
||||||
XCTAssertEqualSequences(permutations, [
|
XCTAssertEqualSequences(
|
||||||
["Alex", "Celeste"],
|
permutations,
|
||||||
["Alex", "Davide"],
|
[
|
||||||
["Celeste", "Alex"],
|
["Alex", "Celeste"],
|
||||||
["Celeste", "Davide"],
|
["Alex", "Davide"],
|
||||||
["Davide", "Alex"],
|
["Celeste", "Alex"],
|
||||||
["Davide", "Celeste"],
|
["Celeste", "Davide"],
|
||||||
])
|
["Davide", "Alex"],
|
||||||
|
["Davide", "Celeste"],
|
||||||
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testDocumentationExample6() {
|
func testDocumentationExample6() {
|
||||||
// From Permutations.swift
|
// From Permutations.swift
|
||||||
let names = ["Alex", "Celeste", "Davide"]
|
let names = ["Alex", "Celeste", "Davide"]
|
||||||
let permutations = names.permutations(ofCount: 1...2)
|
let permutations = names.permutations(ofCount: 1...2)
|
||||||
XCTAssertEqualSequences(permutations, [
|
XCTAssertEqualSequences(
|
||||||
["Alex"],
|
permutations,
|
||||||
["Celeste"],
|
[
|
||||||
["Davide"],
|
["Alex"],
|
||||||
["Alex", "Celeste"],
|
["Celeste"],
|
||||||
["Alex", "Davide"],
|
["Davide"],
|
||||||
["Celeste", "Alex"],
|
["Alex", "Celeste"],
|
||||||
["Celeste", "Davide"],
|
["Alex", "Davide"],
|
||||||
["Davide", "Alex"],
|
["Celeste", "Alex"],
|
||||||
["Davide", "Celeste"],
|
["Celeste", "Davide"],
|
||||||
])
|
["Davide", "Alex"],
|
||||||
|
["Davide", "Celeste"],
|
||||||
|
])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
import XCTest
|
||||||
|
|
||||||
@testable import Algorithms
|
@testable import Algorithms
|
||||||
|
|
||||||
final class ProductTests: XCTestCase {
|
final class ProductTests: XCTestCase {
|
||||||
@@ -22,7 +23,7 @@ final class ProductTests: XCTestCase {
|
|||||||
XCTAssertEqualSequences(product(1...10, ""), [], by: ==)
|
XCTAssertEqualSequences(product(1...10, ""), [], by: ==)
|
||||||
XCTAssertEqualSequences(product("", 1...10), [], by: ==)
|
XCTAssertEqualSequences(product("", 1...10), [], by: ==)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testProductReversed() {
|
func testProductReversed() {
|
||||||
XCTAssertEqualSequences(
|
XCTAssertEqualSequences(
|
||||||
[(2, "B" as Character), (2, "A"), (1, "B"), (1, "A")],
|
[(2, "B" as Character), (2, "A"), (1, "B"), (1, "A")],
|
||||||
@@ -32,25 +33,24 @@ final class ProductTests: XCTestCase {
|
|||||||
XCTAssertEqualSequences(product(1...10, "").reversed(), [], by: ==)
|
XCTAssertEqualSequences(product(1...10, "").reversed(), [], by: ==)
|
||||||
XCTAssertEqualSequences(product("", 1...10).reversed(), [], by: ==)
|
XCTAssertEqualSequences(product("", 1...10).reversed(), [], by: ==)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testProductDistanceFromTo() {
|
func testProductDistanceFromTo() {
|
||||||
let p = product([1, 2], "abc")
|
let p = product([1, 2], "abc")
|
||||||
XCTAssertEqual(p.distance(from: p.startIndex, to: p.endIndex), 6)
|
XCTAssertEqual(p.distance(from: p.startIndex, to: p.endIndex), 6)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testProductIndexTraversals() {
|
func testProductIndexTraversals() {
|
||||||
let validator = IndexValidator<Product2Sequence<[Int], String>>(
|
validateIndexTraversals(
|
||||||
indicesIncludingEnd: { product in
|
product([1, 2, 3, 4], "abc"),
|
||||||
|
product([1, 2, 3, 4], ""),
|
||||||
|
product([], "abc"),
|
||||||
|
product([], ""),
|
||||||
|
indices: { product in
|
||||||
product.base1.indices.flatMap { i1 in
|
product.base1.indices.flatMap { i1 in
|
||||||
product.base2.indices.map { i2 in
|
product.base2.indices.map { i2 in
|
||||||
.init(i1: i1, i2: i2)
|
.init(i1: i1, i2: i2)
|
||||||
}
|
}
|
||||||
} + [.init(i1: product.base1.endIndex, i2: product.base2.startIndex)]
|
} + [.init(i1: product.base1.endIndex, i2: product.base2.startIndex)]
|
||||||
})
|
})
|
||||||
|
|
||||||
validator.validate(product([1, 2, 3, 4], "abc"), expectedCount: 4 * 3)
|
|
||||||
validator.validate(product([1, 2, 3, 4], ""), expectedCount: 4 * 0)
|
|
||||||
validator.validate(product([], "abc"), expectedCount: 0 * 3)
|
|
||||||
validator.validate(product([], ""), expectedCount: 0 * 0)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,11 +10,8 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
import XCTest
|
||||||
@testable import Algorithms
|
|
||||||
|
|
||||||
func expectedRange(for value: Int) -> ClosedRange<Int> {
|
@testable import Algorithms
|
||||||
((value / 3) * 2) ... ((value / 3) * 4)
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateRandomSamples<S: Sequence>(
|
func validateRandomSamples<S: Sequence>(
|
||||||
_ samples: [Int: Int],
|
_ samples: [Int: Int],
|
||||||
@@ -22,8 +19,9 @@ func validateRandomSamples<S: Sequence>(
|
|||||||
expectedValue: Int,
|
expectedValue: Int,
|
||||||
file: StaticString = #file, line: UInt = #line
|
file: StaticString = #file, line: UInt = #line
|
||||||
) where S.Element == Int {
|
) where S.Element == Int {
|
||||||
let expectedRange = expectedRange(for: expectedValue)
|
let expectedRange = ((expectedValue / 3) * 2)...((expectedValue / 3) * 4)
|
||||||
XCTAssertEqualSequences(samples.keys.sorted(), elements,
|
XCTAssertEqualSequences(
|
||||||
|
samples.keys.sorted(), elements,
|
||||||
file: file, line: line)
|
file: file, line: line)
|
||||||
for v in samples.values {
|
for v in samples.values {
|
||||||
XCTAssert(expectedRange.contains(v), file: file, line: line)
|
XCTAssert(expectedRange.contains(v), file: file, line: line)
|
||||||
@@ -32,44 +30,41 @@ func validateRandomSamples<S: Sequence>(
|
|||||||
|
|
||||||
private let n = 100
|
private let n = 100
|
||||||
private let k = 12
|
private let k = 12
|
||||||
private let iterations = 1000
|
private let iterations = 10_000
|
||||||
|
|
||||||
/// A collection to sample from.
|
|
||||||
private let c = 0..<n
|
private let c = 0..<n
|
||||||
/// A sequence to sample from.
|
|
||||||
private let s = sequence(first: 0, next: { $0 == n - 1 ? nil : $0 + 1 })
|
private let s = sequence(first: 0, next: { $0 == n - 1 ? nil : $0 + 1 })
|
||||||
/// An empty sequence
|
|
||||||
private let emptySequence = sequence(state: 0, next: { (_) -> Int? in nil })
|
|
||||||
|
|
||||||
final class RandomSampleTests: XCTestCase {
|
final class RandomSampleTests: XCTestCase {
|
||||||
func testRandomStableSampleCollection() {
|
func testRandomStableSampleCollection() {
|
||||||
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
|
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
|
||||||
let sample = c.randomStableSample(count: k)
|
let sample = c.randomStableSample(count: k)
|
||||||
XCTAssert(sample.isSorted())
|
XCTAssert(sample.isSorted())
|
||||||
result.merge(sample.frequencies, uniquingKeysWith: +)
|
for x in sample {
|
||||||
|
result[x, default: 0] += 1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
|
validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testRandomSampleCollection() {
|
func testRandomSampleCollection() {
|
||||||
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
|
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
|
||||||
result.merge(c.randomSample(count: k).frequencies, uniquingKeysWith: +)
|
for x in c.randomSample(count: k) {
|
||||||
|
result[x, default: 0] += 1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
|
validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testRandomSampleSequence() {
|
func testRandomSampleSequence() {
|
||||||
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
|
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
|
||||||
result.merge(s.randomSample(count: k).frequencies, uniquingKeysWith: +)
|
for x in s.randomSample(count: k) {
|
||||||
|
result[x, default: 0] += 1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
validateRandomSamples(samples, elements: s, expectedValue: (k * iterations) / n)
|
validateRandomSamples(samples, elements: s, expectedValue: (k * iterations) / n)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testRandomSampleEdgeCases() {
|
|
||||||
XCTAssert(emptySequence.randomSample(count: 10).isEmpty)
|
|
||||||
XCTAssert(([] as [Int]).randomSample(count: 10).isEmpty)
|
|
||||||
XCTAssert(([] as [Int]).randomStableSample(count: 10).isEmpty)
|
|
||||||
|
|
||||||
|
func testRandomSampleEdgeCases() {
|
||||||
XCTAssert(c.randomStableSample(count: 0).isEmpty)
|
XCTAssert(c.randomStableSample(count: 0).isEmpty)
|
||||||
XCTAssertEqualSequences(c.randomStableSample(count: n), c)
|
XCTAssertEqualSequences(c.randomStableSample(count: n), c)
|
||||||
XCTAssertEqualSequences(c.randomStableSample(count: n * 2), c)
|
XCTAssertEqualSequences(c.randomStableSample(count: n * 2), c)
|
||||||
@@ -77,30 +72,28 @@ final class RandomSampleTests: XCTestCase {
|
|||||||
XCTAssert(c.randomSample(count: 0).isEmpty)
|
XCTAssert(c.randomSample(count: 0).isEmpty)
|
||||||
XCTAssertEqualSequences(c.randomSample(count: n).sorted(), c)
|
XCTAssertEqualSequences(c.randomSample(count: n).sorted(), c)
|
||||||
XCTAssertEqualSequences(c.randomSample(count: n * 2).sorted(), c)
|
XCTAssertEqualSequences(c.randomSample(count: n * 2).sorted(), c)
|
||||||
|
|
||||||
XCTAssert(s.randomSample(count: 0).isEmpty)
|
XCTAssert(s.randomSample(count: 0).isEmpty)
|
||||||
XCTAssertEqualSequences(s.randomSample(count: n).sorted(), c)
|
XCTAssertEqualSequences(s.randomSample(count: n).sorted(), c)
|
||||||
XCTAssertEqualSequences(s.randomSample(count: n * 2).sorted(), c)
|
XCTAssertEqualSequences(s.randomSample(count: n * 2).sorted(), c)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testRandomSampleRepeatable() {
|
|
||||||
let seed = UInt64.random(in: 0 ... .max)
|
|
||||||
|
|
||||||
var generator = SplitMix64(seed: seed)
|
func testRandomSampleRepeatable() {
|
||||||
|
var generator = SplitMix64(seed: 0)
|
||||||
let sample1a = c.randomSample(count: k, using: &generator)
|
let sample1a = c.randomSample(count: k, using: &generator)
|
||||||
generator = SplitMix64(seed: seed)
|
generator = SplitMix64(seed: 0)
|
||||||
let sample2a = c.randomSample(count: k, using: &generator)
|
let sample2a = c.randomSample(count: k, using: &generator)
|
||||||
XCTAssertEqual(sample1a, sample2a)
|
XCTAssertEqual(sample1a, sample2a)
|
||||||
|
|
||||||
generator = SplitMix64(seed: seed)
|
generator = SplitMix64(seed: 0)
|
||||||
let sample1b = s.randomSample(count: k, using: &generator)
|
let sample1b = s.randomSample(count: k, using: &generator)
|
||||||
generator = SplitMix64(seed: seed)
|
generator = SplitMix64(seed: 0)
|
||||||
let sample2b = s.randomSample(count: k, using: &generator)
|
let sample2b = s.randomSample(count: k, using: &generator)
|
||||||
XCTAssertEqual(sample1b, sample2b)
|
XCTAssertEqual(sample1b, sample2b)
|
||||||
|
|
||||||
generator = SplitMix64(seed: seed)
|
generator = SplitMix64(seed: 0)
|
||||||
let sample1c = c.randomStableSample(count: k, using: &generator)
|
let sample1c = c.randomStableSample(count: k, using: &generator)
|
||||||
generator = SplitMix64(seed: seed)
|
generator = SplitMix64(seed: 0)
|
||||||
let sample2c = c.randomStableSample(count: k, using: &generator)
|
let sample2c = c.randomStableSample(count: k, using: &generator)
|
||||||
XCTAssertEqual(sample1c, sample2c)
|
XCTAssertEqual(sample1c, sample2c)
|
||||||
}
|
}
|
||||||
@@ -110,7 +103,7 @@ final class RandomSampleTests: XCTestCase {
|
|||||||
mutating func next() -> UInt64 { 0 }
|
mutating func next() -> UInt64 { 0 }
|
||||||
}
|
}
|
||||||
var zero = ZeroGenerator()
|
var zero = ZeroGenerator()
|
||||||
_ = nextOffset(w: 1, using: &zero) // must not crash
|
_ = nextOffset(w: 1, using: &zero) // must not crash
|
||||||
|
|
||||||
struct AlmostAllZeroGenerator: RandomNumberGenerator {
|
struct AlmostAllZeroGenerator: RandomNumberGenerator {
|
||||||
private var forward: SplitMix64
|
private var forward: SplitMix64
|
||||||
@@ -128,41 +121,8 @@ final class RandomSampleTests: XCTestCase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var almostAllZero = AlmostAllZeroGenerator(seed: 0)
|
var almostAllZero = AlmostAllZeroGenerator(seed: 0)
|
||||||
_ = s.randomSample(count: k, using: &almostAllZero) // must not crash
|
_ = s.randomSample(count: k, using: &almostAllZero) // must not crash
|
||||||
almostAllZero = AlmostAllZeroGenerator(seed: 0)
|
almostAllZero = AlmostAllZeroGenerator(seed: 0)
|
||||||
_ = c.randomSample(count: k, using: &almostAllZero) // must not crash
|
_ = c.randomSample(count: k, using: &almostAllZero) // must not crash
|
||||||
}
|
|
||||||
|
|
||||||
func testSequenceRandomElement() {
|
|
||||||
XCTAssertNil(emptySequence.randomElement())
|
|
||||||
|
|
||||||
let expectedRange = expectedRange(for: iterations)
|
|
||||||
let randomElements = (0..<(n*iterations)).map { _ in
|
|
||||||
s.randomElement()!
|
|
||||||
}.frequencies
|
|
||||||
XCTAssertEqual(randomElements.count, n)
|
|
||||||
XCTAssert(randomElements.values.allSatisfy { expectedRange.contains($0) })
|
|
||||||
|
|
||||||
let oneElementSequence = sequence(first: 0, next: { _ in nil })
|
|
||||||
let randomOneElement = (0..<iterations).map { _ in
|
|
||||||
oneElementSequence.randomElement()!
|
|
||||||
}
|
|
||||||
XCTAssert(randomOneElement.allSatisfy { $0 == 0 })
|
|
||||||
|
|
||||||
let twoElementSequence = sequence(state: [1, 2].makeIterator(), next: { $0.next() })
|
|
||||||
let randomTwoElement = (0..<(2*iterations)).map { _ in
|
|
||||||
twoElementSequence.randomElement()!
|
|
||||||
}.frequencies
|
|
||||||
XCTAssertEqual(randomTwoElement.count, 2)
|
|
||||||
XCTAssert(randomElements.values.allSatisfy { expectedRange.contains($0) })
|
|
||||||
}
|
|
||||||
|
|
||||||
func testSequenceRandomElementRepeatable() {
|
|
||||||
let seed = UInt64.random(in: 0 ... .max)
|
|
||||||
var generator = SplitMix64(seed: seed)
|
|
||||||
let elements1 = (0..<500).map { _ in s.randomElement(using: &generator)! }
|
|
||||||
generator = SplitMix64(seed: seed)
|
|
||||||
let elements2 = (0..<500).map { _ in s.randomElement(using: &generator)! }
|
|
||||||
XCTAssertEqual(elements1, elements2)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,10 +9,11 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
|
||||||
import Algorithms
|
import Algorithms
|
||||||
|
import XCTest
|
||||||
|
|
||||||
final class ReductionsTests: XCTestCase {
|
final class ReductionsTests: XCTestCase {
|
||||||
|
|
||||||
struct TestError: Error {}
|
struct TestError: Error {}
|
||||||
|
|
||||||
// MARK: - Exclusive Reductions
|
// MARK: - Exclusive Reductions
|
||||||
@@ -51,13 +52,6 @@ final class ReductionsTests: XCTestCase {
|
|||||||
XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() })
|
XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() })
|
||||||
XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() })
|
XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() })
|
||||||
}
|
}
|
||||||
|
|
||||||
func testExclusiveIndexTraversals() {
|
|
||||||
let validator = IndexValidator<ExclusiveReductionsSequence<Range<Int>, Int>>()
|
|
||||||
validator.validate((0..<0).lazy.reductions(0, +), expectedCount: 1)
|
|
||||||
validator.validate((0..<1).lazy.reductions(0, +), expectedCount: 2)
|
|
||||||
validator.validate((0..<4).lazy.reductions(0, +), expectedCount: 5)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Inclusive Reductions
|
// MARK: - Inclusive Reductions
|
||||||
|
|
||||||
@@ -84,11 +78,4 @@ final class ReductionsTests: XCTestCase {
|
|||||||
XCTAssertNoThrow(try [1].reductions { _, _ in throw TestError() })
|
XCTAssertNoThrow(try [1].reductions { _, _ in throw TestError() })
|
||||||
XCTAssertThrowsError(try [1, 1].reductions { _, _ in throw TestError() })
|
XCTAssertThrowsError(try [1, 1].reductions { _, _ in throw TestError() })
|
||||||
}
|
}
|
||||||
|
|
||||||
func testInclusiveIndexTraversals() {
|
|
||||||
let validator = IndexValidator<InclusiveReductionsSequence<Range<Int>>>()
|
|
||||||
validator.validate((0..<0).lazy.reductions(+), expectedCount: 0)
|
|
||||||
validator.validate((0..<1).lazy.reductions(+), expectedCount: 1)
|
|
||||||
validator.validate((0..<4).lazy.reductions(+), expectedCount: 4)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
import XCTest
|
||||||
|
|
||||||
@testable import Algorithms
|
@testable import Algorithms
|
||||||
|
|
||||||
final class RotateTests: XCTestCase {
|
final class RotateTests: XCTestCase {
|
||||||
@@ -17,20 +18,21 @@ final class RotateTests: XCTestCase {
|
|||||||
func testUnderscoreReverse() {
|
func testUnderscoreReverse() {
|
||||||
var input = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]
|
var input = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]
|
||||||
let limit: Int = 4
|
let limit: Int = 4
|
||||||
let (lower, upper) = input._reverse(subrange: input.startIndex..<input.endIndex, until: input.startIndex.advanced(by: limit))
|
let (lower, upper) = input._reverse(
|
||||||
|
subrange: input.startIndex..<input.endIndex, until: input.startIndex.advanced(by: limit))
|
||||||
let expected = ["p", "o", "n", "m", "e", "f", "g", "h", "i", "j", "k", "l", "d", "c", "b", "a"]
|
let expected = ["p", "o", "n", "m", "e", "f", "g", "h", "i", "j", "k", "l", "d", "c", "b", "a"]
|
||||||
XCTAssertEqual(input, expected)
|
XCTAssertEqual(input, expected)
|
||||||
XCTAssertEqual(lower, input.startIndex.advanced(by: limit))
|
XCTAssertEqual(lower, input.startIndex.advanced(by: limit))
|
||||||
XCTAssertEqual(upper, input.endIndex.advanced(by: -limit))
|
XCTAssertEqual(upper, input.endIndex.advanced(by: -limit))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tests the example given in `reverse(subrange:)`’s documentation
|
/// Tests the example given in `reverse(subrange:)`’s documentation
|
||||||
func testReverse() {
|
func testReverse() {
|
||||||
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||||
numbers.reverse(subrange: 0..<4)
|
numbers.reverse(subrange: 0..<4)
|
||||||
XCTAssertEqual(numbers, [40, 30, 20, 10, 50, 60, 70, 80])
|
XCTAssertEqual(numbers, [40, 30, 20, 10, 50, 60, 70, 80])
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tests `rotate(subrange:toStartAt:)` with an empty subrange
|
/// Tests `rotate(subrange:toStartAt:)` with an empty subrange
|
||||||
/// The order of elements are unchanged
|
/// The order of elements are unchanged
|
||||||
func testRotateEmptySubrange() {
|
func testRotateEmptySubrange() {
|
||||||
@@ -39,7 +41,7 @@ final class RotateTests: XCTestCase {
|
|||||||
XCTAssertEqual(numbers, [10, 20, 30, 40, 50, 60, 70, 80])
|
XCTAssertEqual(numbers, [10, 20, 30, 40, 50, 60, 70, 80])
|
||||||
XCTAssertEqual(numbers[oldStart], 40)
|
XCTAssertEqual(numbers[oldStart], 40)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tests `rotate(subrange:toStartAt:)` with an empty collection
|
/// Tests `rotate(subrange:toStartAt:)` with an empty collection
|
||||||
func testRotateSubrangeOnEmptyCollection() {
|
func testRotateSubrangeOnEmptyCollection() {
|
||||||
var numbers = [Int]()
|
var numbers = [Int]()
|
||||||
@@ -47,7 +49,7 @@ final class RotateTests: XCTestCase {
|
|||||||
XCTAssertEqual(numbers, [])
|
XCTAssertEqual(numbers, [])
|
||||||
XCTAssertEqual(oldStart, numbers.startIndex)
|
XCTAssertEqual(oldStart, numbers.startIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tests `rotate(subrange:toStartAt:)` with the full range of the collection
|
/// Tests `rotate(subrange:toStartAt:)` with the full range of the collection
|
||||||
func testRotateFullRange() {
|
func testRotateFullRange() {
|
||||||
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||||
@@ -55,7 +57,7 @@ final class RotateTests: XCTestCase {
|
|||||||
XCTAssertEqual(numbers, [20, 30, 40, 50, 60, 70, 80, 10])
|
XCTAssertEqual(numbers, [20, 30, 40, 50, 60, 70, 80, 10])
|
||||||
XCTAssertEqual(numbers[oldStart], 10)
|
XCTAssertEqual(numbers[oldStart], 10)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tests the example given in `rotate(subrange:toStartAt:)`’s documentation
|
/// Tests the example given in `rotate(subrange:toStartAt:)`’s documentation
|
||||||
func testRotateSubrange() {
|
func testRotateSubrange() {
|
||||||
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||||
@@ -63,7 +65,7 @@ final class RotateTests: XCTestCase {
|
|||||||
XCTAssertEqual(numbers, [30, 40, 10, 20, 50, 60, 70, 80])
|
XCTAssertEqual(numbers, [30, 40, 10, 20, 50, 60, 70, 80])
|
||||||
XCTAssertEqual(numbers[oldStart], 10)
|
XCTAssertEqual(numbers[oldStart], 10)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tests the example given in `rotate(toStartAt:)`’s documentation
|
/// Tests the example given in `rotate(toStartAt:)`’s documentation
|
||||||
func testRotateExample() {
|
func testRotateExample() {
|
||||||
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||||
@@ -71,7 +73,7 @@ final class RotateTests: XCTestCase {
|
|||||||
XCTAssertEqual(numbers, [40, 50, 60, 70, 80, 10, 20, 30])
|
XCTAssertEqual(numbers, [40, 50, 60, 70, 80, 10, 20, 30])
|
||||||
XCTAssertEqual(numbers[oldStart], 10)
|
XCTAssertEqual(numbers[oldStart], 10)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tests `rotate(toStartAt:)` on collections of varying lengths, at different
|
/// Tests `rotate(toStartAt:)` on collections of varying lengths, at different
|
||||||
/// starting points
|
/// starting points
|
||||||
func testRotate() {
|
func testRotate() {
|
||||||
|
|||||||
@@ -9,11 +9,11 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
|
||||||
import Algorithms
|
import Algorithms
|
||||||
|
import XCTest
|
||||||
|
|
||||||
final class StridingTests: XCTestCase {
|
final class StridingTests: XCTestCase {
|
||||||
|
|
||||||
func testStride() {
|
func testStride() {
|
||||||
let a = 0...10
|
let a = 0...10
|
||||||
XCTAssertEqualSequences(a.striding(by: 1), (0...10))
|
XCTAssertEqualSequences(a.striding(by: 1), (0...10))
|
||||||
@@ -23,7 +23,7 @@ final class StridingTests: XCTestCase {
|
|||||||
XCTAssertEqualSequences(a.striding(by: 5), [0, 5, 10])
|
XCTAssertEqualSequences(a.striding(by: 5), [0, 5, 10])
|
||||||
XCTAssertEqualSequences(a.striding(by: 10), [0, 10])
|
XCTAssertEqualSequences(a.striding(by: 10), [0, 10])
|
||||||
XCTAssertEqualSequences(a.striding(by: 11), [0])
|
XCTAssertEqualSequences(a.striding(by: 11), [0])
|
||||||
|
|
||||||
let s = (0...).prefix(11)
|
let s = (0...).prefix(11)
|
||||||
XCTAssertEqualSequences(s.striding(by: 1), (0...10))
|
XCTAssertEqualSequences(s.striding(by: 1), (0...10))
|
||||||
XCTAssertEqualSequences(s.striding(by: 2), [0, 2, 4, 6, 8, 10])
|
XCTAssertEqualSequences(s.striding(by: 2), [0, 2, 4, 6, 8, 10])
|
||||||
@@ -32,22 +32,22 @@ final class StridingTests: XCTestCase {
|
|||||||
XCTAssertEqualSequences(s.striding(by: 5), [0, 5, 10])
|
XCTAssertEqualSequences(s.striding(by: 5), [0, 5, 10])
|
||||||
XCTAssertEqualSequences(s.striding(by: 10), [0, 10])
|
XCTAssertEqualSequences(s.striding(by: 10), [0, 10])
|
||||||
XCTAssertEqualSequences(s.striding(by: 11), [0])
|
XCTAssertEqualSequences(s.striding(by: 11), [0])
|
||||||
|
|
||||||
let empty = (0...).prefix(0)
|
let empty = (0...).prefix(0)
|
||||||
XCTAssertEqualSequences(empty.striding(by: 2), [])
|
XCTAssertEqualSequences(empty.striding(by: 2), [])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testStrideString() {
|
func testStrideString() {
|
||||||
let s = "swift"
|
let s = "swift"
|
||||||
XCTAssertEqualSequences(s.striding(by: 2), ["s", "i", "t"])
|
XCTAssertEqualSequences(s.striding(by: 2), ["s", "i", "t"])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testStrideReversed() {
|
func testStrideReversed() {
|
||||||
let a = [0, 1, 2, 3, 4, 5]
|
let a = [0, 1, 2, 3, 4, 5]
|
||||||
XCTAssertEqualSequences(a.striding(by: 3).reversed(), [3, 0])
|
XCTAssertEqualSequences(a.striding(by: 3).reversed(), [3, 0])
|
||||||
XCTAssertEqualSequences(a.reversed().striding(by: 2), [5, 3, 1])
|
XCTAssertEqualSequences(a.reversed().striding(by: 2), [5, 3, 1])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testStrideIndexes() {
|
func testStrideIndexes() {
|
||||||
let a = [0, 1, 2, 3, 4, 5].striding(by: 2)
|
let a = [0, 1, 2, 3, 4, 5].striding(by: 2)
|
||||||
var i = a.startIndex
|
var i = a.startIndex
|
||||||
@@ -60,20 +60,20 @@ final class StridingTests: XCTestCase {
|
|||||||
XCTAssertEqual(a[i], 2)
|
XCTAssertEqual(a[i], 2)
|
||||||
a.formIndex(before: &i)
|
a.formIndex(before: &i)
|
||||||
XCTAssertEqual(a[i], 0)
|
XCTAssertEqual(a[i], 0)
|
||||||
// a.formIndex(before: &i) // Precondition failed: Incrementing past start index
|
// a.formIndex(before: &i) // Precondition failed: Incrementing past start index
|
||||||
// a.index(after: a.endIndex) // Precondition failed: Advancing past end index
|
// a.index(after: a.endIndex) // Precondition failed: Advancing past end index
|
||||||
}
|
}
|
||||||
|
|
||||||
func testStrideLast() {
|
func testStrideLast() {
|
||||||
XCTAssertEqual((1...10).striding(by: 2).last, 9) // 1, 3, 5, 7, 9
|
XCTAssertEqual((1...10).striding(by: 2).last, 9) // 1, 3, 5, 7, 9
|
||||||
XCTAssertEqual((1...10).striding(by: 3).last, 10) // 1, 4, 7, 10
|
XCTAssertEqual((1...10).striding(by: 3).last, 10) // 1, 4, 7, 10
|
||||||
XCTAssertEqual((1...10).striding(by: 4).last, 9) // 1, 5, 9
|
XCTAssertEqual((1...10).striding(by: 4).last, 9) // 1, 5, 9
|
||||||
XCTAssertEqual((1...10).striding(by: 5).last, 6) // 1, 6
|
XCTAssertEqual((1...10).striding(by: 5).last, 6) // 1, 6
|
||||||
XCTAssertEqual((1...100).striding(by: 50).last, 51) // 1, 51
|
XCTAssertEqual((1...100).striding(by: 50).last, 51) // 1, 51
|
||||||
XCTAssertEqual((1...5).striding(by: 2).last, 5) // 1, 3, 5
|
XCTAssertEqual((1...5).striding(by: 2).last, 5) // 1, 3, 5
|
||||||
XCTAssertEqual([Int]().striding(by: 2).last, nil) // empty
|
XCTAssertEqual([Int]().striding(by: 2).last, nil) // empty
|
||||||
}
|
}
|
||||||
|
|
||||||
func testCount() {
|
func testCount() {
|
||||||
let empty = [Int]().striding(by: 2)
|
let empty = [Int]().striding(by: 2)
|
||||||
XCTAssertEqual(empty.count, 0)
|
XCTAssertEqual(empty.count, 0)
|
||||||
@@ -86,40 +86,33 @@ final class StridingTests: XCTestCase {
|
|||||||
XCTAssertEqual(a.striding(by: 10).count, [0, 10].count)
|
XCTAssertEqual(a.striding(by: 10).count, [0, 10].count)
|
||||||
XCTAssertEqual(a.striding(by: 11).count, [0].count)
|
XCTAssertEqual(a.striding(by: 11).count, [0].count)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testIndexTraversals() {
|
func testIndexTraversals() {
|
||||||
do {
|
let empty = [Int]()
|
||||||
let empty = [Int]()
|
validateIndexTraversals(
|
||||||
let validator = IndexValidator<StridingCollection<[Int]>>()
|
empty.striding(by: 1),
|
||||||
validator.validate(empty.striding(by: 1))
|
empty.striding(by: 2)
|
||||||
validator.validate(empty.striding(by: 2))
|
)
|
||||||
}
|
let zero_to_one_hundered_range = 0...100
|
||||||
|
validateIndexTraversals(
|
||||||
do {
|
zero_to_one_hundered_range.striding(by: 10),
|
||||||
let range = 0...100
|
zero_to_one_hundered_range.striding(by: 11),
|
||||||
let validator = IndexValidator<StridingCollection<ClosedRange<Int>>>()
|
zero_to_one_hundered_range.striding(by: 101)
|
||||||
validator.validate(range.striding(by: 10))
|
)
|
||||||
validator.validate(range.striding(by: 11))
|
let zero_to_one_hundered_array = Array(zero_to_one_hundered_range)
|
||||||
validator.validate(range.striding(by: 101))
|
validateIndexTraversals(
|
||||||
}
|
zero_to_one_hundered_array.striding(by: 10),
|
||||||
|
zero_to_one_hundered_array.striding(by: 11),
|
||||||
do {
|
zero_to_one_hundered_array.striding(by: 101)
|
||||||
let array = Array(0...100)
|
)
|
||||||
let validator = IndexValidator<StridingCollection<[Int]>>()
|
let string = "swift rocks".map(String.init)
|
||||||
validator.validate(array.striding(by: 10))
|
validateIndexTraversals(
|
||||||
validator.validate(array.striding(by: 11))
|
string.striding(by: 1),
|
||||||
validator.validate(array.striding(by: 101))
|
string.striding(by: 2),
|
||||||
}
|
string.striding(by: 10)
|
||||||
|
)
|
||||||
do {
|
|
||||||
let string = "swift rocks"
|
|
||||||
let validator = IndexValidator<StridingCollection<String>>()
|
|
||||||
validator.validate(string.striding(by: 1))
|
|
||||||
validator.validate(string.striding(by: 2))
|
|
||||||
validator.validate(string.striding(by: 10))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func testOffsetBy() {
|
func testOffsetBy() {
|
||||||
let a = (0...100).striding(by: 22)
|
let a = (0...100).striding(by: 22)
|
||||||
let b = [0, 22, 44, 66, 88]
|
let b = [0, 22, 44, 66, 88]
|
||||||
@@ -127,17 +120,11 @@ final class StridingTests: XCTestCase {
|
|||||||
XCTAssertEqual(a[a.index(a.startIndex, offsetBy: i)], b[i])
|
XCTAssertEqual(a[a.index(a.startIndex, offsetBy: i)], b[i])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func testOffsetByEndIndex() {
|
func testOffsetByEndIndex() {
|
||||||
let a = 1...5
|
let a = 1...5
|
||||||
let b = a.striding(by: 3) // [1, 4]
|
let b = a.striding(by: 3) // [1, 4]
|
||||||
let i = b.index(b.startIndex, offsetBy: 2)
|
let i = b.index(b.startIndex, offsetBy: 2)
|
||||||
XCTAssertEqual(i, b.endIndex)
|
XCTAssertEqual(i, b.endIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testLazy() {
|
|
||||||
XCTAssertLazySequence(AnySequence(0..<100).lazy.striding(by: 3))
|
|
||||||
XCTAssertLazySequence((0..<100).lazy.striding(by: 3))
|
|
||||||
XCTAssertLazyCollection((0..<100).lazy.striding(by: 3))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
import XCTest
|
||||||
|
|
||||||
@testable import Algorithms
|
@testable import Algorithms
|
||||||
|
|
||||||
final class SuffixTests: XCTestCase {
|
final class SuffixTests: XCTestCase {
|
||||||
@@ -19,29 +20,29 @@ final class SuffixTests: XCTestCase {
|
|||||||
XCTAssertEqualSequences(a.suffix(while: { $0 > 10 }), [])
|
XCTAssertEqualSequences(a.suffix(while: { $0 > 10 }), [])
|
||||||
XCTAssertEqualSequences(a.suffix(while: { $0 > 9 }), [10])
|
XCTAssertEqualSequences(a.suffix(while: { $0 > 9 }), [10])
|
||||||
XCTAssertEqualSequences(a.suffix(while: { $0 > -1 }), (0...10))
|
XCTAssertEqualSequences(a.suffix(while: { $0 > -1 }), (0...10))
|
||||||
|
|
||||||
let empty: [Int] = []
|
let empty: [Int] = []
|
||||||
XCTAssertEqualSequences(empty.suffix(while: { $0 > 10 }), [])
|
XCTAssertEqualSequences(empty.suffix(while: { $0 > 10 }), [])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testEndOfPrefix() {
|
func testEndOfPrefix() {
|
||||||
let array = Array(0..<10)
|
let array = Array(0..<10)
|
||||||
XCTAssertEqual(array.endOfPrefix(while: { $0 < 3 }), 3)
|
XCTAssertEqual(array.endOfPrefix(while: { $0 < 3 }), 3)
|
||||||
XCTAssertEqual(array.endOfPrefix(while: { _ in false }), array.startIndex)
|
XCTAssertEqual(array.endOfPrefix(while: { _ in false }), array.startIndex)
|
||||||
XCTAssertEqual(array.endOfPrefix(while: { _ in true }), array.endIndex)
|
XCTAssertEqual(array.endOfPrefix(while: { _ in true }), array.endIndex)
|
||||||
|
|
||||||
let empty = [Int]()
|
let empty = [Int]()
|
||||||
XCTAssertEqual(empty.endOfPrefix(while: { $0 < 3 }), 0)
|
XCTAssertEqual(empty.endOfPrefix(while: { $0 < 3 }), 0)
|
||||||
XCTAssertEqual(empty.endOfPrefix(while: { _ in false }), empty.startIndex)
|
XCTAssertEqual(empty.endOfPrefix(while: { _ in false }), empty.startIndex)
|
||||||
XCTAssertEqual(empty.endOfPrefix(while: { _ in true }), empty.endIndex)
|
XCTAssertEqual(empty.endOfPrefix(while: { _ in true }), empty.endIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testStartOfSuffix() {
|
func testStartOfSuffix() {
|
||||||
let array = Array(0..<10)
|
let array = Array(0..<10)
|
||||||
XCTAssertEqual(array.startOfSuffix(while: { $0 >= 3 }), 3)
|
XCTAssertEqual(array.startOfSuffix(while: { $0 >= 3 }), 3)
|
||||||
XCTAssertEqual(array.startOfSuffix(while: { _ in false }), array.endIndex)
|
XCTAssertEqual(array.startOfSuffix(while: { _ in false }), array.endIndex)
|
||||||
XCTAssertEqual(array.startOfSuffix(while: { _ in true }), array.startIndex)
|
XCTAssertEqual(array.startOfSuffix(while: { _ in true }), array.startIndex)
|
||||||
|
|
||||||
let empty = [Int]()
|
let empty = [Int]()
|
||||||
XCTAssertEqual(empty.startOfSuffix(while: { $0 < 3 }), 0)
|
XCTAssertEqual(empty.startOfSuffix(while: { $0 < 3 }), 0)
|
||||||
XCTAssertEqual(empty.startOfSuffix(while: { _ in false }), empty.endIndex)
|
XCTAssertEqual(empty.startOfSuffix(while: { _ in false }), empty.endIndex)
|
||||||
|
|||||||
@@ -23,12 +23,6 @@ extension Sequence where Element: Comparable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Sequence where Element: Hashable {
|
|
||||||
var frequencies: [Element: Int] {
|
|
||||||
reduce(into: [:]) { $0[$1, default: 0] += 1 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Numeric {
|
extension Numeric {
|
||||||
func factorial() -> Self {
|
func factorial() -> Self {
|
||||||
guard self != 0 else { return 1 }
|
guard self != 0 else { return 1 }
|
||||||
@@ -38,16 +32,16 @@ extension Numeric {
|
|||||||
|
|
||||||
struct SplitMix64: RandomNumberGenerator {
|
struct SplitMix64: RandomNumberGenerator {
|
||||||
private var state: UInt64
|
private var state: UInt64
|
||||||
|
|
||||||
init(seed: UInt64) {
|
init(seed: UInt64) {
|
||||||
self.state = seed
|
self.state = seed
|
||||||
}
|
}
|
||||||
|
|
||||||
mutating func next() -> UInt64 {
|
mutating func next() -> UInt64 {
|
||||||
self.state &+= 0x9e3779b97f4a7c15
|
self.state &+= 0x9e37_79b9_7f4a_7c15
|
||||||
var z: UInt64 = self.state
|
var z: UInt64 = self.state
|
||||||
z = (z ^ (z &>> 30)) &* 0xbf58476d1ce4e5b9
|
z = (z ^ (z &>> 30)) &* 0xbf58_476d_1ce4_e5b9
|
||||||
z = (z ^ (z &>> 27)) &* 0x94d049bb133111eb
|
z = (z ^ (z &>> 27)) &* 0x94d0_49bb_1331_11eb
|
||||||
return z ^ (z &>> 31)
|
return z ^ (z &>> 31)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -60,12 +54,12 @@ struct AnyMutableCollection<Base> where Base: MutableCollection {
|
|||||||
extension AnyMutableCollection: MutableCollection {
|
extension AnyMutableCollection: MutableCollection {
|
||||||
typealias Index = Base.Index
|
typealias Index = Base.Index
|
||||||
typealias Element = Base.Element
|
typealias Element = Base.Element
|
||||||
|
|
||||||
var startIndex: Base.Index { base.startIndex }
|
var startIndex: Base.Index { base.startIndex }
|
||||||
var endIndex: Base.Index { base.endIndex }
|
var endIndex: Base.Index { base.endIndex }
|
||||||
|
|
||||||
func index(after i: Index) -> Index {
|
func index(after i: Index) -> Index {
|
||||||
base.index(after: i)
|
return base.index(after: i)
|
||||||
}
|
}
|
||||||
|
|
||||||
subscript(position: Base.Index) -> Base.Element {
|
subscript(position: Base.Index) -> Base.Element {
|
||||||
@@ -86,7 +80,8 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
|
|||||||
_ message: @autoclosure () -> String = "",
|
_ message: @autoclosure () -> String = "",
|
||||||
file: StaticString = #file, line: UInt = #line
|
file: StaticString = #file, line: UInt = #line
|
||||||
) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
|
) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
|
||||||
try XCTAssertEqualSequences(expression1(), expression2(), by: ==,
|
try XCTAssertEqualSequences(
|
||||||
|
expression1(), expression2(), by: ==,
|
||||||
message(), file: file, line: line)
|
message(), file: file, line: line)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,7 +100,7 @@ func XCTAssertUnorderedEqualSequences<S1: Sequence, S2: Sequence>(
|
|||||||
}
|
}
|
||||||
s1.remove(at: idx)
|
s1.remove(at: idx)
|
||||||
}
|
}
|
||||||
|
|
||||||
XCTAssertTrue(
|
XCTAssertTrue(
|
||||||
missing.isEmpty, "first sequence missing '\(missing)' elements from second sequence",
|
missing.isEmpty, "first sequence missing '\(missing)' elements from second sequence",
|
||||||
file: file, line: line
|
file: file, line: line
|
||||||
@@ -127,8 +122,9 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
|
|||||||
|
|
||||||
func fail(_ reason: String) {
|
func fail(_ reason: String) {
|
||||||
let message = message()
|
let message = message()
|
||||||
XCTFail(message.isEmpty ? reason : "\(message) - \(reason)",
|
XCTFail(
|
||||||
file: file, line: line)
|
message.isEmpty ? reason : "\(message) - \(reason)",
|
||||||
|
file: file, line: line)
|
||||||
}
|
}
|
||||||
|
|
||||||
var iter1 = try expression1().makeIterator()
|
var iter1 = try expression1().makeIterator()
|
||||||
@@ -140,7 +136,9 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
|
|||||||
idx += 1
|
idx += 1
|
||||||
continue
|
continue
|
||||||
case let (e1?, e2?):
|
case let (e1?, e2?):
|
||||||
fail("element \(e1) on first sequence does not match element \(e2) on second sequence at position \(idx)")
|
fail(
|
||||||
|
"element \(e1) on first sequence does not match element \(e2) on second sequence at position \(idx)"
|
||||||
|
)
|
||||||
case (_?, nil):
|
case (_?, nil):
|
||||||
fail("second sequence shorter than first")
|
fail("second sequence shorter than first")
|
||||||
case (nil, _?):
|
case (nil, _?):
|
||||||
@@ -169,162 +167,93 @@ func XCTAssertEqualCollections<C1: Collection, C2: Collection>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct IndexValidator<C: Collection> {
|
/// Tests that all index traversal methods behave as expected.
|
||||||
let testRandomAccess = true
|
///
|
||||||
let indicesIncludingEnd: (C) -> [C.Index]
|
/// Verifies the correctness of the implementations of `startIndex`, `endIndex`,
|
||||||
|
/// `indices`, `count`, `isEmpty`, `index(before:)`, `index(after:)`,
|
||||||
/// Creates a new instance of an index validator that can verify that indices
|
/// `index(_:offsetBy:)`, `index(_:offsetBy:limitedBy:)`, and
|
||||||
/// of a collection behave correctly and consistently.
|
/// `distance(from:to:)` by calling them with just about all possible input
|
||||||
///
|
/// combinations. When provided, the `indices` function is used to to test the
|
||||||
/// Usage:
|
/// collection methods against.
|
||||||
///
|
///
|
||||||
/// let validator = IndexValidator<ReversedCollection<String>>()
|
/// - Parameters:
|
||||||
/// validator.validate("abc".reversed())
|
/// - collections: The collections to be validated.
|
||||||
/// validator.validate("xyz".reversed(), expectedCount: 3)
|
/// - indices: A closure that returns the expected indices of the given
|
||||||
///
|
/// collection, including its `endIndex`, in ascending order. Only use this
|
||||||
/// - Parameters:
|
/// parameter if you are able to compute the indices of the collection
|
||||||
/// - testRandomAccess: If `true`, also tests the correctness of the methods
|
/// independently of the `Collection` conformance, e.g. by using the
|
||||||
/// `index(_:offsetBy:)`, `index(_:offsetBy:limitedBy:)`, and
|
/// contents of the collection directly.
|
||||||
/// `distance(from:to:)`. Only useful if the collection overrides these
|
///
|
||||||
/// methods. Defaults to `true`.
|
/// - Complexity: O(*n*^3) for each collection, where *n* is the length of the
|
||||||
/// - indicesIncludingEnd: A closure that returns the expected indices of
|
/// collection.
|
||||||
/// the given collection, including its `endIndex`, in ascending order.
|
func validateIndexTraversals<C>(
|
||||||
/// Only use this parameter if you are able to compute the indices of the
|
_ collections: C...,
|
||||||
/// collection independently of the `Collection` conformance, e.g. by
|
indices: ((C) -> [C.Index])? = nil,
|
||||||
/// using the contents of the collection directly.
|
file: StaticString = #file, line: UInt = #line
|
||||||
init(
|
) where C: BidirectionalCollection {
|
||||||
testRandomAccess: Bool = true,
|
for c in collections {
|
||||||
indicesIncludingEnd: @escaping (C) -> [C.Index] = { $0.indices + [$0.endIndex] }
|
let indicesIncludingEnd = indices?(c) ?? (c.indices + [c.endIndex])
|
||||||
) {
|
|
||||||
self.indicesIncludingEnd = indicesIncludingEnd
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension IndexValidator {
|
|
||||||
fileprivate struct Validator {
|
|
||||||
let collection: C
|
|
||||||
let count: Int
|
|
||||||
let indicesIncludingEnd: [C.Index]
|
|
||||||
let file: StaticString
|
|
||||||
let line: UInt
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Verifies that all index traversal methods behave as expected.
|
|
||||||
///
|
|
||||||
/// Verifies the correctness of the implementations of `startIndex`,
|
|
||||||
/// `endIndex`, `indices`, `count`, `isEmpty`, `index(before:)`,
|
|
||||||
/// `index(after:)`, `index(_:offsetBy:)`, `index(_:offsetBy:limitedBy:)`, and
|
|
||||||
/// `distance(from:to:)` by calling them with just about all possible input
|
|
||||||
/// combinations.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - collection: The collection to be validated.
|
|
||||||
/// - expectedCount:
|
|
||||||
///
|
|
||||||
/// - Complexity: O(*n*^3) where *n* is the length of the collection if the
|
|
||||||
/// collection conforms to `RandomAccesCollection`, otherwise O(*n*^4).
|
|
||||||
func validate(
|
|
||||||
_ collection: C,
|
|
||||||
expectedCount: Int? = nil,
|
|
||||||
file: StaticString = #file, line: UInt = #line
|
|
||||||
) {
|
|
||||||
let indicesIncludingEnd = self.indicesIncludingEnd(collection)
|
|
||||||
let count = indicesIncludingEnd.count - 1
|
let count = indicesIncludingEnd.count - 1
|
||||||
|
|
||||||
let validator = Validator(
|
|
||||||
collection: collection,
|
|
||||||
count: count,
|
|
||||||
indicesIncludingEnd: indicesIncludingEnd,
|
|
||||||
file: file, line: line)
|
|
||||||
|
|
||||||
validator.validateForward(
|
|
||||||
testRandomAccess: testRandomAccess,
|
|
||||||
expectedCount: expectedCount)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension IndexValidator where C: BidirectionalCollection {
|
|
||||||
func validate(
|
|
||||||
_ collection: C, expectedCount: Int? = nil,
|
|
||||||
file: StaticString = #file, line: UInt = #line
|
|
||||||
) {
|
|
||||||
let indicesIncludingEnd = self.indicesIncludingEnd(collection)
|
|
||||||
let count = indicesIncludingEnd.count - 1
|
|
||||||
|
|
||||||
let validator = Validator(
|
|
||||||
collection: collection,
|
|
||||||
count: count,
|
|
||||||
indicesIncludingEnd: indicesIncludingEnd,
|
|
||||||
file: file, line: line)
|
|
||||||
|
|
||||||
validator.validateForward(
|
|
||||||
testRandomAccess: testRandomAccess,
|
|
||||||
expectedCount: expectedCount)
|
|
||||||
validator.validateBackward(testRandomAccess: testRandomAccess)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension IndexValidator.Validator {
|
|
||||||
func validateForward(testRandomAccess: Bool, expectedCount: Int?) {
|
|
||||||
if let expectedCount = expectedCount {
|
|
||||||
XCTAssertEqual(
|
|
||||||
expectedCount, count, "Count mismatch", file: file, line: line)
|
|
||||||
}
|
|
||||||
|
|
||||||
XCTAssertEqual(
|
XCTAssertEqual(
|
||||||
collection.count, count,
|
c.count, count,
|
||||||
"Count mismatch",
|
"Count mismatch",
|
||||||
file: file, line: line)
|
file: file, line: line)
|
||||||
XCTAssertEqual(
|
XCTAssertEqual(
|
||||||
collection.isEmpty, count == 0,
|
c.isEmpty, count == 0,
|
||||||
"Emptiness mismatch",
|
"Emptiness mismatch",
|
||||||
file: file, line: line)
|
file: file, line: line)
|
||||||
XCTAssertEqual(
|
XCTAssertEqual(
|
||||||
collection.startIndex, indicesIncludingEnd.first,
|
c.startIndex, indicesIncludingEnd.first,
|
||||||
"`startIndex` does not equal the first index",
|
"`startIndex` does not equal the first index",
|
||||||
file: file, line: line)
|
file: file, line: line)
|
||||||
XCTAssertEqual(
|
XCTAssertEqual(
|
||||||
collection.endIndex, indicesIncludingEnd.last,
|
c.endIndex, indicesIncludingEnd.last,
|
||||||
"`endIndex` does not equal the last index",
|
"`endIndex` does not equal the last index",
|
||||||
file: file, line: line)
|
file: file, line: line)
|
||||||
|
|
||||||
validateIndexAfter()
|
// `index(after:)`
|
||||||
validateIndices()
|
do {
|
||||||
validateIndexComparisons()
|
var index = c.startIndex
|
||||||
|
|
||||||
if testRandomAccess {
|
for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() {
|
||||||
validateDistanceFromTo()
|
c.formIndex(after: &index)
|
||||||
validateIndexOffsetBy()
|
XCTAssertEqual(
|
||||||
validateIndexOffsetByLimitedBy()
|
index, expected,
|
||||||
|
"""
|
||||||
|
`startIndex` incremented \(offset) times does not equal index at \
|
||||||
|
offset \(offset)
|
||||||
|
""",
|
||||||
|
file: file, line: line)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
// `index(before:)`
|
||||||
func validateIndexAfter() {
|
do {
|
||||||
var index = collection.startIndex
|
var index = c.endIndex
|
||||||
|
|
||||||
for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() {
|
for (offset, expected) in indicesIncludingEnd.enumerated().dropLast().reversed() {
|
||||||
collection.formIndex(after: &index)
|
c.formIndex(before: &index)
|
||||||
XCTAssertEqual(
|
XCTAssertEqual(
|
||||||
index, expected,
|
index, expected,
|
||||||
"""
|
"""
|
||||||
`startIndex` incremented \(offset) times does not equal index at \
|
`endIndex` decremented \(count - offset) times does not equal index \
|
||||||
offset \(offset)
|
at offset \(offset)
|
||||||
""",
|
""",
|
||||||
file: file, line: line)
|
file: file, line: line)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
// `indices`
|
||||||
func validateIndices() {
|
XCTAssertEqual(c.indices.count, count)
|
||||||
XCTAssertEqual(collection.indices.count, count)
|
for (offset, index) in c.indices.enumerated() {
|
||||||
for (offset, index) in collection.indices.enumerated() {
|
|
||||||
XCTAssertEqual(
|
XCTAssertEqual(
|
||||||
index, indicesIncludingEnd[offset],
|
index, indicesIncludingEnd[offset],
|
||||||
"Index mismatch at offset \(offset) in `indices`",
|
"Index mismatch at offset \(offset) in `indices`",
|
||||||
file: file, line: line)
|
file: file, line: line)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
// index comparison
|
||||||
func validateIndexComparisons() {
|
|
||||||
for (offsetA, a) in indicesIncludingEnd.enumerated() {
|
for (offsetA, a) in indicesIncludingEnd.enumerated() {
|
||||||
XCTAssertEqual(
|
XCTAssertEqual(
|
||||||
a, a,
|
a, a,
|
||||||
@@ -334,7 +263,7 @@ extension IndexValidator.Validator {
|
|||||||
a < a,
|
a < a,
|
||||||
"Index at offset \(offsetA) is less than itself",
|
"Index at offset \(offsetA) is less than itself",
|
||||||
file: file, line: line)
|
file: file, line: line)
|
||||||
|
|
||||||
for (offsetB, b) in indicesIncludingEnd[..<offsetA].enumerated() {
|
for (offsetB, b) in indicesIncludingEnd[..<offsetA].enumerated() {
|
||||||
XCTAssertNotEqual(
|
XCTAssertNotEqual(
|
||||||
a, b,
|
a, b,
|
||||||
@@ -348,14 +277,21 @@ extension IndexValidator.Validator {
|
|||||||
file: file, line: line)
|
file: file, line: line)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
// `index(_:offsetBy:)` and `distance(from:to:)`
|
||||||
func validateDistanceFromTo() {
|
|
||||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
||||||
for (endOffset, end) in indicesIncludingEnd.enumerated().dropFirst(startOffset) {
|
for (endOffset, end) in indicesIncludingEnd.enumerated() {
|
||||||
let distance = endOffset - startOffset
|
let distance = endOffset - startOffset
|
||||||
|
|
||||||
XCTAssertEqual(
|
XCTAssertEqual(
|
||||||
collection.distance(from: start, to: end), distance,
|
c.index(start, offsetBy: distance), end,
|
||||||
|
"""
|
||||||
|
Index at offset \(startOffset) offset by \(distance) does not equal \
|
||||||
|
index at offset \(endOffset)
|
||||||
|
""",
|
||||||
|
file: file, line: line)
|
||||||
|
XCTAssertEqual(
|
||||||
|
c.distance(from: start, to: end), distance,
|
||||||
"""
|
"""
|
||||||
Distance from index at offset \(startOffset) to index at offset \
|
Distance from index at offset \(startOffset) to index at offset \
|
||||||
\(endOffset) does not equal \(distance)
|
\(endOffset) does not equal \(distance)
|
||||||
@@ -363,35 +299,19 @@ extension IndexValidator.Validator {
|
|||||||
file: file, line: line)
|
file: file, line: line)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
// `index(_:offsetBy:limitedBy:)`
|
||||||
func validateIndexOffsetBy() {
|
|
||||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
|
||||||
for (endOffset, end) in indicesIncludingEnd.enumerated().dropFirst(startOffset) {
|
|
||||||
let distance = endOffset - startOffset
|
|
||||||
XCTAssertEqual(
|
|
||||||
collection.index(start, offsetBy: distance), end,
|
|
||||||
"""
|
|
||||||
Index at offset \(startOffset) offset by \(distance) does not \
|
|
||||||
equal index at offset \(endOffset)
|
|
||||||
""",
|
|
||||||
file: file, line: line)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateIndexOffsetByLimitedBy() {
|
|
||||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
||||||
for (limitOffset, limit) in indicesIncludingEnd.enumerated() {
|
for (limitOffset, limit) in indicesIncludingEnd.enumerated() {
|
||||||
// verifies that the target index corresponding to each offset in
|
// verifies that the target index corresponding to each offset in
|
||||||
// `range` can or cannot be reached from `start` using
|
// `range` can or cannot be reached from `start` using
|
||||||
// `chain.index(start, offsetBy: _, limitedBy: limit)`, depending on
|
// `chain.index(start, offsetBy: _, limitedBy: limit)`, depending on the
|
||||||
// the value of `pastLimit`
|
// value of `pastLimit`
|
||||||
func checkTargetRange(_ range: ClosedRange<Int>, pastLimit: Bool) {
|
func checkTargetRange(_ range: ClosedRange<Int>, pastLimit: Bool) {
|
||||||
for targetOffset in range {
|
for targetOffset in range {
|
||||||
let distance = targetOffset - startOffset
|
let distance = targetOffset - startOffset
|
||||||
let end = collection.index(start, offsetBy: distance, limitedBy: limit)
|
let end = c.index(start, offsetBy: distance, limitedBy: limit)
|
||||||
|
|
||||||
if pastLimit {
|
if pastLimit {
|
||||||
XCTAssertNil(
|
XCTAssertNil(
|
||||||
end,
|
end,
|
||||||
@@ -412,7 +332,8 @@ extension IndexValidator.Validator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// forward offsets
|
||||||
if limit >= start {
|
if limit >= start {
|
||||||
// the limit has an effect
|
// the limit has an effect
|
||||||
checkTargetRange(startOffset...limitOffset, pastLimit: false)
|
checkTargetRange(startOffset...limitOffset, pastLimit: false)
|
||||||
@@ -421,100 +342,8 @@ extension IndexValidator.Validator {
|
|||||||
// the limit has no effect
|
// the limit has no effect
|
||||||
checkTargetRange(startOffset...count, pastLimit: false)
|
checkTargetRange(startOffset...count, pastLimit: false)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension IndexValidator.Validator where C: BidirectionalCollection {
|
// backward offsets
|
||||||
func validateBackward(testRandomAccess: Bool) {
|
|
||||||
validateIndexBefore()
|
|
||||||
|
|
||||||
if testRandomAccess {
|
|
||||||
validateDistanceFromTo()
|
|
||||||
validateIndexOffsetBy()
|
|
||||||
validateIndexOffsetByLimitedBy()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateIndexBefore() {
|
|
||||||
var index = collection.endIndex
|
|
||||||
|
|
||||||
for (offset, expected) in indicesIncludingEnd.enumerated().dropLast().reversed() {
|
|
||||||
collection.formIndex(before: &index)
|
|
||||||
XCTAssertEqual(
|
|
||||||
index, expected,
|
|
||||||
"""
|
|
||||||
`endIndex` decremented \(count - offset) times does not equal index \
|
|
||||||
at offset \(offset)
|
|
||||||
""",
|
|
||||||
file: file, line: line)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateDistanceFromTo() {
|
|
||||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
|
||||||
for (endOffset, end) in indicesIncludingEnd.enumerated().prefix(startOffset) {
|
|
||||||
let distance = endOffset - startOffset
|
|
||||||
XCTAssertEqual(
|
|
||||||
collection.distance(from: start, to: end), distance,
|
|
||||||
"""
|
|
||||||
Distance from index at offset \(startOffset) to index at offset \
|
|
||||||
\(endOffset) does not equal \(distance)
|
|
||||||
""",
|
|
||||||
file: file, line: line)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateIndexOffsetBy() {
|
|
||||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
|
||||||
for (endOffset, end) in indicesIncludingEnd.enumerated().prefix(startOffset) {
|
|
||||||
let distance = endOffset - startOffset
|
|
||||||
XCTAssertEqual(
|
|
||||||
collection.index(start, offsetBy: distance), end,
|
|
||||||
"""
|
|
||||||
Index at offset \(startOffset) offset by \(distance) does not \
|
|
||||||
equal index at offset \(endOffset)
|
|
||||||
""",
|
|
||||||
file: file, line: line)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateIndexOffsetByLimitedBy() {
|
|
||||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
|
||||||
for (limitOffset, limit) in indicesIncludingEnd.enumerated() {
|
|
||||||
// verifies that the target index corresponding to each offset in
|
|
||||||
// `range` can or cannot be reached from `start` using
|
|
||||||
// `chain.index(start, offsetBy: _, limitedBy: limit)`, depending on
|
|
||||||
// the value of `pastLimit`
|
|
||||||
func checkTargetRange(_ range: ClosedRange<Int>, pastLimit: Bool) {
|
|
||||||
for targetOffset in range {
|
|
||||||
let distance = targetOffset - startOffset
|
|
||||||
let end = collection.index(start, offsetBy: distance, limitedBy: limit)
|
|
||||||
|
|
||||||
if pastLimit {
|
|
||||||
XCTAssertNil(
|
|
||||||
end,
|
|
||||||
"""
|
|
||||||
Index at offset \(startOffset) offset by \(distance) limited \
|
|
||||||
by index at offset \(limitOffset) does not equal `nil`
|
|
||||||
""",
|
|
||||||
file: file, line: line)
|
|
||||||
} else {
|
|
||||||
XCTAssertEqual(
|
|
||||||
end, indicesIncludingEnd[targetOffset],
|
|
||||||
"""
|
|
||||||
Index at offset \(startOffset) offset by \(distance) limited \
|
|
||||||
by index at offset \(limitOffset) does not equal index at \
|
|
||||||
offset \(targetOffset)
|
|
||||||
""",
|
|
||||||
file: file, line: line)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if limit <= start {
|
if limit <= start {
|
||||||
// the limit has an effect
|
// the limit has an effect
|
||||||
checkTargetRange(limitOffset...startOffset, pastLimit: false)
|
checkTargetRange(limitOffset...startOffset, pastLimit: false)
|
||||||
|
|||||||
@@ -13,12 +13,12 @@ import Algorithms
|
|||||||
import XCTest
|
import XCTest
|
||||||
|
|
||||||
final class TrimTests: XCTestCase {
|
final class TrimTests: XCTestCase {
|
||||||
|
|
||||||
func testEmpty() {
|
func testEmpty() {
|
||||||
let results_empty = ([] as [Int]).trimming { $0.isMultiple(of: 2) }
|
let results_empty = ([] as [Int]).trimming { $0.isMultiple(of: 2) }
|
||||||
XCTAssertEqual(results_empty, [])
|
XCTAssertEqual(results_empty, [])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testNoMatch() {
|
func testNoMatch() {
|
||||||
// No match (nothing trimmed).
|
// No match (nothing trimmed).
|
||||||
let results_nomatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming {
|
let results_nomatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming {
|
||||||
@@ -26,83 +26,34 @@ final class TrimTests: XCTestCase {
|
|||||||
}
|
}
|
||||||
XCTAssertEqual(results_nomatch, [1, 3, 5, 7, 9, 11, 13, 15])
|
XCTAssertEqual(results_nomatch, [1, 3, 5, 7, 9, 11, 13, 15])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testNoTailMatch() {
|
func testNoTailMatch() {
|
||||||
// No tail match (only trim head).
|
// No tail match (only trim head).
|
||||||
let results_notailmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0 < 10 }
|
let results_notailmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0 < 10 }
|
||||||
XCTAssertEqual(results_notailmatch, [11, 13, 15])
|
XCTAssertEqual(results_notailmatch, [11, 13, 15])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testNoHeadMatch() {
|
func testNoHeadMatch() {
|
||||||
// No head match (only trim tail).
|
// No head match (only trim tail).
|
||||||
let results_noheadmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0 > 10 }
|
let results_noheadmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0 > 10 }
|
||||||
XCTAssertEqual(results_noheadmatch, [1, 3, 5, 7, 9])
|
XCTAssertEqual(results_noheadmatch, [1, 3, 5, 7, 9])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBothEndsMatch() {
|
func testBothEndsMatch() {
|
||||||
// Both ends match, some string of >1 elements do not (return that string).
|
// Both ends match, some string of >1 elements do not (return that string).
|
||||||
let results = [2, 10, 11, 15, 20, 21, 100].trimming { $0.isMultiple(of: 2) }
|
let results = [2, 10, 11, 15, 20, 21, 100].trimming { $0.isMultiple(of: 2) }
|
||||||
XCTAssertEqual(results, [11, 15, 20, 21])
|
XCTAssertEqual(results, [11, 15, 20, 21])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testEverythingMatches() {
|
func testEverythingMatches() {
|
||||||
// Everything matches (trim everything).
|
// Everything matches (trim everything).
|
||||||
let results_allmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { _ in true }
|
let results_allmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { _ in true }
|
||||||
XCTAssertEqual(results_allmatch, [])
|
XCTAssertEqual(results_allmatch, [])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testEverythingButOneMatches() {
|
func testEverythingButOneMatches() {
|
||||||
// Both ends match, one element does not (trim all except that element).
|
// Both ends match, one element does not (trim all except that element).
|
||||||
let results_one = [2, 10, 12, 15, 20, 100].trimming { $0.isMultiple(of: 2) }
|
let results_one = [2, 10, 12, 15, 20, 100].trimming { $0.isMultiple(of: 2) }
|
||||||
XCTAssertEqual(results_one, [15])
|
XCTAssertEqual(results_one, [15])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testTrimmingPrefix() {
|
|
||||||
let results = [2, 10, 12, 15, 20, 100].trimmingPrefix { $0.isMultiple(of: 2) }
|
|
||||||
XCTAssertEqual(results, [15, 20, 100])
|
|
||||||
}
|
|
||||||
|
|
||||||
func testTrimmingSuffix() {
|
|
||||||
let results = [2, 10, 12, 15, 20, 100].trimmingSuffix { $0.isMultiple(of: 2) }
|
|
||||||
XCTAssertEqual(results, [2, 10, 12, 15])
|
|
||||||
}
|
|
||||||
|
|
||||||
// Self == Self.Subsequence
|
|
||||||
func testTrimNoAmbiguity() {
|
|
||||||
var values = [2, 10, 12, 15, 20, 100] as ArraySlice
|
|
||||||
values.trim { $0.isMultiple(of: 2) }
|
|
||||||
XCTAssertEqual(values, [15])
|
|
||||||
}
|
|
||||||
|
|
||||||
// Self == Self.Subsequence
|
|
||||||
func testTrimPrefixNoAmbiguity() {
|
|
||||||
var values = [2, 10, 12, 15, 20, 100] as ArraySlice
|
|
||||||
values.trimPrefix { $0.isMultiple(of: 2) }
|
|
||||||
XCTAssertEqual(values, [15, 20, 100])
|
|
||||||
}
|
|
||||||
|
|
||||||
// Self == Self.Subsequence
|
|
||||||
func testTrimSuffixNoAmbiguity() {
|
|
||||||
var values = [2, 10, 12, 15, 20, 100] as ArraySlice
|
|
||||||
values.trimSuffix { $0.isMultiple(of: 2) }
|
|
||||||
XCTAssertEqual(values, [2, 10, 12, 15])
|
|
||||||
}
|
|
||||||
|
|
||||||
func testTrimRangeReplaceable() {
|
|
||||||
var values = [2, 10, 12, 15, 20, 100]
|
|
||||||
values.trim { $0.isMultiple(of: 2) }
|
|
||||||
XCTAssertEqual(values, [15])
|
|
||||||
}
|
|
||||||
|
|
||||||
func testTrimPrefixRangeReplaceable() {
|
|
||||||
var values = [2, 10, 12, 15, 20, 100]
|
|
||||||
values.trimPrefix { $0.isMultiple(of: 2) }
|
|
||||||
XCTAssertEqual(values, [15, 20, 100])
|
|
||||||
}
|
|
||||||
|
|
||||||
func testTrimSuffixRangeReplaceable() {
|
|
||||||
var values = [2, 10, 12, 15, 20, 100]
|
|
||||||
values.trimSuffix { $0.isMultiple(of: 2) }
|
|
||||||
XCTAssertEqual(values, [2, 10, 12, 15])
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -9,12 +9,12 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
|
||||||
import Algorithms
|
import Algorithms
|
||||||
|
import XCTest
|
||||||
|
|
||||||
final class UniquePermutationsTests: XCTestCase {
|
final class UniquePermutationsTests: XCTestCase {
|
||||||
static let numbers = [1, 1, 1, 2, 3]
|
static let numbers = [1, 1, 1, 2, 3]
|
||||||
|
|
||||||
static let numbersPermutations: [[[Int]]] = [
|
static let numbersPermutations: [[[Int]]] = [
|
||||||
// k = 0
|
// k = 0
|
||||||
[[]],
|
[[]],
|
||||||
@@ -23,26 +23,32 @@ final class UniquePermutationsTests: XCTestCase {
|
|||||||
// 2
|
// 2
|
||||||
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]],
|
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]],
|
||||||
// 3
|
// 3
|
||||||
[[1, 1, 1], [1, 1, 2], [1, 1, 3],
|
[
|
||||||
[1, 2, 1], [1, 2, 3], [1, 3, 1], [1, 3, 2],
|
[1, 1, 1], [1, 1, 2], [1, 1, 3],
|
||||||
[2, 1, 1], [2, 1, 3], [2, 3, 1],
|
[1, 2, 1], [1, 2, 3], [1, 3, 1], [1, 3, 2],
|
||||||
[3, 1, 1], [3, 1, 2], [3, 2, 1]],
|
[2, 1, 1], [2, 1, 3], [2, 3, 1],
|
||||||
|
[3, 1, 1], [3, 1, 2], [3, 2, 1],
|
||||||
|
],
|
||||||
// 4
|
// 4
|
||||||
[[1, 1, 1, 2], [1, 1, 1, 3],
|
[
|
||||||
[1, 1, 2, 1], [1, 1, 2, 3],
|
[1, 1, 1, 2], [1, 1, 1, 3],
|
||||||
[1, 1, 3, 1], [1, 1, 3, 2],
|
[1, 1, 2, 1], [1, 1, 2, 3],
|
||||||
[1, 2, 1, 1], [1, 2, 1, 3], [1, 2, 3, 1],
|
[1, 1, 3, 1], [1, 1, 3, 2],
|
||||||
[1, 3, 1, 1], [1, 3, 1, 2], [1, 3, 2, 1],
|
[1, 2, 1, 1], [1, 2, 1, 3], [1, 2, 3, 1],
|
||||||
[2, 1, 1, 1], [2, 1, 1, 3], [2, 1, 3, 1], [2, 3, 1, 1],
|
[1, 3, 1, 1], [1, 3, 1, 2], [1, 3, 2, 1],
|
||||||
[3, 1, 1, 1], [3, 1, 1, 2], [3, 1, 2, 1], [3, 2, 1, 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
|
// 5
|
||||||
[[1, 1, 1, 2, 3], [1, 1, 1, 3, 2],
|
[
|
||||||
[1, 1, 2, 1, 3], [1, 1, 2, 3, 1],
|
[1, 1, 1, 2, 3], [1, 1, 1, 3, 2],
|
||||||
[1, 1, 3, 1, 2], [1, 1, 3, 2, 1],
|
[1, 1, 2, 1, 3], [1, 1, 2, 3, 1],
|
||||||
[1, 2, 1, 1, 3], [1, 2, 1, 3, 1], [1, 2, 3, 1, 1],
|
[1, 1, 3, 1, 2], [1, 1, 3, 2, 1],
|
||||||
[1, 3, 1, 1, 2], [1, 3, 1, 2, 1], [1, 3, 2, 1, 1],
|
[1, 2, 1, 1, 3], [1, 2, 1, 3, 1], [1, 2, 3, 1, 1],
|
||||||
[2, 1, 1, 1, 3], [2, 1, 1, 3, 1], [2, 1, 3, 1, 1], [2, 3, 1, 1, 1],
|
[1, 3, 1, 1, 2], [1, 3, 1, 2, 1], [1, 3, 2, 1, 1],
|
||||||
[3, 1, 1, 1, 2], [3, 1, 1, 2, 1], [3, 1, 2, 1, 1], [3, 2, 1, 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],
|
||||||
|
],
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,26 +60,26 @@ extension UniquePermutationsTests {
|
|||||||
XCTAssertEqualSequences(
|
XCTAssertEqualSequences(
|
||||||
([] as [Int]).uniquePermutations(ofCount: 1...3), [])
|
([] as [Int]).uniquePermutations(ofCount: 1...3), [])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testSingleCounts() {
|
func testSingleCounts() {
|
||||||
for (k, expectation) in Self.numbersPermutations.enumerated() {
|
for (k, expectation) in Self.numbersPermutations.enumerated() {
|
||||||
XCTAssertEqualSequences(
|
XCTAssertEqualSequences(
|
||||||
expectation,
|
expectation,
|
||||||
Self.numbers.uniquePermutations(ofCount: k))
|
Self.numbers.uniquePermutations(ofCount: k))
|
||||||
}
|
}
|
||||||
|
|
||||||
XCTAssertEqualSequences(
|
XCTAssertEqualSequences(
|
||||||
Self.numbersPermutations[5],
|
Self.numbersPermutations[5],
|
||||||
Self.numbers.uniquePermutations())
|
Self.numbers.uniquePermutations())
|
||||||
}
|
}
|
||||||
|
|
||||||
func testRanges() {
|
func testRanges() {
|
||||||
for lower in Self.numbersPermutations.indices {
|
for lower in Self.numbersPermutations.indices {
|
||||||
// upper bounded
|
// upper bounded
|
||||||
XCTAssertEqualSequences(
|
XCTAssertEqualSequences(
|
||||||
Self.numbersPermutations[...lower].joined(),
|
Self.numbersPermutations[...lower].joined(),
|
||||||
Self.numbers.uniquePermutations(ofCount: ...lower))
|
Self.numbers.uniquePermutations(ofCount: ...lower))
|
||||||
|
|
||||||
// lower bounded
|
// lower bounded
|
||||||
XCTAssertEqualSequences(
|
XCTAssertEqualSequences(
|
||||||
Self.numbersPermutations[lower...].joined(),
|
Self.numbersPermutations[lower...].joined(),
|
||||||
@@ -91,11 +97,11 @@ extension UniquePermutationsTests {
|
|||||||
extension UniquePermutationsTests {
|
extension UniquePermutationsTests {
|
||||||
private final class IntBox: Hashable {
|
private final class IntBox: Hashable {
|
||||||
var value: Int
|
var value: Int
|
||||||
|
|
||||||
init(_ value: Int) {
|
init(_ value: Int) {
|
||||||
self.value = value
|
self.value = value
|
||||||
}
|
}
|
||||||
|
|
||||||
static func == (lhs: IntBox, rhs: IntBox) -> Bool {
|
static func == (lhs: IntBox, rhs: IntBox) -> Bool {
|
||||||
lhs.value == rhs.value
|
lhs.value == rhs.value
|
||||||
}
|
}
|
||||||
@@ -115,7 +121,7 @@ extension UniquePermutationsTests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func testLaziness() {
|
func testLaziness() {
|
||||||
XCTAssertLazySequence("ABCD".lazy.uniquePermutations())
|
XCTAssertLazySequence("ABCD".lazy.uniquePermutations())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,8 +9,8 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
|
||||||
import Algorithms
|
import Algorithms
|
||||||
|
import XCTest
|
||||||
|
|
||||||
final class UniqueTests: XCTestCase {
|
final class UniqueTests: XCTestCase {
|
||||||
func testUnique() {
|
func testUnique() {
|
||||||
@@ -18,26 +18,26 @@ final class UniqueTests: XCTestCase {
|
|||||||
let b = a.uniqued()
|
let b = a.uniqued()
|
||||||
XCTAssertEqual(b.sorted(), Set(a).sorted())
|
XCTAssertEqual(b.sorted(), Set(a).sorted())
|
||||||
XCTAssertEqual(10, Array(b).count)
|
XCTAssertEqual(10, Array(b).count)
|
||||||
|
|
||||||
let c: [Int] = []
|
let c: [Int] = []
|
||||||
XCTAssertEqualSequences(c.uniqued(), [])
|
XCTAssertEqualSequences(c.uniqued(), [])
|
||||||
|
|
||||||
let d = Array(repeating: 1, count: 10)
|
let d = Array(repeating: 1, count: 10)
|
||||||
XCTAssertEqualSequences(d.uniqued(), [1])
|
XCTAssertEqualSequences(d.uniqued(), [1])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testUniqueOn() {
|
func testUniqueOn() {
|
||||||
let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
|
let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
|
||||||
let b = a.uniqued(on: { $0.first })
|
let b = a.uniqued(on: { $0.first })
|
||||||
XCTAssertEqual(["Albemarle", "Brandywine"], b)
|
XCTAssertEqual(["Albemarle", "Brandywine"], b)
|
||||||
|
|
||||||
let c: [Int] = []
|
let c: [Int] = []
|
||||||
XCTAssertEqual(c.uniqued(on: { $0.bitWidth }), [])
|
XCTAssertEqual(c.uniqued(on: { $0.bitWidth }), [])
|
||||||
|
|
||||||
let d = Array(repeating: "Andromeda", count: 10)
|
let d = Array(repeating: "Andromeda", count: 10)
|
||||||
XCTAssertEqualSequences(d.uniqued(on: { $0.first }), ["Andromeda"])
|
XCTAssertEqualSequences(d.uniqued(on: { $0.first }), ["Andromeda"])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testLazyUniqueOn() {
|
func testLazyUniqueOn() {
|
||||||
let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
|
let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
|
||||||
let b = a.lazy.uniqued(on: { $0.first })
|
let b = a.lazy.uniqued(on: { $0.first })
|
||||||
@@ -46,7 +46,7 @@ final class UniqueTests: XCTestCase {
|
|||||||
|
|
||||||
let c: [Int] = []
|
let c: [Int] = []
|
||||||
XCTAssertEqualSequences(c.lazy.uniqued(on: { $0.bitWidth }), [])
|
XCTAssertEqualSequences(c.lazy.uniqued(on: { $0.bitWidth }), [])
|
||||||
|
|
||||||
let d = Array(repeating: "Andromeda", count: 10)
|
let d = Array(repeating: "Andromeda", count: 10)
|
||||||
XCTAssertEqualSequences(d.lazy.uniqued(on: { $0.first }), ["Andromeda"])
|
XCTAssertEqualSequences(d.lazy.uniqued(on: { $0.first }), ["Andromeda"])
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,9 +10,11 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
import XCTest
|
import XCTest
|
||||||
|
|
||||||
@testable import Algorithms
|
@testable import Algorithms
|
||||||
|
|
||||||
final class WindowsTests: XCTestCase {
|
final class windowsTests: XCTestCase {
|
||||||
|
|
||||||
func testWindowsOfString() {
|
func testWindowsOfString() {
|
||||||
let s = "swift"
|
let s = "swift"
|
||||||
let w = s.windows(ofCount: 2)
|
let w = s.windows(ofCount: 2)
|
||||||
@@ -26,56 +28,56 @@ final class WindowsTests: XCTestCase {
|
|||||||
w.formIndex(after: &i)
|
w.formIndex(after: &i)
|
||||||
XCTAssertEqualSequences(w[i], "ft")
|
XCTAssertEqualSequences(w[i], "ft")
|
||||||
|
|
||||||
// w.index(after: w.endIndex) // ← Precondition failed: windows index is out of range
|
// w.index(after: w.endIndex) // ← Precondition failed: windows index is out of range
|
||||||
// w.index(before: w.startIndex) // ← Precondition failed: windows index is out of range
|
// w.index(before: w.startIndex) // ← Precondition failed: windows index is out of range
|
||||||
// w.formIndex(after: &i); w[i] // ← Precondition failed: windows index is out of range
|
// w.formIndex(after: &i); w[i] // ← Precondition failed: windows index is out of range
|
||||||
}
|
}
|
||||||
|
|
||||||
func testWindowsOfRange() {
|
func testWindowsOfRange() {
|
||||||
let a = 0...100
|
let a = 0...100
|
||||||
|
|
||||||
XCTAssertTrue(a.windows(ofCount: 200).isEmpty)
|
XCTAssertTrue(a.windows(ofCount: 200).isEmpty)
|
||||||
|
|
||||||
let w = a.windows(ofCount: 10)
|
let w = a.windows(ofCount: 10)
|
||||||
|
|
||||||
XCTAssertEqualSequences(w.first!, 0..<10)
|
XCTAssertEqualSequences(w.first!, 0..<10)
|
||||||
XCTAssertEqualSequences(w.last!, 91..<101)
|
XCTAssertEqualSequences(w.last!, 91..<101)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testWindowsOfInt() {
|
func testWindowsOfInt() {
|
||||||
let a = [ 0, 1, 0, 1 ].windows(ofCount: 2)
|
let a = [0, 1, 0, 1].windows(ofCount: 2)
|
||||||
|
|
||||||
XCTAssertEqual(a.count, 3)
|
XCTAssertEqual(a.count, 3)
|
||||||
XCTAssertEqual(a.map { $0.reduce(0, +) }, [1, 1, 1])
|
XCTAssertEqual(a.map { $0.reduce(0, +) }, [1, 1, 1])
|
||||||
|
|
||||||
let a2 = [0, 1, 2, 3, 4, 5, 6].windows(ofCount: 3).map {
|
let a2 = [0, 1, 2, 3, 4, 5, 6].windows(ofCount: 3).map {
|
||||||
$0.reduce(0, +)
|
$0.reduce(0, +)
|
||||||
}.reduce(0, +)
|
}.reduce(0, +)
|
||||||
|
|
||||||
XCTAssertEqual(a2, 3 + 6 + 9 + 12 + 15)
|
XCTAssertEqual(a2, 3 + 6 + 9 + 12 + 15)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testWindowsCount() {
|
func testWindowsCount() {
|
||||||
let a = [0, 1, 2, 3, 4, 5]
|
let a = [0, 1, 2, 3, 4, 5]
|
||||||
XCTAssertEqual(a.windows(ofCount: 3).count, 4)
|
XCTAssertEqual(a.windows(ofCount: 3).count, 4)
|
||||||
|
|
||||||
let a2 = [0, 1, 2, 3, 4]
|
let a2 = [0, 1, 2, 3, 4]
|
||||||
XCTAssertEqual(a2.windows(ofCount: 6).count, 0)
|
XCTAssertEqual(a2.windows(ofCount: 6).count, 0)
|
||||||
|
|
||||||
let a3 = [Int]()
|
let a3 = [Int]()
|
||||||
XCTAssertEqual(a3.windows(ofCount: 2).count, 0)
|
XCTAssertEqual(a3.windows(ofCount: 2).count, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testWindowsSecondAndLast() {
|
func testWindowsSecondAndLast() {
|
||||||
let a = [0, 1, 2, 3, 4, 5]
|
let a = [0, 1, 2, 3, 4, 5]
|
||||||
let w = a.windows(ofCount: 4)
|
let w = a.windows(ofCount: 4)
|
||||||
let snd = w[w.index(after: w.startIndex)]
|
let snd = w[w.index(after: w.startIndex)]
|
||||||
XCTAssertEqualSequences(snd, [1, 2, 3, 4])
|
XCTAssertEqualSequences(snd, [1, 2, 3, 4])
|
||||||
|
|
||||||
let w2 = a.windows(ofCount: 3)
|
let w2 = a.windows(ofCount: 3)
|
||||||
XCTAssertEqualSequences(w2.last!, [3, 4, 5])
|
XCTAssertEqualSequences(w2.last!, [3, 4, 5])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testWindowsIndexAfterAndBefore() {
|
func testWindowsIndexAfterAndBefore() {
|
||||||
let a = [0, 1, 2, 3, 4, 5].windows(ofCount: 2)
|
let a = [0, 1, 2, 3, 4, 5].windows(ofCount: 2)
|
||||||
var i = a.startIndex
|
var i = a.startIndex
|
||||||
@@ -84,25 +86,24 @@ final class WindowsTests: XCTestCase {
|
|||||||
a.formIndex(before: &i)
|
a.formIndex(before: &i)
|
||||||
XCTAssertEqualSequences(a[i], [1, 2])
|
XCTAssertEqualSequences(a[i], [1, 2])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testWindowsIndexTraversals() {
|
func testWindowsIndexTraversals() {
|
||||||
let validator = IndexValidator<WindowsOfCountCollection<String>>(
|
validateIndexTraversals(
|
||||||
indicesIncludingEnd: { windows in
|
"".windows(ofCount: 1),
|
||||||
|
"a".windows(ofCount: 1),
|
||||||
|
"ab".windows(ofCount: 1),
|
||||||
|
"abc".windows(ofCount: 1),
|
||||||
|
"".windows(ofCount: 3),
|
||||||
|
"a".windows(ofCount: 3),
|
||||||
|
"abc".windows(ofCount: 3),
|
||||||
|
"abcdefgh".windows(ofCount: 3),
|
||||||
|
indices: { windows in
|
||||||
let endIndex = windows.base.endIndex
|
let endIndex = windows.base.endIndex
|
||||||
let indices = windows.base.indices + [endIndex]
|
let indices = windows.base.indices + [endIndex]
|
||||||
return zip(indices, indices.dropFirst(windows.windowSize))
|
return zip(indices, indices.dropFirst(windows.size))
|
||||||
.map { .init(lowerBound: $0, upperBound: $1) }
|
.map { .init(lowerBound: $0, upperBound: $1) }
|
||||||
+ [.init(lowerBound: endIndex, upperBound: endIndex)]
|
+ [.init(lowerBound: endIndex, upperBound: endIndex)]
|
||||||
})
|
})
|
||||||
|
|
||||||
validator.validate("".windows(ofCount: 1), expectedCount: 0)
|
|
||||||
validator.validate("a".windows(ofCount: 1), expectedCount: 1)
|
|
||||||
validator.validate("ab".windows(ofCount: 1), expectedCount: 2)
|
|
||||||
validator.validate("abc".windows(ofCount: 1), expectedCount: 3)
|
|
||||||
validator.validate("".windows(ofCount: 3), expectedCount: 0)
|
|
||||||
validator.validate("a".windows(ofCount: 3), expectedCount: 0)
|
|
||||||
validator.validate("abc".windows(ofCount: 3), expectedCount: 1)
|
|
||||||
validator.validate("abcdefgh".windows(ofCount: 3), expectedCount: 6)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func testWindowsLazy() {
|
func testWindowsLazy() {
|
||||||
|
|||||||
Reference in new issue
Block a user