mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-22 04:10:39 +00:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
993b950250 | ||
|
|
04d91803a2 | ||
|
|
36bcc5581b | ||
|
|
31d600a4f1 | ||
|
|
0e44ceb7bb | ||
|
|
78dd4b5b93 | ||
|
|
abc5559ef6 | ||
|
|
bcdbac800a | ||
|
|
718220d0f8 | ||
|
|
551b4af927 | ||
|
|
dca25448e0 | ||
|
|
1639c1e2c3 | ||
|
|
a61c3db4fb | ||
|
|
198eee004e | ||
|
|
4cca4895cc | ||
|
|
001247f8a5 | ||
|
|
0065c60a22 | ||
|
|
5cde0b1b67 | ||
|
|
220649e999 | ||
|
|
b171b81577 | ||
|
|
e652f01949 | ||
|
|
9783c1be91 |
No files matched your search
@@ -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
|
||||
}
|
||||
+72
-2
@@ -8,7 +8,7 @@ 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.0.1")` as the requirement.
|
||||
`.upToNextMinor(from: "0.1.0")` as the requirement.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
@@ -16,6 +16,59 @@ package updates, you can specify your package dependency using
|
||||
|
||||
---
|
||||
|
||||
## [0.1.0] - 2021-04-13
|
||||
|
||||
### Additions
|
||||
|
||||
- The `compacted()` method lazily finds the non-`nil` elements of a sequence or
|
||||
collection ([#112]).
|
||||
|
||||
### Changes
|
||||
|
||||
- The `uniqued()` method now lazily computes the unique elements of a sequence
|
||||
or a collection ([#71]). Pass this resulting sequence to an `Array`
|
||||
initializer to recover the behavior of the previous release.
|
||||
- Calling `cycled(times:)` now returns a new `FiniteCycle` type, which has the
|
||||
same conformances as its underlying collection ([#106]).
|
||||
- The base collections of the sequence and collection wrapper types are no
|
||||
longer public ([#85], [#125]), and the wrapper types no longer conform to the
|
||||
`Equatable` or `Hashable` protocols ([#124]). If you need those conformances,
|
||||
convert the wrapper type to an `Array` or other collection currrency type
|
||||
before storing. Please file an issue if these changes pose a problem for your
|
||||
use case.
|
||||
|
||||
The 0.1.0 release includes contributions from [LemonSpike], [LucianoPAlmeida],
|
||||
[natecook1000], and [timvermeulen]. Thank you!
|
||||
|
||||
---
|
||||
|
||||
## [0.0.4] - 2021-03-29
|
||||
|
||||
### Additions
|
||||
|
||||
More new algorithms to join the party:
|
||||
|
||||
- A lazy version of the standard library's two `split` methods. ([#78])
|
||||
- `firstNonNil(_:)` returns the first non-`nil` element from an
|
||||
optional-generating transform. ([#31])
|
||||
- `uniquePermutations()` skips duplicates when generating permutations of a
|
||||
collection. ([#91])
|
||||
- The `reductions` methods return all the in-between states of reducing a
|
||||
sequence or collection. ([#46])
|
||||
|
||||
### Fixes
|
||||
|
||||
- Methods and computed properties are more consistently marked as inlinable,
|
||||
resolving a performance regression.
|
||||
- The `Stride` type now efficiently calculates distances between positions,
|
||||
supported by the underlying collection.
|
||||
- Better test coverage and improved diagnostics for comparing sequences.
|
||||
- Fixed links and improved documentation.
|
||||
|
||||
The 0.0.4 release includes contributions from [bjhomer], [danielctull],
|
||||
[hashemi], [karwa], [kylemacomber], [LucianoPAlmeida], [mdznr], [natecook1000],
|
||||
[ollieatkinson], [Qata], [timvermeulen], and [toddthomas]. Thank you!
|
||||
|
||||
## [0.0.3] - 2021-02-26
|
||||
|
||||
### Additions
|
||||
@@ -96,7 +149,9 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
|
||||
<!-- Link references for releases -->
|
||||
|
||||
[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.0.3...HEAD
|
||||
[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.1.0...HEAD
|
||||
[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.3]: https://github.com/apple/swift-algorithms/compare/0.0.2...0.0.3
|
||||
[0.0.2]: https://github.com/apple/swift-algorithms/compare/0.0.1...0.0.2
|
||||
[0.0.1]: https://github.com/apple/swift-algorithms/releases/tag/0.0.1
|
||||
@@ -107,24 +162,37 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
[#9]: https://github.com/apple/swift-algorithms/pull/9
|
||||
[#20]: https://github.com/apple/swift-algorithms/pull/20
|
||||
[#24]: https://github.com/apple/swift-algorithms/pull/24
|
||||
[#31]: https://github.com/apple/swift-algorithms/pull/31
|
||||
[#35]: https://github.com/apple/swift-algorithms/pull/35
|
||||
[#46]: https://github.com/apple/swift-algorithms/pull/46
|
||||
[#51]: https://github.com/apple/swift-algorithms/pull/51
|
||||
[#54]: https://github.com/apple/swift-algorithms/pull/54
|
||||
[#56]: https://github.com/apple/swift-algorithms/pull/56
|
||||
[#65]: https://github.com/apple/swift-algorithms/pull/65
|
||||
[#71]: https://github.com/apple/swift-algorithms/pull/71
|
||||
[#77]: https://github.com/apple/swift-algorithms/pull/77
|
||||
[#78]: https://github.com/apple/swift-algorithms/pull/78
|
||||
[#85]: https://github.com/apple/swift-algorithms/pull/85
|
||||
[#91]: https://github.com/apple/swift-algorithms/pull/91
|
||||
[#106]: https://github.com/apple/swift-algorithms/pull/106
|
||||
[#112]: https://github.com/apple/swift-algorithms/pull/112
|
||||
[#124]: https://github.com/apple/swift-algorithms/pull/124
|
||||
[#125]: https://github.com/apple/swift-algorithms/pull/125
|
||||
|
||||
<!-- Link references for contributors -->
|
||||
|
||||
[AustinConlon]: https://github.com/apple/swift-algorithms/commits?author=AustinConlon
|
||||
[benrimmington]: https://github.com/apple/swift-algorithms/commits?author=benrimmington
|
||||
[bjhomer]: https://github.com/apple/swift-algorithms/commits?author=bjhomer
|
||||
[danielctull]: https://github.com/apple/swift-algorithms/commits?author=danielctull
|
||||
[dhruvshah8]: https://github.com/apple/swift-algorithms/commits?author=dhruvshah8
|
||||
[egorzhdan]: https://github.com/apple/swift-algorithms/commits?author=egorzhdan
|
||||
[hashemi]: https://github.com/apple/swift-algorithms/commits?author=hashemi
|
||||
[IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen
|
||||
[iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7
|
||||
[karwa]: https://github.com/apple/swift-algorithms/commits?author=karwa
|
||||
[kylemacomber]: https://github.com/apple/swift-algorithms/commits?author=kylemacomber
|
||||
[LemonSpike]: https://github.com/apple/swift-algorithms/commits?author=LemonSpike
|
||||
[LucianoPAlmeida]: https://github.com/apple/swift-algorithms/commits?author=LucianoPAlmeida
|
||||
[markuswntr]: https://github.com/apple/swift-algorithms/commits?author=markuswntr
|
||||
[mdznr]: https://github.com/apple/swift-algorithms/commits?author=mdznr
|
||||
@@ -133,6 +201,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
[nordicio]: https://github.com/apple/swift-algorithms/commits?author=nordicio
|
||||
[ollieatkinson]: https://github.com/apple/swift-algorithms/commits?author=ollieatkinson
|
||||
[pmtao]: https://github.com/apple/swift-algorithms/commits?author=pmtao
|
||||
[Qata]: https://github.com/apple/swift-algorithms/commits?author=Qata
|
||||
[rakaramos]: https://github.com/apple/swift-algorithms/commits?author=rakaramos
|
||||
[rockbruno]: https://github.com/apple/swift-algorithms/commits?author=rockbruno
|
||||
[Roshankumar350]: https://github.com/apple/swift-algorithms/commits?author=Roshankumar350
|
||||
@@ -140,3 +209,4 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
[sidepelican]: https://github.com/apple/swift-algorithms/commits?author=sidepelican
|
||||
[stephentyrone]: https://github.com/apple/swift-algorithms/commits?author=stephentyrone
|
||||
[timvermeulen]: https://github.com/apple/swift-algorithms/commits?author=timvermeulen
|
||||
[toddthomas]: https://github.com/apple/swift-algorithms/commits?author=toddthomas
|
||||
+3
-3
@@ -76,15 +76,15 @@ extension Collection {
|
||||
extension LazyCollectionProtocol {
|
||||
public func chunked(
|
||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||
) -> LazyChunked<Elements>
|
||||
) -> Chunked<Elements>
|
||||
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: @escaping (Element) -> Subject
|
||||
) -> LazyChunked<Elements>
|
||||
) -> Chunked<Elements>
|
||||
}
|
||||
```
|
||||
|
||||
The `LazyChunked` type is bidirectional when the wrapped collection is
|
||||
The `Chunked` type is bidirectional when the wrapped collection is
|
||||
bidirectional.
|
||||
|
||||
### Complexity
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# Compacted
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Compacted.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/CompactedTests.swift)]
|
||||
|
||||
A convenience method that lazily flattens the `nil`s out of a sequence
|
||||
or collection.
|
||||
|
||||
The new method matches one of the most common uses of `compactMap`,
|
||||
which is to only remove `nil`s without transforming the elements
|
||||
(e.g. `collection.lazy.compactMap { $0 }`).
|
||||
|
||||
```swift
|
||||
let array: [Int?] = [10, nil, 30, nil, 2, 3, nil, 5]
|
||||
let withNoNils = array.compacted()
|
||||
// Array(withNoNils) == [10, 30, 2, 3, 5]
|
||||
```
|
||||
|
||||
The type returned by `compacted()` lazily computes the non-`nil` elements
|
||||
without requiring a user to provide a closure or use the `.lazy` property.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `compacted()` methods has two overloads:
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
|
||||
where Element == Unwrapped?
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
|
||||
where Element == Unwrapped?
|
||||
}
|
||||
```
|
||||
|
||||
The `Sequence` version of `compacted()` returns a `CompactedSequence` type,
|
||||
while the `Collection` version returns `CompactedCollection`. The collection
|
||||
has conditional conformance to `BidirectionalCollection` and
|
||||
`LazyCollectionProtocol` when the base collection conforms.
|
||||
|
||||
### Naming
|
||||
|
||||
The name `compacted()` matches the existing method `compactMap`,
|
||||
which is commonly used to extract only the non-`nil` values
|
||||
without mapping them to a different type.
|
||||
+9
-8
@@ -16,9 +16,9 @@ for x in (1...3).cycled(times: 3) {
|
||||
// Prints 1 through 3 three times
|
||||
```
|
||||
|
||||
`cycled(times:)` combines two other existing standard library functions
|
||||
(`repeatElement` and `joined`) to provide a more expressive way of repeating a
|
||||
collection's elements a limited number of times.
|
||||
`cycled(times:)` provides a more expressive way of repeating a
|
||||
collection's elements a limited number of times than
|
||||
combining `repeatElement(_:count:)` and `joined()`.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
@@ -28,7 +28,7 @@ Two new methods are added to collections:
|
||||
extension Collection {
|
||||
func cycled() -> Cycle<Self>
|
||||
|
||||
func cycled(times: Int) -> FlattenSequence<Repeated<Self>>
|
||||
func cycled(times: Int) -> FiniteCycle<Self>
|
||||
}
|
||||
```
|
||||
|
||||
@@ -36,9 +36,10 @@ The new `Cycle` type is a sequence only, given that the `Collection` protocol
|
||||
design makes infinitely large types impossible/impractical. `Cycle` also
|
||||
conforms to `LazySequenceProtocol` when the base type conforms.
|
||||
|
||||
Note that despite its name, the returned `FlattenSequence` will always have
|
||||
`Collection` conformance, and will have `BidirectionalCollection` conformance
|
||||
when called on a bidirectional collection.
|
||||
The `FiniteCycle` type always has `Collection` conformance, with
|
||||
`BidirectionalCollection` conformance
|
||||
when called on a bidirectional collection. `FiniteCycle` also
|
||||
conforms to `LazyCollectionProtocol` when the base type conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
@@ -61,4 +62,4 @@ anything that matches the `cycled(times:)` behavior.
|
||||
`cycled(times:)` here.
|
||||
|
||||
**Python:** Python’s `itertools` includes a `cycle` method, which caches the
|
||||
elements of the iterator on the first pass.
|
||||
elements of the iterator on the first pass.
|
||||
+60
-18
@@ -2,23 +2,48 @@
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/FirstNonNil.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/FirstNonNilTests.swift)]
|
||||
|
||||
Retrieves the first `.some` encountered while applying the given transform.
|
||||
|
||||
This operation is available through the `firstNonNil(_:)` method on any sequence.
|
||||
|
||||
Returns the first non-`nil` result obtained from applying the given
|
||||
transformation to the elements of the sequence.
|
||||
|
||||
```swift
|
||||
let value = ["A", "B", "10"].firstNonNil { Int($0) }
|
||||
// value == .some(10)
|
||||
//
|
||||
let noValue = ["A", "B", "C"].firstNonNil { Int($0) }
|
||||
// noValue == .none
|
||||
let strings = ["three", "3.14", "-5", "2"]
|
||||
if let firstInt = strings.firstNonNil({ Int($0) }) {
|
||||
print(firstInt)
|
||||
// -5
|
||||
}
|
||||
```
|
||||
|
||||
Like `first(where:)`, this method stops iterating the sequence once a match is
|
||||
found. Use `firstNonNil(_:)` to avoid having to apply a transformation twice:
|
||||
|
||||
This method is analogous to `first(where:)` in how it only consumes values until
|
||||
a `.some` is found, unlike using lazy operators, which will load any sequence into a collection
|
||||
before evaluating its transforms lazily.
|
||||
```swift
|
||||
let strings = ["three", "3.14", "-5", "2"]
|
||||
if let firstIntAsString = strings.first(where: { Int($0) != nil }) {
|
||||
let firstInt = Int(firstIntAsString)! // :(
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
This method's behavior can also be approximated using `compactMap(_:)`:
|
||||
|
||||
```swift
|
||||
let strings = ["three", "3.14", "-5", "2"]
|
||||
if let firstInt = strings.compactMap({ Int($0) }).first {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
However, unlike `firstNonNil(_:)` and `first(where:)`, `compactMap(_:)` does not
|
||||
stop iterating the sequence once the first match is found. Adding `.lazy` fixes
|
||||
this, at the cost of requiring an escaping closure that you cannot `throw` from:
|
||||
|
||||
```swift
|
||||
let strings = ["three", "3.14", "-5", "2"]
|
||||
if let firstInt = strings.lazy.compactMap({ Int($0) }).first {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
@@ -27,17 +52,34 @@ protocol:
|
||||
|
||||
```swift
|
||||
public extension Sequence {
|
||||
func firstNonNil<Result>(_ transform: (Element) throws -> Result?)
|
||||
rethrows -> Result?
|
||||
func firstNonNil<Result>(
|
||||
_ transform: (Element) throws -> Result?
|
||||
) rethrows -> Result?
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
`firstNonNil(_:)` is an O(*n*) operation, where *n* is the number of
|
||||
elements at the start of the sequence that result in `nil` when applying the
|
||||
transformation.
|
||||
|
||||
### Naming
|
||||
|
||||
This method’s name was selected for its comprehensibility.
|
||||
Some alternative names were considered:
|
||||
|
||||
* `compactMapFirst(_:)`
|
||||
* `first(mapping:)`
|
||||
* `firstSome(_:)`
|
||||
* `firstMap(_:)`
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
**Scala**: Scala provides a `collectFirst` function that finds the first element
|
||||
in a collection for which a partial function is defined.
|
||||
**Haskell**: Haskell includes the `firstJust` method, which has the same
|
||||
semantics as the `firstNonNil(_:)` method.
|
||||
|
||||
**Rust**: Rust includes the `find_map` method, which has the same semantics as
|
||||
the `firstNonNil(_:)` method.
|
||||
|
||||
**Scala**: Scala includes the `collectFirst` method, which has the same
|
||||
semantics as the `firstNonNil(_:)` method.
|
||||
+35
-13
@@ -3,7 +3,7 @@
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Permutations.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/PermutationsTests.swift)]
|
||||
|
||||
A type that computes permutations of a collection’s elements, or of a subset of
|
||||
Methods that compute permutations of a collection’s elements, or of a subset of
|
||||
those elements.
|
||||
|
||||
The `permutations(ofCount:)` method, when called without the `ofCount`
|
||||
@@ -60,7 +60,18 @@ for perm in numbers2.permutations() {
|
||||
// [10, 10, 20]
|
||||
```
|
||||
|
||||
Given a range, the `permutations(ofCount:)` method returns a sequence of all the different permutations of the given sizes of a collection’s elements in increasing order of size.
|
||||
To generate only unique permutations, use the `uniquePermutations(ofCount:)` method:
|
||||
|
||||
```swift
|
||||
for perm in numbers2.uniquePermutations() {
|
||||
print(perm)
|
||||
}
|
||||
// [20, 10, 10]
|
||||
// [10, 20, 10]
|
||||
// [10, 10, 20]
|
||||
```
|
||||
|
||||
Given a range, the methods return a sequence of all the different permutations of the given sizes of a collection’s elements in increasing order of size.
|
||||
|
||||
```swift
|
||||
let numbers = [10, 20, 30]
|
||||
@@ -87,21 +98,29 @@ for perm in numbers.permutations(ofCount: 0...) {
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `permutations(ofCount:)` method is declared as a `Collection` extension,
|
||||
and returns a `Permutations` type:
|
||||
The `permutations(ofCount:)` and `uniquePermutations(ofCount:)` methods are declared as `Collection` extensions,
|
||||
and return `Permutations` and `UniquePermutations` instances, respectively:
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
public func permutations(ofCount k: Int? = nil) -> Permutations<Self>
|
||||
public func permutations<R>(ofCount kRange: R) -> Permutations<Self>
|
||||
where R: RangeExpression, R.Bound == Int
|
||||
}
|
||||
|
||||
extension Collection where Element: Hashable {
|
||||
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self>
|
||||
public func uniquePermutations<R>(ofCount kRange: R) -> UniquePermutations<Self>
|
||||
where R: RangeExpression, R.Bound == Int
|
||||
}
|
||||
```
|
||||
|
||||
Since the `Permutations` type needs to store an array of the collection’s
|
||||
indices and mutate the array to generate each permutation, `Permutations` only
|
||||
has `Sequence` conformance. Adding `Collection` conformance would require
|
||||
Since both result types need to store an array of the collection’s
|
||||
indices and mutate the array to generate each permutation, they only
|
||||
have `Sequence` conformance. Adding `Collection` conformance would require
|
||||
storing the array in the index type, which would in turn lead to copying the
|
||||
array at every index advancement. `Combinations` does conform to
|
||||
`LazySequenceProtocol` when the base type conforms.
|
||||
array at every index advancement. The `Permutations` type
|
||||
conforms to `LazySequenceProtocol` when its base type conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
@@ -109,6 +128,10 @@ Calling `permutations()` is an O(1) operation. Creating the iterator for a
|
||||
`Permutations` instance and each call to `Permutations.Iterator.next()` is an
|
||||
O(_n_) operation.
|
||||
|
||||
Calling `uniquePermutations()` is an O(_n_) operation, because it preprocesses the
|
||||
collection to find duplicate elements. Creating the iterator for and each call to
|
||||
`next()` is also an O(_n_) operation.
|
||||
|
||||
### Naming
|
||||
|
||||
See the ["Naming" section for `combinations(ofCount:)`](Combinations.md#naming) for detail.
|
||||
@@ -117,9 +140,8 @@ See the ["Naming" section for `combinations(ofCount:)`](Combinations.md#naming)
|
||||
|
||||
**C++:** The `<algorithm>` library defines a `next_permutation` function that
|
||||
advances an array of comparable values through their lexicographic orderings.
|
||||
This function is tricky to use and understand, so while it’s included in
|
||||
`swift-algorithms` as an implementation detail of the `Permutations` type, it
|
||||
isn’t public.
|
||||
This function is very similar to the `uniquePermutations(ofCount:)` method.
|
||||
|
||||
**Rust/Ruby/Python:** Rust, Ruby, and Python all define functions with
|
||||
essentially the same semantics as the method described here.
|
||||
essentially the same semantics as the `permutations(ofCount:)` method
|
||||
described here.
|
||||
@@ -0,0 +1,134 @@
|
||||
# Reductions
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Reductions.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ReductionsTests.swift)]
|
||||
|
||||
Produces all the intermediate results of reducing a sequence's elements using a closure.
|
||||
|
||||
```swift
|
||||
let exclusiveRunningTotal = (1...5).reductions(0, +)
|
||||
print(exclusiveRunningTotal)
|
||||
// prints [0, 1, 3, 6, 10, 15]
|
||||
|
||||
let intoRunningTotal = (1...5).reductions(into: 0, +=)
|
||||
print(intoRunningTotal)
|
||||
// prints [0, 1, 3, 6, 10, 15]
|
||||
|
||||
let inclusiveRunningTotal = (1...5).reductions(+)
|
||||
print(inclusiveRunningTotal)
|
||||
// prints [1, 3, 6, 10, 15]
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
One trio of methods are added to `LazySequenceProtocol` for a lazily evaluated
|
||||
sequence and another trio are added to `Sequence` which are eagerly evaluated.
|
||||
|
||||
```swift
|
||||
extension LazySequenceProtocol {
|
||||
|
||||
public func reductions<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: @escaping (Result, Element) -> Result
|
||||
) -> ExclusiveReductions<Result, Self>
|
||||
|
||||
public func reductions<Result>(
|
||||
into initial: Result,
|
||||
_ transform: @escaping (inout Result, Element) -> Void
|
||||
) -> ExclusiveReductions<Result, Self>
|
||||
|
||||
public func reductions(
|
||||
_ transform: @escaping (Element, Element) -> Element
|
||||
) -> InclusiveReductions<Self>
|
||||
}
|
||||
```
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
|
||||
public func reductions<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: (Result, Element) throws -> Result
|
||||
) rethrows -> [Result]
|
||||
|
||||
public func reductions<Result>(
|
||||
into initial: Result,
|
||||
_ transform: (inout Result, Element) throws -> Void
|
||||
) rethrows -> [Result]
|
||||
|
||||
public func reductions(
|
||||
_ transform: (Element, Element) throws -> Element
|
||||
) rethrows -> [Element]
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling the lazy methods, those defined on `LazySequenceProtocol`, is O(_1_).
|
||||
Calling the eager methods, those returning an array, is O(_n_).
|
||||
|
||||
### Naming
|
||||
|
||||
While the name `scan` is the term of art for this function, it has been
|
||||
discussed that `reductions` aligns better with the existing `reduce` function
|
||||
and will aid newcomers that might not know the existing `scan` term.
|
||||
|
||||
Deprecated `scan` methods have been added for people who are familiar with the
|
||||
term, so they can easily discover the `reductions` methods via compiler
|
||||
deprecation warnings.
|
||||
|
||||
Below are two quotes from the Swift forum [discussion about SE-0045][SE-0045]
|
||||
which proposed adding `scan` to the standard library and one from
|
||||
[issue #25][Issue 25] on the swift-algorithms GitHub project. These provide
|
||||
the reasoning to use the name `reductions`.
|
||||
|
||||
[Brent Royal-Gordon][Brent_Royal-Gordon]:
|
||||
> I really like the `reduce`/`reductions` pairing instead of `reduce`/`scan`;
|
||||
it does a really good job of explaining the relationship between the two
|
||||
functions.
|
||||
|
||||
[David Rönnqvist][David Rönnqvist]:
|
||||
> As other have already pointed out, I also feel that `scan` is the least
|
||||
intuitive name among these and that the `reduce`/`reductions` pairing would do
|
||||
a good job at explaining the relation between the two.
|
||||
|
||||
[Kyle Macomber][Kyle Macomber]:
|
||||
> As someone unfamiliar with the prior art, `reductions` strikes me as very
|
||||
approachable—I feel like I can extrapolate the expected behavior purely from my
|
||||
familiarity with `reduce`.
|
||||
|
||||
As part of early discussions, it was decided to have two variants, one which
|
||||
takes an initial value to use for the first element in the returned sequence,
|
||||
and another which uses the first value of the base sequence as the initial
|
||||
value. C++ calls these variants exclusive and inclusive respectively and so
|
||||
these terms carry through as the name for the lazy sequences;
|
||||
`ExclusiveReductions` and `InclusiveReductions`.
|
||||
|
||||
[SE-0045]: https://forums.swift.org/t/review-se-0045-add-scan-prefix-while-drop-while-and-iterate-to-the-stdlib/2382
|
||||
[Issue 25]: https://github.com/apple/swift-algorithms/issues/25
|
||||
[Brent_Royal-Gordon]: https://forums.swift.org/t/review-se-0045-add-scan-prefix-while-drop-while-and-iterate-to-the-stdlib/2382/6
|
||||
[David Rönnqvist]: https://forums.swift.org/t/review-se-0045-add-scan-prefix-while-drop-while-and-iterate-to-the-stdlib/2382/8
|
||||
[Kyle Macomber]: https://github.com/apple/swift-algorithms/issues/25#issuecomment-709317894
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
**C++:** As of C++17, the `<algorithm>` library includes both
|
||||
[`exclusive_scan`][C++ Exclusive] and [`inclusive_scan`][C++ Inclusive]
|
||||
functions.
|
||||
|
||||
**[Clojure][Clojure]:** Clojure 1.2 added a `reductions` function.
|
||||
|
||||
**[Haskell][Haskell]:** Haskell includes a `scan` function for its
|
||||
`Traversable` type, which is akin to Swift's `Sequence`.
|
||||
|
||||
**Python:** Python’s `itertools` includes an `accumulate` method. In version
|
||||
3.3, a function parameter was added. Version 3.8 added the optional initial
|
||||
parameter.
|
||||
|
||||
**[Rust][Rust]:** Rust provides a `scan` function.
|
||||
|
||||
[C++ Exclusive]: https://en.cppreference.com/w/cpp/algorithm/exclusive_scan
|
||||
[C++ Inclusive]: https://en.cppreference.com/w/cpp/algorithm/inclusive_scan
|
||||
[Clojure]: http://clojure.github.io/clojure/clojure.core-api.html#clojure.core/reductions
|
||||
[Haskell]: http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:scanl
|
||||
[Rust]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.scan
|
||||
+1
-1
@@ -101,7 +101,7 @@ let result = myString.drop(while: \.isWhitespace)
|
||||
```
|
||||
|
||||
With a lazy filter that drops _all_ whitespace characters regardless of where they are in the string.
|
||||
Besides that, the root `trim` leads to clearer, more conscise code, which is more aligned with other programming
|
||||
Besides that, the root `trim` leads to clearer, more concise code, which is more aligned with other programming
|
||||
languages:
|
||||
|
||||
```swift
|
||||
|
||||
+14
-7
@@ -5,7 +5,7 @@
|
||||
|
||||
Methods to strip repeated elements from a sequence or collection.
|
||||
|
||||
The `uniqued()` method returns an array, dropping duplicate elements
|
||||
The `uniqued()` method returns a sequence, dropping duplicate elements
|
||||
from a sequence. The `uniqued(on:)` method does the same, using
|
||||
the result of the given closure to determine the "uniqueness" of each
|
||||
element.
|
||||
@@ -14,29 +14,36 @@ element.
|
||||
let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1]
|
||||
|
||||
let unique = numbers.uniqued()
|
||||
// unique == [1, 2, 3]
|
||||
// Array(unique) == [1, 2, 3]
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
Both methods are available for sequences, with the simplest limited to
|
||||
when the element type conforms to `Hashable`. Both methods preserve
|
||||
the relative order of the elements.
|
||||
the relative order of the elements. `uniqued(on:)` has a matching lazy
|
||||
version that is added to `LazySequenceProtocol`.
|
||||
|
||||
```swift
|
||||
extension Sequence where Element: Hashable {
|
||||
func uniqued() -> [Element]
|
||||
func uniqued() -> Uniqued<Self, Element>
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
func uniqued<T>(on: (Element) throws -> T) rethrows -> [Element]
|
||||
where T: Hashable
|
||||
func uniqued<Subject>(on projection: (Element) throws -> Subject) rethrows -> [Element]
|
||||
where Subject: Hashable
|
||||
}
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
func uniqued<Subject>(on projection: @escaping (Element) -> Subject) -> Uniqued<Self, Subject>
|
||||
where Subject: Hashable
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
The `uniqued` methods are O(_n_) in both time and space complexity.
|
||||
The eager `uniqued(on:)` method is O(_n_) in both time and space complexity.
|
||||
The lazy versions are O(_1_).
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
|
||||
+19
-22
@@ -13,26 +13,23 @@
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "swift-algorithms",
|
||||
products: [
|
||||
.library(
|
||||
name: "Algorithms",
|
||||
targets: ["Algorithms"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-numerics", from: "0.0.1"),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "Algorithms",
|
||||
dependencies: [
|
||||
.product(name: "RealModule", package: "swift-numerics"),
|
||||
]),
|
||||
.target(
|
||||
name: "Benchmark",
|
||||
dependencies: ["Algorithms"]),
|
||||
.testTarget(
|
||||
name: "SwiftAlgorithmsTests",
|
||||
dependencies: ["Algorithms"]),
|
||||
]
|
||||
name: "swift-algorithms",
|
||||
products: [
|
||||
.library(
|
||||
name: "Algorithms",
|
||||
targets: ["Algorithms"])
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-numerics", from: "0.0.1")
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "Algorithms",
|
||||
dependencies: [
|
||||
.product(name: "RealModule", package: "swift-numerics")
|
||||
]),
|
||||
.testTarget(
|
||||
name: "SwiftAlgorithmsTests",
|
||||
dependencies: ["Algorithms"]),
|
||||
]
|
||||
)
|
||||
@@ -10,6 +10,7 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
||||
|
||||
- [`combinations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Combinations.md): Combinations of particular sizes of the elements in a collection.
|
||||
- [`permutations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md): Permutations of a particular size of the elements in a collection, or of the full collection.
|
||||
- [`uniquePermutations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md): Permutations of a collection's elements, skipping any duplicate permutations.
|
||||
|
||||
#### Mutating algorithms
|
||||
|
||||
@@ -24,9 +25,12 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
||||
|
||||
#### 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.
|
||||
- [`randomSample(count:)`, `randomSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection.
|
||||
- [`randomStableSample(count:)`, `randomStableSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection, preserving their original relative order.
|
||||
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
|
||||
- [`suffix(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Suffix.md): Returns the suffix of a collection where all element pass a given predicate.
|
||||
- [`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.
|
||||
|
||||
#### Partial sorting
|
||||
@@ -36,12 +40,12 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
||||
#### Other useful operations
|
||||
|
||||
- [`chunked(by:)`, `chunked(on:)`, `chunks(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chunked.md): Eager and lazy operations that break a collection into chunks based on either a binary predicate or when the result of a projection changes or chunks of a given count.
|
||||
- [`firstNonNil(_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/FirstNonNil.md): Returns the first non-`nil` result from transforming a sequence's elements.
|
||||
- [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements.
|
||||
- [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence.
|
||||
- [`trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start and end.
|
||||
- [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection.
|
||||
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
|
||||
- [`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/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.
|
||||
|
||||
## Adding Swift Algorithms as a Dependency
|
||||
|
||||
@@ -58,7 +62,7 @@ If you don't want potentially source-breaking package updates,
|
||||
use this dependency specification instead:
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.0.1")),
|
||||
.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.1.0")),
|
||||
```
|
||||
|
||||
Finally, include `"Algorithms"` as a dependency for your executable target:
|
||||
@@ -67,7 +71,7 @@ Finally, include `"Algorithms"` as a dependency for your executable target:
|
||||
let package = Package(
|
||||
// name, platforms, products, etc.
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-algorithms", from: "0.0.1"),
|
||||
.package(url: "https://github.com/apple/swift-algorithms", from: "0.1.0"),
|
||||
// other dependencies
|
||||
],
|
||||
targets: [
|
||||
|
||||
@@ -11,15 +11,16 @@
|
||||
|
||||
/// A concatenation of two sequences with the same element type.
|
||||
public struct Chain2<Base1: Sequence, Base2: Sequence>
|
||||
where Base1.Element == Base2.Element
|
||||
{
|
||||
where Base1.Element == Base2.Element {
|
||||
/// The first sequence in this chain.
|
||||
public let base1: Base1
|
||||
|
||||
/// The second sequence in this chain.
|
||||
public let base2: Base2
|
||||
|
||||
@usableFromInline
|
||||
internal let base1: Base1
|
||||
|
||||
/// The second sequence in this chain.
|
||||
@usableFromInline
|
||||
internal let base2: Base2
|
||||
|
||||
@inlinable
|
||||
internal init(base1: Base1, base2: Base2) {
|
||||
self.base1 = base1
|
||||
self.base2 = base2
|
||||
@@ -31,22 +32,22 @@ extension Chain2: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator1: Base1.Iterator
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal var iterator2: Base2.Iterator
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal init(_ concatenation: Chain2) {
|
||||
iterator1 = concatenation.base1.makeIterator()
|
||||
iterator2 = concatenation.base2.makeIterator()
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base1.Element? {
|
||||
return iterator1.next() ?? iterator2.next()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(self)
|
||||
@@ -62,7 +63,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
// from the penultimate index of the first collection to the start of the
|
||||
// second.
|
||||
@usableFromInline
|
||||
internal enum Representation : Equatable {
|
||||
internal enum Representation: Equatable {
|
||||
case first(Base1.Index)
|
||||
case second(Base2.Index)
|
||||
}
|
||||
@@ -71,13 +72,13 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
internal let position: Representation
|
||||
|
||||
/// Creates a new index into the first underlying collection.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal init(first i: Base1.Index) {
|
||||
position = .first(i)
|
||||
}
|
||||
|
||||
/// Creates a new index into the second underlying collection.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal init(second i: Base2.Index) {
|
||||
position = .second(i)
|
||||
}
|
||||
@@ -96,11 +97,11 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Converts an index of `Base1` to the corresponding `Index` by mapping
|
||||
/// `base1.endIndex` to `base2.startIndex`.
|
||||
@usableFromInline
|
||||
internal func convertIndex(_ i: Base1.Index) -> Index {
|
||||
@inlinable
|
||||
internal func normalizeIndex(_ i: Base1.Index) -> Index {
|
||||
i == base1.endIndex ? Index(second: base2.startIndex) : Index(first: i)
|
||||
}
|
||||
|
||||
@@ -108,7 +109,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
public var startIndex: Index {
|
||||
// if `base1` is empty, this will return `base2.startIndex` - if `base2` is
|
||||
// also empty, this will correctly equal `base2.endIndex`
|
||||
convertIndex(base1.startIndex)
|
||||
normalizeIndex(base1.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -131,112 +132,119 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
switch i.position {
|
||||
case let .first(i):
|
||||
assert(i != base1.endIndex)
|
||||
return convertIndex(base1.index(after: i))
|
||||
return normalizeIndex(base1.index(after: i))
|
||||
case let .second(i):
|
||||
return Index(second: base2.index(after: i))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy n: Int) -> Index {
|
||||
if n == 0 { return i }
|
||||
return n > 0
|
||||
? offsetForward(i, by: n, limitedBy: endIndex)!
|
||||
: offsetBackward(i, by: -n, limitedBy: startIndex)!
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
guard distance != 0 else { return i }
|
||||
|
||||
return distance > 0
|
||||
? offsetForward(i, by: distance)
|
||||
: offsetBackward(i, by: -distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
offsetBy n: Int,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
if n == 0 { return i }
|
||||
return n > 0
|
||||
? offsetForward(i, by: n, limitedBy: limit)
|
||||
: offsetBackward(i, by: -n, limitedBy: limit)
|
||||
if distance >= 0 {
|
||||
return limit >= i
|
||||
? offsetForward(i, by: distance, limitedBy: limit)
|
||||
: offsetForward(i, by: distance)
|
||||
} else {
|
||||
return limit <= i
|
||||
? offsetBackward(i, by: -distance, limitedBy: limit)
|
||||
: offsetBackward(i, by: -distance)
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@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(
|
||||
_ i: Index, by n: Int, limitedBy limit: Index
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance >= 0)
|
||||
assert(limit >= i)
|
||||
|
||||
switch (i.position, limit.position) {
|
||||
case let (.first(i), .first(limit)):
|
||||
if limit >= i {
|
||||
// `limit` is relevant, so `base2` cannot be reached
|
||||
return base1.index(i, offsetBy: n, limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
} else if let j = base1.index(i, offsetBy: n, limitedBy: base1.endIndex) {
|
||||
// the offset stays within the bounds of `base1`
|
||||
return convertIndex(j)
|
||||
} else {
|
||||
// the offset overflows the bounds of `base1` by `n - d`
|
||||
let d = base1.distance(from: i, to: base1.endIndex)
|
||||
return Index(second: base2.index(base2.startIndex, offsetBy: n - d))
|
||||
}
|
||||
|
||||
return base1.index(i, offsetBy: distance, limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
|
||||
case let (.first(i), .second(limit)):
|
||||
if let j = base1.index(i, offsetBy: n, limitedBy: base1.endIndex) {
|
||||
if let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) {
|
||||
// the offset stays within the bounds of `base1`
|
||||
return convertIndex(j)
|
||||
return normalizeIndex(j)
|
||||
} else {
|
||||
// the offset overflows the bounds of `base1` by `n - d`
|
||||
let d = base1.distance(from: i, to: base1.endIndex)
|
||||
return base2.index(base2.startIndex, offsetBy: n - d, limitedBy: limit)
|
||||
return base2.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
}
|
||||
|
||||
case let (.second(i), .first):
|
||||
// `limit` has no effect here
|
||||
return Index(second: base2.index(i, offsetBy: n))
|
||||
|
||||
|
||||
case (.second, .first):
|
||||
// impossible because `limit >= i`
|
||||
fatalError()
|
||||
|
||||
case let (.second(i), .second(limit)):
|
||||
return base2.index(i, offsetBy: n, limitedBy: limit)
|
||||
return base2.index(i, offsetBy: distance, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ i: Index, by n: Int, limitedBy limit: Index
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance >= 0)
|
||||
assert(limit <= i)
|
||||
|
||||
switch (i.position, limit.position) {
|
||||
case let (.first(i), .first(limit)):
|
||||
return base1.index(i, offsetBy: -n, limitedBy: limit)
|
||||
return base1.index(i, offsetBy: -distance, limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
|
||||
case let (.first(i), .second):
|
||||
// `limit` has no effect here
|
||||
return Index(first: base1.index(i, offsetBy: -n))
|
||||
|
||||
|
||||
case (.first, .second):
|
||||
// impossible because `limit <= i`
|
||||
fatalError()
|
||||
|
||||
case let (.second(i), .first(limit)):
|
||||
if let j = base2.index(i, offsetBy: -n, limitedBy: base2.startIndex) {
|
||||
if let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex) {
|
||||
// the offset stays within the bounds of `base2`
|
||||
return Index(second: j)
|
||||
} else {
|
||||
// the offset overflows the bounds of `base2` by `n - d`
|
||||
let d = base2.distance(from: base2.startIndex, to: i)
|
||||
return base1.index(base1.endIndex, offsetBy: -(n - d), limitedBy: limit)
|
||||
return base1.index(base1.endIndex, offsetBy: -(distance - d), limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
}
|
||||
|
||||
case let (.second(i), .second(limit)):
|
||||
if limit <= i {
|
||||
// `limit` is relevant, so `base1` cannot be reached
|
||||
return base2.index(i, offsetBy: -n, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
} else if let j = base2.index(i, offsetBy: -n, limitedBy: base2.startIndex) {
|
||||
// the offset stays within the bounds of `base2`
|
||||
return Index(second: j)
|
||||
} else {
|
||||
// the offset overflows the bounds of `base2` by `n - d`
|
||||
let d = base2.distance(from: base2.startIndex, to: i)
|
||||
return Index(first: base1.index(base1.endIndex, offsetBy: -(n - d)))
|
||||
}
|
||||
// `limit` is relevant, so `base1` cannot be reached
|
||||
return base2.index(i, offsetBy: -distance, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (start.position, end.position) {
|
||||
@@ -255,8 +263,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
}
|
||||
|
||||
extension Chain2: BidirectionalCollection
|
||||
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
|
||||
{
|
||||
where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
assert(i != startIndex, "Can't advance before startIndex")
|
||||
@@ -272,10 +279,7 @@ extension Chain2: BidirectionalCollection
|
||||
}
|
||||
|
||||
extension Chain2: RandomAccessCollection
|
||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||
|
||||
extension Chain2: Equatable where Base1: Equatable, Base2: Equatable {}
|
||||
extension Chain2: Hashable where Base1: Hashable, Base2: Hashable {}
|
||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// chain(_:_:)
|
||||
@@ -320,8 +324,7 @@ 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
|
||||
{
|
||||
where Element == S.Element {
|
||||
Chain2(base1: self, base2: other)
|
||||
}
|
||||
}
|
||||
+106
-106
@@ -11,23 +11,24 @@
|
||||
|
||||
/// A collection wrapper that breaks a collection into chunks based on a
|
||||
/// predicate or projection.
|
||||
public struct LazyChunked<Base: Collection, Subject> {
|
||||
public struct Chunked<Base: Collection, Subject> {
|
||||
/// The collection that this instance provides a view onto.
|
||||
public let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
/// The projection function.
|
||||
@usableFromInline
|
||||
internal let projection: (Base.Element) -> Subject
|
||||
|
||||
|
||||
/// The predicate.
|
||||
@usableFromInline
|
||||
internal let belongInSameGroup: (Subject, Subject) -> Bool
|
||||
|
||||
|
||||
/// The upper bound of the first chunk.
|
||||
@usableFromInline
|
||||
internal var firstUpperBound: Base.Index
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
projection: @escaping (Base.Element) -> Subject,
|
||||
@@ -37,32 +38,32 @@ public struct LazyChunked<Base: Collection, Subject> {
|
||||
self.projection = projection
|
||||
self.belongInSameGroup = belongInSameGroup
|
||||
self.firstUpperBound = base.startIndex
|
||||
|
||||
|
||||
if !base.isEmpty {
|
||||
firstUpperBound = endOfChunk(startingAt: base.startIndex)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension LazyChunked: LazyCollectionProtocol {
|
||||
extension Chunked: LazyCollectionProtocol {
|
||||
/// A position in a chunked collection.
|
||||
public struct Index: Comparable {
|
||||
/// The range corresponding to the chunk at this position.
|
||||
@usableFromInline
|
||||
internal var baseRange: Range<Base.Index>
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal init(_ baseRange: Range<Base.Index>) {
|
||||
self.baseRange = baseRange
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||
// Since each index represents the range of a disparate chunk, no two
|
||||
// unique indices will have the same lower bound.
|
||||
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
// Only use the lower bound to test for ordering, as above.
|
||||
@@ -72,23 +73,23 @@ extension LazyChunked: LazyCollectionProtocol {
|
||||
|
||||
/// Returns the index in the base collection of the end of the chunk starting
|
||||
/// at the given index.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal func endOfChunk(startingAt start: Base.Index) -> Base.Index {
|
||||
let subject = projection(base[start])
|
||||
return base[base.index(after: start)...]
|
||||
.endOfPrefix(while: { belongInSameGroup(subject, projection($0)) })
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(base.startIndex..<firstUpperBound)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(base.endIndex..<base.endIndex)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i != endIndex, "Can't advance past endIndex")
|
||||
@@ -97,7 +98,7 @@ extension LazyChunked: LazyCollectionProtocol {
|
||||
let end = endOfChunk(startingAt: upperBound)
|
||||
return Index(upperBound..<end)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Base.SubSequence {
|
||||
precondition(position != endIndex, "Can't subscript using endIndex")
|
||||
@@ -105,17 +106,16 @@ extension LazyChunked: LazyCollectionProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
extension LazyChunked.Index: Hashable where Base.Index: Hashable {}
|
||||
extension Chunked.Index: Hashable where Base.Index: Hashable {}
|
||||
|
||||
extension LazyChunked: BidirectionalCollection
|
||||
where Base: BidirectionalCollection
|
||||
{
|
||||
extension Chunked: BidirectionalCollection
|
||||
where Base: BidirectionalCollection {
|
||||
/// Returns the index in the base collection of the start of the chunk ending
|
||||
/// at the given index.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
|
||||
let indexBeforeEnd = base.index(before: end)
|
||||
|
||||
|
||||
// Get the projected value of the last element in the range ending at `end`.
|
||||
let subject = projection(base[indexBeforeEnd])
|
||||
return base[..<indexBeforeEnd]
|
||||
@@ -130,6 +130,9 @@ extension LazyChunked: BidirectionalCollection
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "Chunked")
|
||||
public typealias LazyChunked<Base: Collection, Subject> = Chunked<Base, Subject>
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// lazy.chunked(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
@@ -142,13 +145,13 @@ extension LazyCollectionProtocol {
|
||||
@inlinable
|
||||
public func chunked(
|
||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||
) -> LazyChunked<Elements, Element> {
|
||||
LazyChunked(
|
||||
) -> Chunked<Elements, Element> {
|
||||
Chunked(
|
||||
base: elements,
|
||||
projection: { $0 },
|
||||
belongInSameGroup: belongInSameGroup)
|
||||
}
|
||||
|
||||
|
||||
/// Returns a lazy collection of subsequences of this collection, chunked by
|
||||
/// grouping elements that project to the same value.
|
||||
///
|
||||
@@ -156,8 +159,8 @@ extension LazyCollectionProtocol {
|
||||
@inlinable
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: @escaping (Element) -> Subject
|
||||
) -> LazyChunked<Elements, Subject> {
|
||||
LazyChunked(
|
||||
) -> Chunked<Elements, Subject> {
|
||||
Chunked(
|
||||
base: elements,
|
||||
projection: projection,
|
||||
belongInSameGroup: ==)
|
||||
@@ -174,17 +177,17 @@ extension Collection {
|
||||
/// predicate.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal func chunked<Subject>(
|
||||
on projection: (Element) throws -> Subject,
|
||||
by belongInSameGroup: (Subject, Subject) throws -> Bool
|
||||
) 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) {
|
||||
@@ -193,14 +196,14 @@ extension Collection {
|
||||
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.
|
||||
///
|
||||
@@ -238,15 +241,15 @@ extension Collection {
|
||||
/// * `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 `LazyMapCollection`
|
||||
public struct ChunkedByCount<Base: Collection> {
|
||||
|
||||
|
||||
public typealias Element = Base.SubSequence
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal let chunkCount: Int
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal var startUpperBound: Base.Index
|
||||
|
||||
@@ -258,13 +261,14 @@ public struct ChunkedByCount<Base: Collection> {
|
||||
internal init(_base: Base, _chunkCount: Int) {
|
||||
self.base = _base
|
||||
self.chunkCount = _chunkCount
|
||||
|
||||
|
||||
// Compute the start index upfront in order to make
|
||||
// start index a O(1) lookup.
|
||||
self.startUpperBound = _base.index(
|
||||
_base.startIndex, offsetBy: _chunkCount,
|
||||
limitedBy: _base.endIndex
|
||||
) ?? _base.endIndex
|
||||
self.startUpperBound =
|
||||
_base.index(
|
||||
_base.startIndex, offsetBy: _chunkCount,
|
||||
limitedBy: _base.endIndex
|
||||
) ?? _base.endIndex
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,8 +276,8 @@ extension ChunkedByCount: Collection {
|
||||
public struct Index {
|
||||
@usableFromInline
|
||||
internal let baseRange: Range<Base.Index>
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal init(_baseRange: Range<Base.Index>) {
|
||||
self.baseRange = _baseRange
|
||||
}
|
||||
@@ -288,34 +292,40 @@ extension ChunkedByCount: Collection {
|
||||
public var endIndex: Index {
|
||||
Index(_baseRange: base.endIndex..<base.endIndex)
|
||||
}
|
||||
|
||||
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public subscript(i: Index) -> Element {
|
||||
precondition(i < endIndex, "Index out of range")
|
||||
return base[i.baseRange]
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i < endIndex, "Advancing past end index")
|
||||
let baseIdx = base.index(
|
||||
i.baseRange.upperBound, offsetBy: chunkCount,
|
||||
limitedBy: base.endIndex
|
||||
) ?? base.endIndex
|
||||
let baseIdx =
|
||||
base.index(
|
||||
i.baseRange.upperBound, offsetBy: chunkCount,
|
||||
limitedBy: base.endIndex
|
||||
) ?? base.endIndex
|
||||
return Index(_baseRange: i.baseRange.upperBound..<baseIdx)
|
||||
}
|
||||
}
|
||||
|
||||
extension ChunkedByCount.Index: Comparable {
|
||||
@inlinable
|
||||
public static func == (lhs: ChunkedByCount.Index,
|
||||
rhs: ChunkedByCount.Index) -> Bool {
|
||||
public static func == (
|
||||
lhs: ChunkedByCount.Index,
|
||||
rhs: ChunkedByCount.Index
|
||||
) -> Bool {
|
||||
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: ChunkedByCount.Index,
|
||||
rhs: ChunkedByCount.Index) -> Bool {
|
||||
public static func < (
|
||||
lhs: ChunkedByCount.Index,
|
||||
rhs: ChunkedByCount.Index
|
||||
) -> Bool {
|
||||
lhs.baseRange.lowerBound < rhs.baseRange.lowerBound
|
||||
}
|
||||
}
|
||||
@@ -326,19 +336,20 @@ where Base: RandomAccessCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(i > startIndex, "Advancing past start index")
|
||||
|
||||
|
||||
var offset = chunkCount
|
||||
if i.baseRange.lowerBound == base.endIndex {
|
||||
let remainder = base.count%chunkCount
|
||||
let remainder = base.count % chunkCount
|
||||
if remainder != 0 {
|
||||
offset = remainder
|
||||
}
|
||||
}
|
||||
|
||||
let baseIdx = base.index(
|
||||
i.baseRange.lowerBound, offsetBy: -offset,
|
||||
limitedBy: base.startIndex
|
||||
) ?? base.startIndex
|
||||
|
||||
let baseIdx =
|
||||
base.index(
|
||||
i.baseRange.lowerBound, offsetBy: -offset,
|
||||
limitedBy: base.startIndex
|
||||
) ?? base.startIndex
|
||||
return Index(_baseRange: baseIdx..<i.baseRange.lowerBound)
|
||||
}
|
||||
}
|
||||
@@ -347,8 +358,9 @@ extension ChunkedByCount {
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
let distance =
|
||||
base.distance(from: start.baseRange.lowerBound,
|
||||
to: end.baseRange.lowerBound)
|
||||
base.distance(
|
||||
from: start.baseRange.lowerBound,
|
||||
to: end.baseRange.lowerBound)
|
||||
let (quotient, remainder) =
|
||||
distance.quotientAndRemainder(dividingBy: chunkCount)
|
||||
return quotient + remainder.signum()
|
||||
@@ -360,14 +372,14 @@ extension ChunkedByCount {
|
||||
base.count.quotientAndRemainder(dividingBy: chunkCount)
|
||||
return quotient + remainder.signum()
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index, offsetBy offset: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
guard offset != 0 else { return i }
|
||||
guard limit != i else { return nil }
|
||||
|
||||
|
||||
if offset > 0 {
|
||||
return limit > i
|
||||
? offsetForward(i, offsetBy: offset, limit: limit)
|
||||
@@ -382,17 +394,18 @@ extension ChunkedByCount {
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
guard distance != 0 else { return i }
|
||||
|
||||
let idx = distance > 0
|
||||
? offsetForward(i, offsetBy: distance)
|
||||
: offsetBackward(i, offsetBy: distance)
|
||||
|
||||
let idx =
|
||||
distance > 0
|
||||
? offsetForward(i, offsetBy: distance)
|
||||
: offsetBackward(i, offsetBy: distance)
|
||||
guard let index = idx else {
|
||||
fatalError("Out of bounds")
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ i: Index, offsetBy distance: Int, limit: Index? = nil
|
||||
) -> Index? {
|
||||
@@ -404,14 +417,14 @@ extension ChunkedByCount {
|
||||
limit: limit, by: >
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
// Convenience to compute offset backward base distance.
|
||||
@inline(__always)
|
||||
private func computeOffsetBackwardBaseDistance(
|
||||
@inlinable
|
||||
internal func computeOffsetBackwardBaseDistance(
|
||||
_ i: Index, _ distance: Int
|
||||
) -> Int {
|
||||
if i == endIndex {
|
||||
let remainder = base.count%chunkCount
|
||||
let remainder = base.count % chunkCount
|
||||
// We have to take it into account when calculating offsets.
|
||||
if remainder != 0 {
|
||||
// Distance "minus" one(at this point distance is negative)
|
||||
@@ -422,24 +435,24 @@ extension ChunkedByCount {
|
||||
}
|
||||
return distance * chunkCount
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ i: Index, offsetBy distance: Int, limit: Index? = nil
|
||||
) -> Index? {
|
||||
assert(distance < 0)
|
||||
let baseDistance =
|
||||
computeOffsetBackwardBaseDistance(i, distance)
|
||||
computeOffsetBackwardBaseDistance(i, distance)
|
||||
return makeOffsetIndex(
|
||||
from: i, baseBound: base.startIndex,
|
||||
distance: distance, baseDistance: baseDistance,
|
||||
limit: limit, by: <
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
// Helper to compute index(offsetBy:) index.
|
||||
@inline(__always)
|
||||
private func makeOffsetIndex(
|
||||
@inlinable
|
||||
internal func makeOffsetIndex(
|
||||
from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int,
|
||||
limit: Index?, by limitFn: (Base.Index, Base.Index) -> Bool
|
||||
) -> Index? {
|
||||
@@ -447,7 +460,7 @@ extension ChunkedByCount {
|
||||
i.baseRange.lowerBound, offsetBy: baseDistance,
|
||||
limitedBy: baseBound
|
||||
)
|
||||
|
||||
|
||||
if let limit = limit {
|
||||
if baseIdx == nil {
|
||||
// If we past the bounds while advancing forward and the
|
||||
@@ -473,12 +486,13 @@ extension ChunkedByCount {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let baseStartIdx = baseIdx ?? baseBound
|
||||
let baseEndIdx = base.index(
|
||||
baseStartIdx, offsetBy: chunkCount, limitedBy: base.endIndex
|
||||
) ?? base.endIndex
|
||||
|
||||
let baseEndIdx =
|
||||
base.index(
|
||||
baseStartIdx, offsetBy: chunkCount, limitedBy: base.endIndex
|
||||
) ?? base.endIndex
|
||||
|
||||
return Index(_baseRange: baseStartIdx..<baseEndIdx)
|
||||
}
|
||||
}
|
||||
@@ -507,24 +521,10 @@ extension Collection {
|
||||
}
|
||||
}
|
||||
|
||||
// Conditional conformances.
|
||||
extension ChunkedByCount: Equatable where Base: Equatable {}
|
||||
|
||||
// Since we have another stored property of type `Index` on the
|
||||
// collection, synthesis of `Hashble` conformace would require
|
||||
// a `Base.Index: Hashable` constraint, so we implement the hasher
|
||||
// only in terms of `base`. Since the computed index is based on it,
|
||||
// it should not make a difference here.
|
||||
extension ChunkedByCount: Hashable where Base: Hashable {
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(base)
|
||||
}
|
||||
}
|
||||
extension ChunkedByCount.Index: Hashable where Base.Index: Hashable {}
|
||||
|
||||
// Lazy conditional conformance.
|
||||
extension ChunkedByCount: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension ChunkedByCount: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
where Base: LazyCollectionProtocol {}
|
||||
@@ -12,32 +12,33 @@
|
||||
/// A collection wrapper that generates combinations of a base collection.
|
||||
public struct Combinations<Base: Collection> {
|
||||
/// The collection to iterate over for combinations.
|
||||
public let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let baseCount: Int
|
||||
|
||||
|
||||
/// The range of accepted sizes of combinations.
|
||||
/// - Note: This may be `nil` if the attempted range entirely exceeds the
|
||||
/// upper bounds of the size of the `base` collection.
|
||||
@usableFromInline
|
||||
internal let kRange: Range<Int>?
|
||||
|
||||
|
||||
/// Initializes a `Combinations` for all combinations of `base` of size `k`.
|
||||
/// - Parameters:
|
||||
/// - base: The collection to iterate over for combinations.
|
||||
/// - k: The expected size of each combination.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal init(_ base: Base, k: Int) {
|
||||
self.init(base, kRange: k...k)
|
||||
}
|
||||
|
||||
|
||||
/// Initializes a `Combinations` for all combinations of `base` of sizes
|
||||
/// within a given range.
|
||||
/// - Parameters:
|
||||
/// - base: The collection to iterate over for combinations.
|
||||
/// - kRange: The range of accepted sizes of combinations.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal init<R: RangeExpression>(
|
||||
_ base: Base, kRange: R
|
||||
) where R.Bound == Int {
|
||||
@@ -46,20 +47,21 @@ public struct Combinations<Base: Collection> {
|
||||
let baseCount = base.count
|
||||
self.baseCount = baseCount
|
||||
let upperBound = baseCount + 1
|
||||
self.kRange = range.lowerBound < upperBound
|
||||
? range.clamped(to: 0 ..< upperBound)
|
||||
self.kRange =
|
||||
range.lowerBound < upperBound
|
||||
? range.clamped(to: 0..<upperBound)
|
||||
: nil
|
||||
}
|
||||
|
||||
|
||||
/// The total number of combinations.
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
guard let k = self.kRange else { return 0 }
|
||||
let n = baseCount
|
||||
if k == 0 ..< (n + 1) {
|
||||
if k == 0..<(n + 1) {
|
||||
return 1 << n
|
||||
}
|
||||
|
||||
|
||||
func binomial(n: Int, k: Int) -> Int {
|
||||
switch k {
|
||||
case n, 0: return 1
|
||||
@@ -68,7 +70,7 @@ public struct Combinations<Base: Collection> {
|
||||
default: return n * binomial(n: n - 1, k: k - 1) / k
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return k.map {
|
||||
binomial(n: n, k: $0)
|
||||
}.reduce(0, +)
|
||||
@@ -80,29 +82,30 @@ extension Combinations: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
|
||||
/// The current range of accepted sizes of combinations.
|
||||
/// - Note: The range is contracted until empty while iterating over
|
||||
/// combinations of different sizes. When the range is empty, iteration is
|
||||
/// finished.
|
||||
@usableFromInline
|
||||
internal var kRange: Range<Int>
|
||||
|
||||
|
||||
/// Whether or not iteration is finished (`kRange` is empty)
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal var isFinished: Bool {
|
||||
return kRange.isEmpty
|
||||
}
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
|
||||
|
||||
@inlinable
|
||||
internal init(_ combinations: Combinations) {
|
||||
self.base = combinations.base
|
||||
self.kRange = combinations.kRange ?? 0..<0
|
||||
self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound))
|
||||
}
|
||||
|
||||
|
||||
/// Advances the current indices to the next set of combinations. If
|
||||
/// `indexes.count == 3` and `base.count == 5`, the indices advance like
|
||||
/// this:
|
||||
@@ -121,19 +124,19 @@ extension Combinations: Sequence {
|
||||
/// [2, 3, 4] *
|
||||
/// // Can't advance without needing to go past `base.endIndex`,
|
||||
/// // so the iteration is finished.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal mutating func advance() {
|
||||
/// Advances `kRange` by incrementing its `lowerBound` until the range is
|
||||
/// empty, when iteration is finished.
|
||||
func advanceKRange() {
|
||||
if kRange.lowerBound < kRange.upperBound {
|
||||
let advancedLowerBound = kRange.lowerBound + 1
|
||||
kRange = advancedLowerBound ..< kRange.upperBound
|
||||
kRange = advancedLowerBound..<kRange.upperBound
|
||||
indexes.removeAll(keepingCapacity: true)
|
||||
indexes.append(contentsOf: base.indices.prefix(kRange.lowerBound))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
guard !indexes.isEmpty else {
|
||||
// Initial state for combinations of 0 elements is an empty array with
|
||||
// `finished == false`. Even though no indexes are involved, advancing
|
||||
@@ -141,11 +144,11 @@ extension Combinations: Sequence {
|
||||
advanceKRange()
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
let i = indexes.count - 1
|
||||
base.formIndex(after: &indexes[i])
|
||||
if indexes[i] != base.endIndex { return }
|
||||
|
||||
|
||||
var j = i
|
||||
while indexes[i] == base.endIndex {
|
||||
j -= 1
|
||||
@@ -154,7 +157,7 @@ extension Combinations: Sequence {
|
||||
advanceKRange()
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
base.formIndex(after: &indexes[j])
|
||||
for k in indexes.indices[(j + 1)...] {
|
||||
indexes[k] = base.index(after: indexes[k - 1])
|
||||
@@ -164,7 +167,7 @@ extension Combinations: Sequence {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> [Base.Element]? {
|
||||
guard !isFinished else { return nil }
|
||||
@@ -172,15 +175,13 @@ extension Combinations: Sequence {
|
||||
return indexes.map { i in base[i] }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension Combinations: Equatable where Base: Equatable {}
|
||||
extension Combinations: Hashable where Base: Hashable {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// combinations(ofCount:)
|
||||
@@ -254,7 +255,7 @@ extension Collection {
|
||||
) -> Combinations<Self> where R.Bound == Int {
|
||||
return Combinations(self, kRange: kRange)
|
||||
}
|
||||
|
||||
|
||||
/// Returns a collection of combinations of this collection's elements, with
|
||||
/// each combination having the specified number of elements.
|
||||
///
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 `Sequence` that iterates over every non-nil element from the original `Sequence`.
|
||||
public struct CompactedSequence<Base: Sequence, Element>: Sequence
|
||||
where Base.Element == Element? {
|
||||
|
||||
@usableFromInline
|
||||
let base: Base
|
||||
|
||||
@inlinable
|
||||
init(base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
var base: Base.Iterator
|
||||
|
||||
@inlinable
|
||||
init(base: Base.Iterator) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Element? {
|
||||
while let wrapped = base.next() {
|
||||
guard let some = wrapped else { continue }
|
||||
return some
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
return Iterator(base: base.makeIterator())
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
/// Returns a new `Sequence` that iterates over every non-nil element
|
||||
/// from the original `Sequence`.
|
||||
/// It produces the same result as `c.compactMap { $0 }`.
|
||||
///
|
||||
/// let c = [1, nil, 2, 3, nil]
|
||||
/// for num in c.compacted() {
|
||||
/// print(num)
|
||||
/// }
|
||||
/// // 1
|
||||
/// // 2
|
||||
/// // 3
|
||||
///
|
||||
/// - Returns: A `Sequence` where the element is the unwrapped original
|
||||
/// element and iterates over every non-nil element from the original
|
||||
/// `Sequence`.
|
||||
///
|
||||
/// Complexity: O(1)
|
||||
@inlinable
|
||||
public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
|
||||
where Element == Unwrapped? {
|
||||
CompactedSequence(base: self)
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Collection` that iterates over every non-nil element from the original `Collection`.
|
||||
public struct CompactedCollection<Base: Collection, Element>: Collection
|
||||
where Base.Element == Element? {
|
||||
|
||||
@usableFromInline
|
||||
let base: Base
|
||||
|
||||
@inlinable
|
||||
init(base: Base) {
|
||||
self.base = base
|
||||
let idx = base.firstIndex(where: { $0 != nil }) ?? base.endIndex
|
||||
self.startIndex = Index(base: idx)
|
||||
}
|
||||
|
||||
public struct Index {
|
||||
@usableFromInline
|
||||
let base: Base.Index
|
||||
|
||||
@inlinable
|
||||
init(base: Base.Index) {
|
||||
self.base = base
|
||||
}
|
||||
}
|
||||
|
||||
public var startIndex: Index
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index { Index(base: base.endIndex) }
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Element {
|
||||
base[position.base]!
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i != endIndex, "Index out of bounds")
|
||||
|
||||
let baseIdx = base.index(after: i.base)
|
||||
guard let idx = base[baseIdx...].firstIndex(where: { $0 != nil })
|
||||
else { return endIndex }
|
||||
return Index(base: idx)
|
||||
}
|
||||
}
|
||||
|
||||
extension CompactedCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection {
|
||||
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(i != startIndex, "Index out of bounds")
|
||||
|
||||
guard
|
||||
let idx =
|
||||
base[startIndex.base..<i.base]
|
||||
.lastIndex(where: { $0 != nil })
|
||||
else { fatalError("Index out of bounds") }
|
||||
return Index(base: idx)
|
||||
}
|
||||
}
|
||||
|
||||
extension CompactedCollection.Index: Comparable {
|
||||
@inlinable
|
||||
public static func < (
|
||||
lhs: CompactedCollection.Index,
|
||||
rhs: CompactedCollection.Index
|
||||
) -> Bool {
|
||||
lhs.base < rhs.base
|
||||
}
|
||||
}
|
||||
|
||||
extension CompactedCollection.Index: Hashable
|
||||
where Base.Index: Hashable {}
|
||||
|
||||
extension Collection {
|
||||
/// Returns a new `Collection` that iterates over every non-nil element
|
||||
/// from the original `Collection`.
|
||||
/// It produces the same result as `c.compactMap { $0 }`.
|
||||
///
|
||||
/// let c = [1, nil, 2, 3, nil]
|
||||
/// for num in c.compacted() {
|
||||
/// print(num)
|
||||
/// }
|
||||
/// // 1
|
||||
/// // 2
|
||||
/// // 3
|
||||
///
|
||||
/// - Returns: A `Collection` where the element is the unwrapped original
|
||||
/// element and iterates over every non-nil element from the original
|
||||
/// `Collection`.
|
||||
///
|
||||
/// Complexity: O(*n*) where *n* is the number of elements in the
|
||||
/// original `Collection`.
|
||||
@inlinable
|
||||
public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
|
||||
where Element == Unwrapped? {
|
||||
CompactedCollection(base: self)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Protocol Conformances
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension CompactedSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension CompactedCollection: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension CompactedCollection: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
+123
-14
@@ -12,9 +12,10 @@
|
||||
/// A collection wrapper that repeats the elements of a base collection.
|
||||
public struct Cycle<Base: Collection> {
|
||||
/// The collection to repeat.
|
||||
public let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
@@ -24,30 +25,30 @@ extension Cycle: Sequence {
|
||||
/// The iterator for a `Cycle` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
let base: Base
|
||||
|
||||
@usableFromInline
|
||||
var current: Base.Index
|
||||
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal var current: Base.Index
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
self.current = base.startIndex
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element? {
|
||||
guard !base.isEmpty else { return nil }
|
||||
|
||||
|
||||
if current == base.endIndex {
|
||||
current = base.startIndex
|
||||
}
|
||||
|
||||
|
||||
defer { base.formIndex(after: ¤t) }
|
||||
return base[current]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(base: base)
|
||||
@@ -56,6 +57,114 @@ extension Cycle: Sequence {
|
||||
|
||||
extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
/// A collection wrapper that repeats the elements of a base collection for a
|
||||
/// finite number of times.
|
||||
public struct FiniteCycle<Base: Collection> {
|
||||
/// A Product2 instance for iterating the Base collection.
|
||||
@usableFromInline
|
||||
internal let product: Product2<Range<Int>, Base>
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, times: Int) {
|
||||
self.product = Product2(0..<times, base)
|
||||
}
|
||||
}
|
||||
|
||||
extension FiniteCycle: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
|
||||
extension FiniteCycle: Collection {
|
||||
|
||||
public typealias Element = Base.Element
|
||||
|
||||
public struct Index: Comparable {
|
||||
/// The index corresponding to the Product2 index at this position.
|
||||
@usableFromInline
|
||||
internal let productIndex: Product2<Range<Int>, Base>.Index
|
||||
|
||||
@inlinable
|
||||
internal init(_ productIndex: Product2<Range<Int>, Base>.Index) {
|
||||
self.productIndex = productIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.productIndex == rhs.productIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.productIndex < rhs.productIndex
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(product.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(product.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(_ index: Index) -> Element {
|
||||
product[index.productIndex].1
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
let productIndex = product.index(after: i.productIndex)
|
||||
return Index(productIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
product.distance(from: start.productIndex, to: end.productIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
let productIndex = product.index(i.productIndex, offsetBy: distance)
|
||||
return Index(productIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
guard
|
||||
let productIndex = product.index(
|
||||
i.productIndex,
|
||||
offsetBy: distance,
|
||||
limitedBy: limit.productIndex)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
return Index(productIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
product.count
|
||||
}
|
||||
}
|
||||
|
||||
extension FiniteCycle: BidirectionalCollection
|
||||
where Base: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
let productIndex = product.index(before: i.productIndex)
|
||||
return Index(productIndex)
|
||||
}
|
||||
}
|
||||
|
||||
extension FiniteCycle: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// cycled()
|
||||
//===----------------------------------------------------------------------===//
|
||||
@@ -90,7 +199,7 @@ extension Collection {
|
||||
public func cycled() -> Cycle<Self> {
|
||||
Cycle(base: self)
|
||||
}
|
||||
|
||||
|
||||
/// Returns a sequence that repeats the elements of this collection the
|
||||
/// specified number of times.
|
||||
///
|
||||
@@ -109,7 +218,7 @@ extension Collection {
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func cycled(times: Int) -> FlattenSequence<Repeated<Self>> {
|
||||
repeatElement(self, count: times).joined()
|
||||
public func cycled(times: Int) -> FiniteCycle<Self> {
|
||||
FiniteCycle(base: self, times: times)
|
||||
}
|
||||
}
|
||||
@@ -13,16 +13,31 @@
|
||||
// firstNonNil(_:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
public extension Sequence {
|
||||
/// Returns the first element in `self` that `transform` maps to a `.some`.
|
||||
func firstNonNil<Result>(
|
||||
extension Sequence {
|
||||
/// Returns the first non-`nil` result obtained from applying the given
|
||||
/// transformation to the elements of the sequence.
|
||||
///
|
||||
/// let strings = ["three", "3.14", "-5", "2"]
|
||||
/// if let firstInt = strings.firstNonNil({ Int($0) }) {
|
||||
/// print(firstInt)
|
||||
/// // -5
|
||||
/// }
|
||||
///
|
||||
/// - Parameter transform: A closure that takes an element of the sequence as
|
||||
/// its argument and returns an optional transformed value.
|
||||
/// - Returns: The first non-`nil` return value of the transformation, or
|
||||
/// `nil` if no transformation is successful.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the number of elements at the start of
|
||||
/// the sequence that result in `nil` when applying the transformation.
|
||||
public func firstNonNil<Result>(
|
||||
_ transform: (Element) throws -> Result?
|
||||
) rethrows -> Result? {
|
||||
for value in self {
|
||||
if let value = try transform(value) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
for value in self {
|
||||
if let value = try transform(value) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -14,11 +14,12 @@
|
||||
public struct Indexed<Base: Collection> {
|
||||
/// The element type for an `Indexed` collection.
|
||||
public typealias Element = (index: Base.Index, element: Base.Element)
|
||||
|
||||
|
||||
/// The base collection.
|
||||
public let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
@@ -29,32 +30,34 @@ extension Indexed: Collection {
|
||||
public var startIndex: Base.Index {
|
||||
base.startIndex
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Base.Index {
|
||||
base.endIndex
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Base.Index) -> Element {
|
||||
(index: position, element: base[position])
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Base.Index) -> Base.Index {
|
||||
base.index(after: i)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index {
|
||||
base.index(i, offsetBy: distance)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index) -> Base.Index? {
|
||||
public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index) -> Base
|
||||
.Index?
|
||||
{
|
||||
base.index(i, offsetBy: distance, limitedBy: limit)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Base.Index, to end: Base.Index) -> Int {
|
||||
base.distance(from: start, to: end)
|
||||
@@ -71,8 +74,6 @@ extension Indexed: BidirectionalCollection where Base: BidirectionalCollection {
|
||||
extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
extension Indexed: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension Indexed: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
||||
extension Indexed: Equatable where Base: Equatable {}
|
||||
extension Indexed: Hashable where Base: Hashable {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// indexed()
|
||||
|
||||
@@ -14,11 +14,11 @@
|
||||
public struct Intersperse<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal let separator: Base.Element
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, separator: Base.Element) {
|
||||
self.base = base
|
||||
self.separator = separator
|
||||
@@ -30,19 +30,19 @@ extension Intersperse: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal let separator: Base.Element
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal var state = State.start
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal init(iterator: Base.Iterator, separator: Base.Element) {
|
||||
self.iterator = iterator
|
||||
self.separator = separator
|
||||
}
|
||||
|
||||
|
||||
@usableFromInline
|
||||
enum State {
|
||||
case start
|
||||
@@ -85,28 +85,33 @@ extension Intersperse: Collection where Base: Collection {
|
||||
case element(Base.Index)
|
||||
case separator(next: Base.Index)
|
||||
}
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal let representation: Representation
|
||||
|
||||
@inlinable
|
||||
init(representation: Representation) {
|
||||
self.representation = representation
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
switch (lhs.representation, rhs.representation) {
|
||||
case let (.element(li), .element(ri)),
|
||||
let (.separator(next: li), .separator(next: ri)),
|
||||
let (.element(li), .separator(next: ri)):
|
||||
let (.separator(next: li), .separator(next: ri)),
|
||||
let (.element(li), .separator(next: ri)):
|
||||
return li < ri
|
||||
case let (.separator(next: li), .element(ri)):
|
||||
return li <= ri
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
static func element(_ index: Base.Index) -> Self {
|
||||
Self(representation: .element(index))
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
static func separator(next: Base.Index) -> Self {
|
||||
Self(representation: .separator(next: next))
|
||||
}
|
||||
@@ -140,7 +145,7 @@ extension Intersperse: Collection where Base: Collection {
|
||||
case .separator: return separator
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
switch (i.representation, distance.isMultiple(of: 2)) {
|
||||
@@ -164,15 +169,14 @@ extension Intersperse: Collection where Base: Collection {
|
||||
case let (.separator(next: separator), .element(element)):
|
||||
return 2 * base.distance(from: separator, to: element) + 1
|
||||
case let (.element(start), .element(end)),
|
||||
let (.separator(start), .separator(end)):
|
||||
let (.separator(start), .separator(end)):
|
||||
return 2 * base.distance(from: start, to: end)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Intersperse: BidirectionalCollection
|
||||
where Base: BidirectionalCollection
|
||||
{
|
||||
where Base: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(i != startIndex, "Can't move before startIndex")
|
||||
@@ -186,13 +190,13 @@ extension Intersperse: BidirectionalCollection
|
||||
}
|
||||
|
||||
extension Intersperse: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
extension Intersperse: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension Intersperse: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
where Base: LazyCollectionProtocol {}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ public struct LazySplitSequence<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let omittingEmptySubsequences: Bool
|
||||
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
isSeparator: @escaping (Base.Element) -> Bool,
|
||||
@@ -72,7 +72,7 @@ extension LazySplitSequence {
|
||||
@usableFromInline
|
||||
internal var sequenceLength = 0
|
||||
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base.Iterator,
|
||||
whereSeparator: @escaping (Base.Element) -> Bool,
|
||||
@@ -360,7 +360,7 @@ public struct LazySplitCollection<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal var _startIndex: Index
|
||||
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
isSeparator: @escaping (Base.Element) -> Bool,
|
||||
@@ -415,7 +415,7 @@ extension LazySplitCollection: LazyCollectionProtocol {
|
||||
@usableFromInline
|
||||
internal let splitCount: Int
|
||||
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal init(
|
||||
baseRange: Range<Base.Index>,
|
||||
sequenceLength: Int,
|
||||
@@ -441,7 +441,7 @@ extension LazySplitCollection: LazyCollectionProtocol {
|
||||
|
||||
/// Returns the index of the subsequence starting at or after the given base
|
||||
/// collection index.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal func indexForSubsequence(
|
||||
atOrAfter lowerBound: Base.Index,
|
||||
sequenceLength: Int,
|
||||
|
||||
@@ -17,20 +17,20 @@ extension Sequence {
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
var iterator = makeIterator()
|
||||
|
||||
|
||||
var result: [Element] = []
|
||||
result.reserveCapacity(count)
|
||||
while result.count < count, let e = iterator.next() {
|
||||
result.append(e)
|
||||
}
|
||||
try result.sort(by: areInIncreasingOrder)
|
||||
|
||||
|
||||
while let e = iterator.next() {
|
||||
// To be part of `result`, `e` must be strictly less than `result.last`.
|
||||
guard try areInIncreasingOrder(e, result.last!) else { continue }
|
||||
let insertionIndex =
|
||||
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
|
||||
|
||||
|
||||
assert(insertionIndex != result.endIndex)
|
||||
result.removeLast()
|
||||
result.insert(e, at: insertionIndex)
|
||||
@@ -38,7 +38,7 @@ extension Sequence {
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
/// Implementation for max(count:areInIncreasingOrder:)
|
||||
@inlinable
|
||||
internal func _maxImplementation(
|
||||
@@ -46,14 +46,14 @@ extension Sequence {
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
var iterator = makeIterator()
|
||||
|
||||
|
||||
var result: [Element] = []
|
||||
result.reserveCapacity(count)
|
||||
while result.count < count, let e = iterator.next() {
|
||||
result.append(e)
|
||||
}
|
||||
try result.sort(by: areInIncreasingOrder)
|
||||
|
||||
|
||||
while let e = iterator.next() {
|
||||
// To be part of `result`, `e` must be greater/equal to `result.first`.
|
||||
guard try !areInIncreasingOrder(e, result.first!) else { continue }
|
||||
@@ -71,10 +71,10 @@ extension Sequence {
|
||||
}
|
||||
result[insertionIndex - 1] = e
|
||||
}
|
||||
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
/// Returns the smallest elements of this sequence, as sorted by the given
|
||||
/// predicate.
|
||||
///
|
||||
@@ -107,7 +107,9 @@ extension Sequence {
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
precondition(count >= 0, """
|
||||
precondition(
|
||||
count >= 0,
|
||||
"""
|
||||
Cannot find a minimum with a negative count of elements!
|
||||
"""
|
||||
)
|
||||
@@ -120,7 +122,7 @@ extension Sequence {
|
||||
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
|
||||
}
|
||||
|
||||
/// Returns the largets elements of this sequence, as sorted by the given
|
||||
/// Returns the largest elements of this sequence, as sorted by the given
|
||||
/// predicate.
|
||||
///
|
||||
/// This example partially sorts an array of integers to retrieve its three
|
||||
@@ -152,7 +154,9 @@ extension Sequence {
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
precondition(count >= 0, """
|
||||
precondition(
|
||||
count >= 0,
|
||||
"""
|
||||
Cannot find a maximum with a negative count of elements!
|
||||
"""
|
||||
)
|
||||
@@ -253,7 +257,9 @@ extension Collection {
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
precondition(count >= 0, """
|
||||
precondition(
|
||||
count >= 0,
|
||||
"""
|
||||
Cannot find a minimum with a negative count of elements!
|
||||
"""
|
||||
)
|
||||
@@ -271,11 +277,11 @@ extension Collection {
|
||||
guard prefixCount < (self.count / 10) else {
|
||||
return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount))
|
||||
}
|
||||
|
||||
|
||||
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
|
||||
}
|
||||
|
||||
/// Returns the largets elements of this collection, as sorted by the given
|
||||
/// Returns the largest elements of this collection, as sorted by the given
|
||||
/// predicate.
|
||||
///
|
||||
/// This example partially sorts an array of integers to retrieve its three
|
||||
@@ -307,7 +313,9 @@ extension Collection {
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
precondition(count >= 0, """
|
||||
precondition(
|
||||
count >= 0,
|
||||
"""
|
||||
Cannot find a maximum with a negative count of elements!
|
||||
"""
|
||||
)
|
||||
|
||||
@@ -21,11 +21,11 @@ extension MutableCollection {
|
||||
/// - Complexity: O(*n* log *n*), where *n* is the number of elements.
|
||||
/// - Precondition:
|
||||
/// `n == distance(from: range.lowerBound, to: range.upperBound)`
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal mutating func stablePartition(
|
||||
count n: Int,
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws-> Bool
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
if n == 0 { return subrange.lowerBound }
|
||||
if n == 1 {
|
||||
@@ -33,8 +33,9 @@ extension MutableCollection {
|
||||
? subrange.lowerBound
|
||||
: 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(
|
||||
count: h,
|
||||
subrange: subrange.lowerBound..<i,
|
||||
@@ -45,7 +46,7 @@ extension MutableCollection {
|
||||
by: belongsInSecondPartition)
|
||||
return rotate(subrange: j..<k, toStartAt: i)
|
||||
}
|
||||
|
||||
|
||||
/// Moves all elements satisfying the given predicate into a suffix of the
|
||||
/// given range, preserving the relative order of the elements in both
|
||||
/// partitions, and returns the start of the resulting suffix.
|
||||
@@ -60,14 +61,14 @@ extension MutableCollection {
|
||||
@inlinable
|
||||
public mutating func stablePartition(
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws-> Bool
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
try stablePartition(
|
||||
count: distance(from: subrange.lowerBound, to: subrange.upperBound),
|
||||
subrange: subrange,
|
||||
by: belongsInSecondPartition)
|
||||
}
|
||||
|
||||
|
||||
/// Moves all elements satisfying the given predicate into a suffix of this
|
||||
/// collection, preserving the relative order of the elements in both
|
||||
/// 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.
|
||||
@inlinable
|
||||
public mutating func stablePartition(
|
||||
by belongsInSecondPartition: (Element) throws-> Bool
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
try stablePartition(
|
||||
subrange: startIndex..<endIndex,
|
||||
@@ -104,8 +105,8 @@ extension MutableCollection {
|
||||
// This version of `partition(subrange:)` is half stable; the elements in
|
||||
// the first partition retain their original relative order.
|
||||
guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition)
|
||||
else { return subrange.upperBound }
|
||||
|
||||
else { return subrange.upperBound }
|
||||
|
||||
var j = index(after: i)
|
||||
while j != subrange.upperBound {
|
||||
if try !belongsInSecondPartition(self[j]) {
|
||||
@@ -114,7 +115,7 @@ extension MutableCollection {
|
||||
}
|
||||
formIndex(after: &j)
|
||||
}
|
||||
|
||||
|
||||
return i
|
||||
}
|
||||
}
|
||||
@@ -189,7 +190,7 @@ extension Collection {
|
||||
) rethrows -> Index {
|
||||
var n = count
|
||||
var l = startIndex
|
||||
|
||||
|
||||
while n > 0 {
|
||||
let half = n / 2
|
||||
let mid = index(l, offsetBy: half)
|
||||
@@ -203,4 +204,3 @@ extension Collection {
|
||||
return l
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,43 +9,109 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// nextPermutation()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension MutableCollection
|
||||
where Self: BidirectionalCollection, Element: Comparable {
|
||||
/// Permutes this collection's elements through all the lexical orderings.
|
||||
///
|
||||
/// Call `nextPermutation()` repeatedly starting with the collection in
|
||||
/// sorted order. When the full cycle of all permutations has been completed,
|
||||
/// the collection will be back in sorted order and this method will return
|
||||
/// `false`.
|
||||
///
|
||||
/// - Returns: A Boolean value indicating whether the collection still has
|
||||
/// remaining permutations. When this method returns `false`, the collection
|
||||
/// is in ascending order according to `areInIncreasingOrder`.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
internal mutating func nextPermutation(upperBound: Index? = nil) -> Bool {
|
||||
// Ensure we have > 1 element in the collection.
|
||||
guard !isEmpty else { return false }
|
||||
var i = index(before: endIndex)
|
||||
if i == startIndex { return false }
|
||||
|
||||
let upperBound = upperBound ?? endIndex
|
||||
|
||||
while true {
|
||||
let ip1 = i
|
||||
formIndex(before: &i)
|
||||
|
||||
// Find the last ascending pair (ie. ..., a, b, ... where a < b)
|
||||
if self[i] < self[ip1] {
|
||||
// Find the last element greater than self[i]
|
||||
// This is _always_ at most `ip1` due to if statement above
|
||||
let j = lastIndex(where: { self[i] < $0 })!
|
||||
|
||||
// At this point we have something like this:
|
||||
// 0, 1, 4, 3, 2
|
||||
// ^ ^
|
||||
// i j
|
||||
swapAt(i, j)
|
||||
self.reverse(subrange: ip1..<endIndex)
|
||||
|
||||
// Only return if we've made a change within ..<upperBound region
|
||||
if i < upperBound {
|
||||
return true
|
||||
} else {
|
||||
i = index(before: endIndex)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if i == startIndex {
|
||||
self.reverse()
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// struct Permutations<Base>
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence of all the permutations of a collection's elements.
|
||||
public struct Permutations<Base: Collection> {
|
||||
/// The base collection to iterate over for permutations.
|
||||
public let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let baseCount: Int
|
||||
|
||||
|
||||
/// The range of accepted sizes of permutations.
|
||||
/// - Note: This may be empty if the attempted range entirely exceeds the
|
||||
/// bounds of the size of the `base` collection.
|
||||
@usableFromInline
|
||||
internal let kRange: Range<Int>
|
||||
|
||||
|
||||
/// Initializes a `Permutations` for all permutations of `base` of size `k`.
|
||||
/// - Parameters:
|
||||
/// - base: The collection to iterate over for permutations
|
||||
/// - k: The expected size of each permutation, or `nil` (default) to
|
||||
/// iterate over all permutations of the same size as the base collection.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal init(_ base: Base, k: Int? = nil) {
|
||||
let kRange: ClosedRange<Int>?
|
||||
if let countToChoose = k {
|
||||
kRange = countToChoose ... countToChoose
|
||||
kRange = countToChoose...countToChoose
|
||||
} else {
|
||||
kRange = nil
|
||||
}
|
||||
self.init(base, kRange: kRange)
|
||||
}
|
||||
|
||||
|
||||
/// Initializes a `Permutations` for all combinations of `base` of sizes
|
||||
/// within a given range.
|
||||
/// - Parameters:
|
||||
/// - base: The collection to iterate over for permutations.
|
||||
/// - kRange: The range of accepted sizes of permutations, or `nil` to
|
||||
/// iterate over all permutations of the same size as the base collection.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal init<R: RangeExpression>(
|
||||
_ base: Base, kRange: R?
|
||||
) where R.Bound == Int {
|
||||
@@ -53,11 +119,11 @@ public struct Permutations<Base: Collection> {
|
||||
let baseCount = base.count
|
||||
self.baseCount = baseCount
|
||||
let upperBound = baseCount + 1
|
||||
self.kRange = kRange?.relative(to: 0 ..< .max)
|
||||
.clamped(to: 0 ..< upperBound) ??
|
||||
baseCount ..< upperBound
|
||||
self.kRange =
|
||||
kRange?.relative(to: 0 ..< .max)
|
||||
.clamped(to: 0..<upperBound) ?? baseCount..<upperBound
|
||||
}
|
||||
|
||||
|
||||
/// The total number of permutations.
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
@@ -71,35 +137,35 @@ extension Permutations: Sequence {
|
||||
/// The iterator for a `Permutations` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var base: Base
|
||||
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let baseCount: Int
|
||||
|
||||
|
||||
/// The current range of accepted sizes of permutations.
|
||||
/// - Note: The range is contracted until empty while iterating over
|
||||
/// permutations of different sizes. When the range is empty, iteration is
|
||||
/// finished.
|
||||
@usableFromInline
|
||||
internal var kRange: Range<Int>
|
||||
|
||||
|
||||
/// Whether or not iteration is finished (`kRange` is empty)
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal var isFinished: Bool {
|
||||
return kRange.isEmpty
|
||||
}
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal init(_ permutations: Permutations) {
|
||||
self.base = permutations.base
|
||||
self.baseCount = permutations.baseCount
|
||||
self.kRange = permutations.kRange
|
||||
self.indexes = Array(permutations.base.indices)
|
||||
}
|
||||
|
||||
|
||||
/// Advances the `indexes` array such that the first `countToChoose`
|
||||
/// elements contain the next lexicographic ordering of elements.
|
||||
///
|
||||
@@ -111,48 +177,48 @@ extension Permutations: Sequence {
|
||||
/// is in ascending order.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal mutating func nextState() -> Bool {
|
||||
let countToChoose = self.kRange.lowerBound
|
||||
let edge = countToChoose - 1
|
||||
|
||||
|
||||
// Find first index greater than the one at `edge`.
|
||||
if let i = indexes[countToChoose...].firstIndex(where: { indexes[edge] < $0 }) {
|
||||
indexes.swapAt(edge, i)
|
||||
} else {
|
||||
indexes.reverse(subrange: countToChoose ..< indexes.endIndex)
|
||||
|
||||
indexes.reverse(subrange: countToChoose..<indexes.endIndex)
|
||||
|
||||
// Find last increasing pair below `edge`.
|
||||
// TODO: This could be indexes[..<edge].adjacentPairs().lastIndex(where: ...)
|
||||
var lastAscent = edge - 1
|
||||
while (lastAscent >= 0 && indexes[lastAscent] >= indexes[lastAscent + 1]) {
|
||||
while lastAscent >= 0 && indexes[lastAscent] >= indexes[lastAscent + 1] {
|
||||
lastAscent -= 1
|
||||
}
|
||||
if lastAscent < 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
// Find rightmost index less than that at `lastAscent`.
|
||||
if let i = indexes[lastAscent...].lastIndex(where: { indexes[lastAscent] < $0 }) {
|
||||
indexes.swapAt(lastAscent, i)
|
||||
}
|
||||
indexes.reverse(subrange: (lastAscent + 1) ..< indexes.endIndex)
|
||||
indexes.reverse(subrange: (lastAscent + 1)..<indexes.endIndex)
|
||||
}
|
||||
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> [Base.Element]? {
|
||||
guard !isFinished else { return nil }
|
||||
|
||||
|
||||
/// Advances `kRange` by incrementing its `lowerBound` until the range is
|
||||
/// empty, when iteration is finished.
|
||||
func advanceKRange() {
|
||||
kRange.removeFirst()
|
||||
indexes = Array(base.indices)
|
||||
}
|
||||
|
||||
|
||||
let countToChoose = self.kRange.lowerBound
|
||||
if countToChoose == 0 {
|
||||
defer {
|
||||
@@ -160,7 +226,7 @@ extension Permutations: Sequence {
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
|
||||
let permutesFullCollection = (countToChoose == baseCount)
|
||||
if permutesFullCollection {
|
||||
// If we're permuting the full collection, each iteration is just a
|
||||
@@ -185,7 +251,7 @@ extension Permutations: Sequence {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(self)
|
||||
@@ -194,54 +260,6 @@ extension Permutations: Sequence {
|
||||
|
||||
extension Permutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// nextPermutation()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension MutableCollection
|
||||
where Self: BidirectionalCollection, Element: Comparable
|
||||
{
|
||||
/// Permutes this collection's elements through all the lexical orderings.
|
||||
///
|
||||
/// Call `nextPermutation()` repeatedly starting with the collection in
|
||||
/// sorted order. When the full cycle of all permutations has been completed,
|
||||
/// the collection will be back in sorted order and this method will return
|
||||
/// `false`.
|
||||
///
|
||||
/// - Returns: A Boolean value indicating whether the collection still has
|
||||
/// remaining permutations. When this method returns `false`, the collection
|
||||
/// is in ascending order according to `areInIncreasingOrder`.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@usableFromInline
|
||||
internal mutating func nextPermutation() -> Bool {
|
||||
// Ensure we have > 1 element in the collection.
|
||||
guard !isEmpty else { return false }
|
||||
var i = index(before: endIndex)
|
||||
if i == startIndex { return false }
|
||||
|
||||
while true {
|
||||
let ip1 = i
|
||||
formIndex(before: &i)
|
||||
|
||||
if self[i] < self[ip1] {
|
||||
var j = index(before: endIndex)
|
||||
while self[i] >= self[j] {
|
||||
formIndex(before: &j)
|
||||
}
|
||||
swapAt(i, j)
|
||||
self.reverse(subrange: ip1 ..< endIndex)
|
||||
return true
|
||||
}
|
||||
|
||||
if i == startIndex {
|
||||
self.reverse()
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// permutations(ofCount:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
@@ -268,41 +286,48 @@ extension Collection {
|
||||
/// // Davide, Celeste
|
||||
///
|
||||
/// This example prints _all_ the permutations (including an empty array) from
|
||||
/// the an array of numbers:
|
||||
/// an array of numbers:
|
||||
///
|
||||
/// let numbers = [10, 20, 30]
|
||||
/// for perm in numbers.permutations(ofCount: 0...) {
|
||||
/// print(perm)
|
||||
/// }
|
||||
/// // []
|
||||
/// // [10]
|
||||
/// // [20]
|
||||
/// // [30]
|
||||
/// // [10, 20]
|
||||
/// // [10, 30]
|
||||
/// // [20, 10]
|
||||
/// // [20, 30]
|
||||
/// // [30, 10]
|
||||
/// // [30, 20]
|
||||
/// // [10, 20, 30]
|
||||
/// // [10, 30, 20]
|
||||
/// // [20, 10, 30]
|
||||
/// // [20, 30, 10]
|
||||
/// // [30, 10, 20]
|
||||
/// // [30, 20, 10]
|
||||
/// for perm in numbers.permutations(ofCount: 0...) {
|
||||
/// print(perm)
|
||||
/// }
|
||||
/// // []
|
||||
/// // [10]
|
||||
/// // [20]
|
||||
/// // [30]
|
||||
/// // [10, 20]
|
||||
/// // [10, 30]
|
||||
/// // [20, 10]
|
||||
/// // [20, 30]
|
||||
/// // [30, 10]
|
||||
/// // [30, 20]
|
||||
/// // [10, 20, 30]
|
||||
/// // [10, 30, 20]
|
||||
/// // [20, 10, 30]
|
||||
/// // [20, 30, 10]
|
||||
/// // [30, 10, 20]
|
||||
/// // [30, 20, 10]
|
||||
///
|
||||
/// - Parameter kRange: The number of elements to include in each permutation.
|
||||
/// The returned permutations are in ascending order by length, and then
|
||||
/// lexicographically within each group of the same length.
|
||||
///
|
||||
/// - Parameter kRange: A range of the number of elements to include in each
|
||||
/// permutation. `kRange` can be any integer range expression, and is
|
||||
/// clamped to the number of elements in this collection. Passing a range
|
||||
/// covering sizes greater than the number of elements in this collection
|
||||
/// results in an empty sequence.
|
||||
///
|
||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||
/// is the number of elements in the base collection, since `Permutations`
|
||||
/// accesses the `count` of the base collection.
|
||||
/// is the number of elements in the base collection, since `Permutations`
|
||||
/// accesses the `count` of the base collection.
|
||||
@inlinable
|
||||
public func permutations<R: RangeExpression>(
|
||||
ofCount kRange: R
|
||||
) -> Permutations<Self> where R.Bound == Int {
|
||||
return Permutations(self, kRange: kRange)
|
||||
}
|
||||
|
||||
|
||||
/// Returns a collection of the permutations of this collection of the
|
||||
/// specified length.
|
||||
///
|
||||
@@ -346,11 +371,12 @@ extension Collection {
|
||||
///
|
||||
/// - Parameter k: The number of elements to include in each permutation.
|
||||
/// If `k` is `nil`, the resulting sequence represents permutations of this
|
||||
/// entire collection.
|
||||
/// entire collection. If `k` is greater than the number of elements in
|
||||
/// this collection, the resulting sequence is empty.
|
||||
///
|
||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||
/// is the number of elements in the base collection, since `Permutations`
|
||||
/// accesses the `count` of the base collection.
|
||||
/// is the number of elements in the base collection, since `Permutations`
|
||||
/// accesses the `count` of the base collection.
|
||||
@inlinable
|
||||
public func permutations(ofCount k: Int? = nil) -> Permutations<Self> {
|
||||
precondition(
|
||||
@@ -359,3 +385,195 @@ extension Collection {
|
||||
return Permutations(self, k: k)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// uniquePermutations()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence of the unique permutations of the elements of a sequence or
|
||||
/// collection.
|
||||
///
|
||||
/// To create a `UniquePermutations` instance, call one of the
|
||||
/// `uniquePermutations` methods on your collection.
|
||||
public struct UniquePermutations<Base: Collection> {
|
||||
/// The base collection to iterate over for permutations.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
|
||||
@usableFromInline
|
||||
internal let kRange: Range<Int>
|
||||
}
|
||||
|
||||
extension UniquePermutations where Base.Element: Hashable {
|
||||
@inlinable
|
||||
internal static func _indexes(_ base: Base) -> [Base.Index] {
|
||||
let firstIndexesAndCountsByElement = Dictionary(
|
||||
base.indices.lazy.map { (base[$0], ($0, 1)) },
|
||||
uniquingKeysWith: { indexAndCount, _ in (indexAndCount.0, indexAndCount.1 + 1) })
|
||||
|
||||
return firstIndexesAndCountsByElement
|
||||
.values.sorted(by: { $0.0 < $1.0 })
|
||||
.flatMap { index, count in repeatElement(index, count: count) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal init(_ elements: Base) {
|
||||
self.indexes = Self._indexes(elements)
|
||||
self.base = elements
|
||||
self.kRange = self.indexes.count..<(self.indexes.count + 1)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal init<R: RangeExpression>(_ base: Base, _ range: R)
|
||||
where R.Bound == Int {
|
||||
self.indexes = Self._indexes(base)
|
||||
self.base = base
|
||||
|
||||
let upperBound = self.indexes.count + 1
|
||||
self.kRange = range.relative(to: 0 ..< .max)
|
||||
.clamped(to: 0..<upperBound)
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquePermutations: Sequence {
|
||||
/// The iterator for a `UniquePermutations` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
|
||||
@usableFromInline
|
||||
internal var lengths: Range<Int>
|
||||
|
||||
@usableFromInline
|
||||
internal var initial = true
|
||||
|
||||
@inlinable
|
||||
internal init(_ elements: Base, indexes: [Base.Index], lengths: Range<Int>) {
|
||||
self.base = elements
|
||||
self.indexes = indexes
|
||||
self.lengths = lengths
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> [Base.Element]? {
|
||||
// In the end case, `lengths` is an empty range.
|
||||
if lengths.isEmpty {
|
||||
return nil
|
||||
}
|
||||
|
||||
// The first iteration must produce the original sorted array, before any
|
||||
// permutations. We skip the permutation the first time so that we can
|
||||
// always mutate the array _before_ returning a slice, which avoids
|
||||
// copying when possible.
|
||||
if initial {
|
||||
initial = false
|
||||
return indexes[..<lengths.lowerBound].map { base[$0] }
|
||||
}
|
||||
|
||||
if !indexes.nextPermutation(upperBound: lengths.lowerBound) {
|
||||
lengths.removeFirst()
|
||||
|
||||
if lengths.isEmpty {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return indexes[..<lengths.lowerBound].map { base[$0] }
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(base, indexes: indexes, lengths: kRange)
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquePermutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
extension Collection where Element: Hashable {
|
||||
/// Returns a sequence of the unique permutations of this sequence of the
|
||||
/// specified length.
|
||||
///
|
||||
/// Use this method to iterate over the unique permutations of a sequence
|
||||
/// with repeating elements. This example prints every unique two-element
|
||||
/// permutation of an array of numbers:
|
||||
///
|
||||
/// let numbers = [1, 1, 2]
|
||||
/// for perm in numbers.uniquePermutations(ofCount: 2) {
|
||||
/// print(perm)
|
||||
/// }
|
||||
/// // [1, 1]
|
||||
/// // [1, 2]
|
||||
/// // [2, 1]
|
||||
///
|
||||
/// By contrast, the `permutations(ofCount:)` method permutes a collection's
|
||||
/// elements by position, and can include permutations with equal elements
|
||||
/// in each permutation:
|
||||
///
|
||||
/// for perm in numbers.permutations(ofCount: 2)
|
||||
/// print(perm)
|
||||
/// }
|
||||
/// // [1, 1]
|
||||
/// // [1, 1]
|
||||
/// // [1, 2]
|
||||
/// // [1, 2]
|
||||
/// // [2, 1]
|
||||
/// // [2, 1]
|
||||
///
|
||||
/// The returned permutations are in lexicographically sorted order.
|
||||
///
|
||||
/// - Parameter k: The number of elements to include in each permutation.
|
||||
/// If `k` is `nil`, the resulting sequence represents permutations of this
|
||||
/// entire collection. If `k` is greater than the number of elements in
|
||||
/// this collection, the resulting sequence is empty.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the number of elements in this
|
||||
/// collection.
|
||||
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self> {
|
||||
if let k = k {
|
||||
return UniquePermutations(self, k..<(k + 1))
|
||||
} else {
|
||||
return UniquePermutations(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a collection of the unique permutations of this sequence with
|
||||
/// lengths in the specified range.
|
||||
///
|
||||
/// Use this method to iterate over the unique permutations of a sequence
|
||||
/// with repeating elements. This example prints every unique permutation
|
||||
/// of an array of numbers with lengths through 2 elements:
|
||||
///
|
||||
/// let numbers = [1, 1, 2]
|
||||
/// for perm in numbers.uniquePermutations(ofCount: ...2) {
|
||||
/// print(perm)
|
||||
/// }
|
||||
/// // []
|
||||
/// // [1]
|
||||
/// // [2]
|
||||
/// // [1, 1]
|
||||
/// // [1, 2]
|
||||
/// // [2, 1]
|
||||
///
|
||||
/// The returned permutations are in ascending order by length, and then
|
||||
/// lexicographically within each group of the same length.
|
||||
///
|
||||
/// - Parameter kRange: A range of the number of elements to include in each
|
||||
/// permutation. `kRange` can be any integer range expression, and is
|
||||
/// clamped to the number of elements in this collection. Passing a range
|
||||
/// covering sizes greater than the number of elements in this collection
|
||||
/// results in an empty sequence.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the number of elements in this
|
||||
/// collection.
|
||||
public func uniquePermutations<R: RangeExpression>(ofCount kRange: R) -> UniquePermutations<Self>
|
||||
where R.Bound == Int {
|
||||
UniquePermutations(self, kRange)
|
||||
}
|
||||
}
|
||||
@@ -12,11 +12,14 @@
|
||||
/// A sequence that represents the product of two sequences' elements.
|
||||
public struct Product2<Base1: Sequence, Base2: Collection> {
|
||||
/// The outer sequence in the product.
|
||||
public let base1: Base1
|
||||
/// The inner sequence in the product.
|
||||
public let base2: Base2
|
||||
|
||||
@usableFromInline
|
||||
internal let base1: Base1
|
||||
|
||||
/// The inner sequence in the product.
|
||||
@usableFromInline
|
||||
internal let base2: Base2
|
||||
|
||||
@inlinable
|
||||
internal init(_ base1: Base1, _ base2: Base2) {
|
||||
self.base1 = base1
|
||||
self.base2 = base2
|
||||
@@ -24,6 +27,8 @@ public struct Product2<Base1: Sequence, Base2: Collection> {
|
||||
}
|
||||
|
||||
extension Product2: Sequence {
|
||||
public typealias Element = (Base1.Element, Base2.Element)
|
||||
|
||||
/// The iterator for a `Product2` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
@@ -35,16 +40,19 @@ extension Product2: Sequence {
|
||||
@usableFromInline
|
||||
internal let base2: Base2
|
||||
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal init(_ c: Product2) {
|
||||
self.base2 = c.base2
|
||||
self.i1 = c.base1.makeIterator()
|
||||
self.i2 = c.base2.makeIterator()
|
||||
self.element1 = nil
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> (Base1.Element, Base2.Element)? {
|
||||
public mutating func next() -> (
|
||||
Base1.Element,
|
||||
Base2.Element
|
||||
)? {
|
||||
// This is the initial state, where i1.next() has never
|
||||
// been called, or the final state, where i1.next() has
|
||||
// already returned nil.
|
||||
@@ -53,21 +61,21 @@ extension Product2: Sequence {
|
||||
// once Base1 is exhausted, return `nil` forever
|
||||
if element1 == nil { return nil }
|
||||
}
|
||||
|
||||
|
||||
// Get the next element from the second sequence, if not
|
||||
// at end.
|
||||
if let element2 = i2.next() {
|
||||
return (element1!, element2)
|
||||
}
|
||||
|
||||
|
||||
// We've reached the end of the second sequence, so:
|
||||
// 1) Get the next element of the first sequence, if exists
|
||||
// 2) Restart iteration of the second sequence
|
||||
// 3) Get the first element of the second sequence, if exists
|
||||
element1 = i1.next()
|
||||
guard let element1 = element1
|
||||
else { return nil }
|
||||
|
||||
else { return nil }
|
||||
|
||||
i2 = base2.makeIterator()
|
||||
if let element2 = i2.next() {
|
||||
return (element1, element2)
|
||||
@@ -89,69 +97,72 @@ extension Product2: Collection where Base1: Collection {
|
||||
internal var i1: Base1.Index
|
||||
@usableFromInline
|
||||
internal var i2: Base2.Index
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal init(i1: Base1.Index, i2: Base2.Index) {
|
||||
self.i1 = i1
|
||||
self.i2 = i2
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
(lhs.i1, lhs.i2) < (rhs.i1, rhs.i2)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
base1.count * base2.count
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(
|
||||
i1: base2.isEmpty ? base1.endIndex : base1.startIndex,
|
||||
i2: base2.startIndex)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
// `base2.startIndex` simplifies index calculations.
|
||||
Index(i1: base1.endIndex, i2: base2.startIndex)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> (Base1.Element, Base2.Element) {
|
||||
public subscript(position: Index) -> (
|
||||
Base1.Element,
|
||||
Base2.Element
|
||||
) {
|
||||
(base1[position.i1], base2[position.i2])
|
||||
}
|
||||
|
||||
|
||||
/// Forms an index from a pair of base indices, normalizing
|
||||
/// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if
|
||||
/// necessary.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal func normalizeIndex(_ i1: Base1.Index, _ i2: Base2.Index) -> Index {
|
||||
i2 == base2.endIndex
|
||||
? Index(i1: base1.index(after: i1), i2: base2.startIndex)
|
||||
: Index(i1: i1, i2: i2)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i.i1 != base1.endIndex, "Can't advance past endIndex")
|
||||
return normalizeIndex(i.i1, base2.index(after: i.i2))
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
guard start.i1 <= end.i1
|
||||
else { return -distance(from: end, to: start) }
|
||||
else { return -distance(from: end, to: start) }
|
||||
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`,
|
||||
// excluding the cycles that `start` and `end` are on.
|
||||
let fullBase2Cycles = base1[start.i1..<end.i1].count - 1
|
||||
|
||||
|
||||
if start.i2 <= end.i2 {
|
||||
// start.i2
|
||||
// v
|
||||
@@ -162,11 +173,11 @@ extension Product2: Collection where Base1: Collection {
|
||||
// end.i1 > [l l l c c c c c c|r r r]
|
||||
// ^
|
||||
// end.i2
|
||||
|
||||
|
||||
let left = base2[..<start.i2].count
|
||||
let center = base2[start.i2..<end.i2].count
|
||||
let right = base2[end.i2...].count
|
||||
|
||||
|
||||
return center + right
|
||||
+ fullBase2Cycles * (left + center + right)
|
||||
+ left + center
|
||||
@@ -180,29 +191,31 @@ extension Product2: Collection where Base1: Collection {
|
||||
// end.i1 > [l l l|c c c c c c r r r]
|
||||
// ^
|
||||
// end.i2
|
||||
|
||||
|
||||
let left = base2[..<end.i2].count
|
||||
let right = base2[start.i2...].count
|
||||
|
||||
|
||||
// We can avoid traversing `base2[end.i2..<start.i2]` if `start` and `end`
|
||||
// are on consecutive cycles.
|
||||
guard fullBase2Cycles > 0 else { return right + left }
|
||||
|
||||
|
||||
let center = base2[end.i2..<start.i2].count
|
||||
return right
|
||||
+ fullBase2Cycles * (left + center + right)
|
||||
+ left
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
guard distance != 0 else { return i }
|
||||
|
||||
|
||||
return distance > 0
|
||||
? offsetForward(i, by: distance)
|
||||
: offsetBackward(i, by: -distance)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
offsetBy distance: Int,
|
||||
@@ -219,39 +232,38 @@ extension Product2: Collection where Base1: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance >= 0)
|
||||
assert(limit >= i)
|
||||
|
||||
|
||||
if limit.i1 == i.i1 {
|
||||
// Delegate to `base2` if the offset is limited to `i.i1`.
|
||||
//
|
||||
// i.i2 limit.i2
|
||||
// v v
|
||||
// i.i1 > [x x x|x x x x x x|x x x]
|
||||
|
||||
|
||||
return base2.index(i.i2, offsetBy: distance, limitedBy: limit.i2)
|
||||
.map { i2 in Index(i1: i.i1, i2: i2) }
|
||||
}
|
||||
|
||||
|
||||
|
||||
if let i2 = base2.index(i.i2, offsetBy: distance, limitedBy: base2.endIndex) {
|
||||
// `distance` does not overflow `base2[i.i2...]`.
|
||||
//
|
||||
@@ -259,14 +271,14 @@ extension Product2: Collection where Base1: Collection {
|
||||
// v v
|
||||
// i.i1 > [x x x|x x x x x x|x x x]
|
||||
// [ |> > > > > >| ] (`distance`)
|
||||
|
||||
|
||||
return normalizeIndex(i.i1, i2)
|
||||
}
|
||||
|
||||
|
||||
let suffixCount = base2[i.i2...].count
|
||||
let remaining = distance - suffixCount
|
||||
let nextI1 = base1.index(after: i.i1)
|
||||
|
||||
|
||||
if limit.i1 == nextI1 {
|
||||
// Delegate to `base2` if the offset is limited to `nextI1`.
|
||||
//
|
||||
@@ -276,11 +288,11 @@ extension Product2: Collection where Base1: Collection {
|
||||
// nextI1 > [x x x x x x x x x|x x x]
|
||||
// ^
|
||||
// limit.i2
|
||||
|
||||
|
||||
return base2.index(base2.startIndex, offsetBy: remaining, limitedBy: limit.i2)
|
||||
.map { i2 in Index(i1: nextI1, i2: i2) }
|
||||
}
|
||||
|
||||
|
||||
if let i2 = base2.index(base2.startIndex, offsetBy: remaining, limitedBy: i.i2) {
|
||||
// `remaining` does not overflow `base2[..<i.i2]`.
|
||||
//
|
||||
@@ -292,43 +304,43 @@ extension Product2: Collection where Base1: Collection {
|
||||
// nextI1 > [x x x|x x x x x x x x x]
|
||||
// ^
|
||||
// i2
|
||||
|
||||
|
||||
return Index(i1: nextI1, i2: i2)
|
||||
}
|
||||
|
||||
|
||||
let prefixCount = base2[..<i.i2].count
|
||||
let base2Count = prefixCount + suffixCount
|
||||
let base1Distance = remaining / base2Count
|
||||
|
||||
|
||||
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.
|
||||
let base2Distance = remaining % base2Count
|
||||
|
||||
|
||||
let base2Limit = limit.i1 == i1 ? limit.i2 : base2.endIndex
|
||||
return base2.index(base2.startIndex, offsetBy: base2Distance, limitedBy: base2Limit)
|
||||
.map { i2 in Index(i1: i1, i2: i2) }
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance >= 0)
|
||||
assert(limit <= i)
|
||||
|
||||
|
||||
if limit.i1 == i.i1 {
|
||||
// Delegate to `base2` if the offset is limited to `i.i1`.
|
||||
//
|
||||
// limit.i2 i.i2
|
||||
// v v
|
||||
// i.i1 > [x x x|x x x x x x|x x x]
|
||||
|
||||
|
||||
return base2.index(i.i2, offsetBy: -distance, limitedBy: limit.i2)
|
||||
.map { i2 in Index(i1: i.i1, i2: i2) }
|
||||
}
|
||||
|
||||
|
||||
if let i2 = base2.index(i.i2, offsetBy: -distance, limitedBy: base2.startIndex) {
|
||||
// `distance` does not underflow `base2[..<i.i2]`.
|
||||
//
|
||||
@@ -336,14 +348,14 @@ extension Product2: Collection where Base1: Collection {
|
||||
// v v
|
||||
// i.i1 > [x x x|x x x x x x|x x x]
|
||||
// [ |< < < < < <| ] (`distance`)
|
||||
|
||||
|
||||
return Index(i1: i.i1, i2: i2)
|
||||
}
|
||||
|
||||
|
||||
let prefixCount = base2[..<i.i2].count
|
||||
let remaining = distance - prefixCount
|
||||
let previousI1 = base1.index(i.i1, offsetBy: -1)
|
||||
|
||||
|
||||
if limit.i1 == previousI1 {
|
||||
// Delegate to `base2` if the offset is limited to `previousI1`.
|
||||
//
|
||||
@@ -353,11 +365,11 @@ extension Product2: Collection where Base1: Collection {
|
||||
// i.i1 > [x x x x x x x x x|x x x]
|
||||
// ^
|
||||
// i.i2
|
||||
|
||||
|
||||
return base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: limit.i2)
|
||||
.map { i2 in Index(i1: previousI1, i2: i2) }
|
||||
}
|
||||
|
||||
|
||||
if let i2 = base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: i.i2) {
|
||||
// `remaining` does not underflow `base2[i.i2...]`.
|
||||
//
|
||||
@@ -369,17 +381,17 @@ extension Product2: Collection where Base1: Collection {
|
||||
// i.i1 > [x x x|x x x x x x x x x]
|
||||
// ^
|
||||
// i.i2
|
||||
|
||||
|
||||
return Index(i1: previousI1, i2: i2)
|
||||
}
|
||||
|
||||
|
||||
let suffixCount = base2[i.i2...].count
|
||||
let base2Count = prefixCount + suffixCount
|
||||
let base1Distance = remaining / base2Count
|
||||
|
||||
|
||||
// The distance from `base2.endIndex` to the target.
|
||||
let base2Distance = remaining % base2Count
|
||||
|
||||
|
||||
if base2Distance == 0 {
|
||||
// We end up exactly between two cycles, so `base1Distance` would
|
||||
// overshoot the target by 1.
|
||||
@@ -392,7 +404,7 @@ extension Product2: Collection where Base1: Collection {
|
||||
// i.i1 > [x x x|x x x x x x x x x]
|
||||
// ^
|
||||
// i.i2
|
||||
|
||||
|
||||
if let i1 = base1.index(previousI1, offsetBy: -(base1Distance - 1), limitedBy: limit.i1) {
|
||||
let index = Index(i1: i1, i2: base2.startIndex)
|
||||
return index < limit ? nil : index
|
||||
@@ -400,10 +412,10 @@ extension Product2: Collection where Base1: Collection {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
return base2.index(base2.endIndex, offsetBy: -base2Distance, limitedBy: base2Limit)
|
||||
.map { i2 in Index(i1: i1, i2: i2) }
|
||||
@@ -411,12 +423,12 @@ extension Product2: Collection where Base1: Collection {
|
||||
}
|
||||
|
||||
extension Product2: BidirectionalCollection
|
||||
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
|
||||
{
|
||||
where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(i != startIndex,
|
||||
"Can't move before startIndex")
|
||||
precondition(
|
||||
i != startIndex,
|
||||
"Can't move before startIndex")
|
||||
if i.i2 == base2.startIndex {
|
||||
return Index(
|
||||
i1: base1.index(before: i.i1),
|
||||
@@ -428,11 +440,9 @@ extension Product2: BidirectionalCollection
|
||||
}
|
||||
|
||||
extension Product2: RandomAccessCollection
|
||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||
|
||||
extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {}
|
||||
extension Product2: Equatable where Base1: Equatable, Base2: Equatable {}
|
||||
extension Product2: Hashable where Base1: Hashable, Base2: Hashable {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// product(_:_:)
|
||||
|
||||
@@ -10,8 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// For log(_:) and root(_:_:)
|
||||
@_implementationOnly
|
||||
import RealModule
|
||||
@_implementationOnly import RealModule
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// randomStableSample(count:)
|
||||
@@ -33,13 +32,13 @@ extension Collection {
|
||||
count k: Int, using rng: inout G
|
||||
) -> [Element] {
|
||||
guard k > 0 else { return [] }
|
||||
|
||||
|
||||
var remainingCount = count
|
||||
guard k < remainingCount else { return Array(self) }
|
||||
|
||||
|
||||
var result: [Element] = []
|
||||
result.reserveCapacity(k)
|
||||
|
||||
|
||||
var i = startIndex
|
||||
var countToSelect = k
|
||||
while countToSelect > 0 {
|
||||
@@ -52,10 +51,10 @@ extension Collection {
|
||||
formIndex(after: &i)
|
||||
remainingCount -= 1
|
||||
}
|
||||
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
/// Randomly selects the specified number of elements from this collection,
|
||||
/// maintaining their relative order.
|
||||
///
|
||||
@@ -120,22 +119,22 @@ extension Collection {
|
||||
var w = 1.0
|
||||
var result: [Element] = []
|
||||
result.reserveCapacity(k)
|
||||
|
||||
|
||||
// Fill the reservoir with the first `k` elements.
|
||||
var i = startIndex
|
||||
while i < endIndex, result.count < k {
|
||||
result.append(self[i])
|
||||
formIndex(after: &i)
|
||||
}
|
||||
|
||||
|
||||
while i < endIndex {
|
||||
// Calculate the next value of w.
|
||||
w *= nextW(k: k, using: &rng)
|
||||
|
||||
|
||||
// Find index of the next element to swap into the reservoir.
|
||||
let offset = nextOffset(w: w, using: &rng)
|
||||
i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex
|
||||
|
||||
|
||||
if i < endIndex {
|
||||
// Swap selected element with a randomly chosen one in the reservoir.
|
||||
let j = Int.random(in: 0..<result.count, using: &rng)
|
||||
@@ -143,12 +142,12 @@ extension Collection {
|
||||
formIndex(after: &i)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// FIXME: necessary?
|
||||
result.shuffle(using: &rng)
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
/// Randomly selects the specified number of elements from this collection.
|
||||
///
|
||||
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
|
||||
@@ -186,11 +185,11 @@ extension Sequence {
|
||||
count k: Int, using rng: inout G
|
||||
) -> [Element] {
|
||||
guard k > 0 else { return [] }
|
||||
|
||||
|
||||
var w = 1.0
|
||||
var result: [Element] = []
|
||||
result.reserveCapacity(k)
|
||||
|
||||
|
||||
// Fill the reservoir with the first `k` elements.
|
||||
var iterator = makeIterator()
|
||||
while result.count < k, let el = iterator.next() {
|
||||
@@ -200,26 +199,26 @@ extension Sequence {
|
||||
while true {
|
||||
// Calculate the next value of w.
|
||||
w *= nextW(k: k, using: &rng)
|
||||
|
||||
|
||||
// Find the offset of the next element to swap into the reservoir.
|
||||
var offset = nextOffset(w: w, using: &rng)
|
||||
|
||||
|
||||
// Skip over `offset` elements to find the selected element.
|
||||
while offset > 0, let _ = iterator.next() {
|
||||
offset -= 1
|
||||
}
|
||||
guard let nextElement = iterator.next() else { break }
|
||||
|
||||
|
||||
// Swap selected element with a randomly chosen one in the reservoir.
|
||||
let j = Int.random(in: 0..<result.count, using: &rng)
|
||||
result[j] = nextElement
|
||||
}
|
||||
|
||||
|
||||
// FIXME: necessary?
|
||||
result.shuffle(using: &rng)
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
/// Randomly selects the specified number of elements from this sequence.
|
||||
///
|
||||
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
|
||||
|
||||
@@ -0,0 +1,645 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// MARK: - Exclusive Reductions
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
|
||||
/// Returns a sequence containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
/// This can be seen as applying the reduce function to each element and
|
||||
/// providing the initial value followed by these results as a sequence.
|
||||
///
|
||||
/// ```
|
||||
/// let runningTotal = [1, 2, 3, 4].lazy.reductions(0, +)
|
||||
/// print(Array(runningTotal))
|
||||
///
|
||||
/// // prints [0, 1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - initial: The value to use as the initial value.
|
||||
/// - transform: A closure that combines the previously reduced result and
|
||||
/// the next element in the receiving sequence.
|
||||
/// - Returns: A sequence of the initial value followed by the reduced
|
||||
/// elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func reductions<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: @escaping (Result, Element) -> Result
|
||||
) -> ExclusiveReductions<Result, Self> {
|
||||
return reductions(into: initial) { result, element in
|
||||
result = transform(result, element)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a sequence containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
/// This can be seen as applying the reduce function to each element and
|
||||
/// providing the initial value followed by these results as a sequence.
|
||||
///
|
||||
/// ```
|
||||
/// let runningTotal = [1, 2, 3, 4].lazy.reductions(into: 0, +)
|
||||
/// print(Array(runningTotal))
|
||||
///
|
||||
/// // prints [0, 1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - initial: The value to use as the initial value.
|
||||
/// - transform: A closure that combines the previously reduced result and
|
||||
/// the next element in the receiving sequence.
|
||||
/// - Returns: A sequence of the initial value followed by the reduced
|
||||
/// elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func reductions<Result>(
|
||||
into initial: Result,
|
||||
_ transform: @escaping (inout Result, Element) -> Void
|
||||
) -> ExclusiveReductions<Result, Self> {
|
||||
ExclusiveReductions(base: self, initial: initial, transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns an array containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
/// This can be seen as applying the reduce function to each element and
|
||||
/// providing the initial value followed by these results as a sequence.
|
||||
///
|
||||
/// ```
|
||||
/// let runningTotal = [1, 2, 3, 4].reductions(0, +)
|
||||
/// print(runningTotal)
|
||||
///
|
||||
/// // prints [0, 1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// When `reductions(_:_:)` is called, the following steps occur:
|
||||
///
|
||||
/// 1. The `initial` result is added to an array of results.
|
||||
/// 2. The `transform` closure is called with the `initial` result and the
|
||||
/// first element of the sequence, appending the result to the array.
|
||||
/// 3. The closure is called again repeatedly with the updated accumulating
|
||||
/// result and each element of the sequence, adding each result to the
|
||||
/// array.
|
||||
/// 4. When the sequence is exhausted, the results array is returned to the
|
||||
/// caller.
|
||||
///
|
||||
/// If the sequence has no elements, `transform` is never executed and
|
||||
/// an array containing only the `initial` result is returned.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - initial: The value to use as the initial value.
|
||||
/// - transform: A closure that combines the previously reduced result and
|
||||
/// the next element in the receiving sequence.
|
||||
/// - Returns: An array of the initial value followed by the reduced elements.
|
||||
///
|
||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||
@inlinable
|
||||
public func reductions<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: (Result, Element) throws -> Result
|
||||
) rethrows -> [Result] {
|
||||
return try reductions(into: initial) { result, element in
|
||||
result = try transform(result, element)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an array containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
/// This can be seen as applying the reduce function to each element and
|
||||
/// providing the initial value followed by these results as a sequence.
|
||||
///
|
||||
/// ```
|
||||
/// let runningTotal = [1, 2, 3, 4].reductions(into: 0, +)
|
||||
/// print(runningTotal)
|
||||
///
|
||||
/// // prints [0, 1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// When `reductions(into:_:_)` is called, the following steps occur:
|
||||
///
|
||||
/// 1. The `initial` result is added to an array of results.
|
||||
/// 2. The `transform` closure is called with the `initial` result and the
|
||||
/// first element of the sequence, appending the result to the array.
|
||||
/// 3. The closure is called again repeatedly with the updated accumulating
|
||||
/// result and each element of the sequence, adding each result to the
|
||||
/// array.
|
||||
/// 4. When the sequence is exhausted, the results array is returned to the
|
||||
/// caller.
|
||||
///
|
||||
/// If the sequence has no elements, `transform` is never executed and
|
||||
/// an array containing only the `initial` result is returned.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - initial: The value to use as the initial value.
|
||||
/// - transform: A closure that combines the previously reduced result and
|
||||
/// the next element in the receiving sequence.
|
||||
/// - Returns: An array of the initial value followed by the reduced elements.
|
||||
///
|
||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||
@inlinable
|
||||
public func reductions<Result>(
|
||||
into initial: Result,
|
||||
_ transform: (inout Result, Element) throws -> Void
|
||||
) rethrows -> [Result] {
|
||||
|
||||
var output = [Result]()
|
||||
output.reserveCapacity(underestimatedCount + 1)
|
||||
output.append(initial)
|
||||
|
||||
var initial = initial
|
||||
for element in self {
|
||||
try transform(&initial, element)
|
||||
output.append(initial)
|
||||
}
|
||||
|
||||
return output
|
||||
}
|
||||
}
|
||||
|
||||
/// A sequence of applying a transform to the element of a sequence and the
|
||||
/// previously transformed result.
|
||||
public struct ExclusiveReductions<Result, Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let initial: Result
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (inout Result, Base.Element) -> Void
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
initial: Result,
|
||||
transform: @escaping (inout Result, Base.Element) -> Void
|
||||
) {
|
||||
self.base = base
|
||||
self.initial = initial
|
||||
self.transform = transform
|
||||
}
|
||||
}
|
||||
|
||||
extension ExclusiveReductions: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal var current: Result?
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (inout Result, Base.Element) -> Void
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
iterator: Base.Iterator,
|
||||
current: Result? = nil,
|
||||
transform: @escaping (inout Result, Base.Element) -> Void
|
||||
) {
|
||||
self.iterator = iterator
|
||||
self.current = current
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Result? {
|
||||
guard let result = current else { return nil }
|
||||
current = iterator.next().map { element in
|
||||
var result = result
|
||||
transform(&result, element)
|
||||
return result
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(
|
||||
iterator: base.makeIterator(),
|
||||
current: initial,
|
||||
transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension ExclusiveReductions: Collection where Base: Collection {
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let representation: ReductionsIndexRepresentation<Base.Index, Result>
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
_ representation: ReductionsIndexRepresentation<Base.Index, Result>
|
||||
) {
|
||||
self.representation = representation
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.representation < rhs.representation
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index { Index(.start) }
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index { Index(.end) }
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Result {
|
||||
switch position.representation {
|
||||
case .start: return initial
|
||||
case .base(_, let result): return result
|
||||
case .end: fatalError("Cannot get element of end index.")
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
func index(base index: Base.Index, previous: Result) -> Index {
|
||||
guard index != base.endIndex else { return endIndex }
|
||||
var previous = previous
|
||||
transform(&previous, base[index])
|
||||
return Index(.base(index: index, result: previous))
|
||||
}
|
||||
switch i.representation {
|
||||
case .start:
|
||||
return index(base: base.startIndex, previous: initial)
|
||||
case let .base(i, result):
|
||||
return index(base: base.index(after: i), previous: result)
|
||||
case .end:
|
||||
fatalError("Cannot get index after end index.")
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (start.representation, end.representation) {
|
||||
case (.start, .start):
|
||||
return 0
|
||||
case let (.start, .base(index, _)):
|
||||
return base.distance(from: base.startIndex, to: index) + 1
|
||||
case (.start, .end):
|
||||
return base.distance(from: base.startIndex, to: base.endIndex) + 1
|
||||
case let (.base(index, _), .start):
|
||||
return base.distance(from: index, to: base.startIndex) - 1
|
||||
case let (.base(start, _), .base(end, _)):
|
||||
return base.distance(from: start, to: end)
|
||||
case let (.base(index, _), .end):
|
||||
return base.distance(from: index, to: base.endIndex)
|
||||
case (.end, .start):
|
||||
return base.distance(from: base.endIndex, to: base.startIndex) - 1
|
||||
case let (.end, .base(index, _)):
|
||||
return base.distance(from: base.endIndex, to: index)
|
||||
case (.end, .end):
|
||||
return 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ExclusiveReductions: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension ExclusiveReductions: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
|
||||
// MARK: - Inclusive Reductions
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
|
||||
/// Returns a sequence containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
/// This can be seen as applying the reduce function to each element and
|
||||
/// providing the initial value followed by these results as a sequence.
|
||||
///
|
||||
/// ```
|
||||
/// let runningTotal = [1, 2, 3, 4].lazy.reductions(+)
|
||||
/// print(Array(runningTotal))
|
||||
///
|
||||
/// // prints [1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - transform: A closure that combines the previously reduced result and
|
||||
/// the next element in the receiving sequence.
|
||||
/// - Returns: A sequence of the reduced elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func reductions(
|
||||
_ transform: @escaping (Element, Element) -> Element
|
||||
) -> InclusiveReductions<Self> {
|
||||
InclusiveReductions(base: self, transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns an array containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
/// This can be seen as applying the reduce function to each element and
|
||||
/// providing the initial value followed by these results as a sequence.
|
||||
///
|
||||
/// ```
|
||||
/// let runningTotal = [1, 2, 3, 4].reductions(+)
|
||||
/// print(runningTotal)
|
||||
///
|
||||
/// // prints [1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// When `reductions(_:)` is called, the following steps occur:
|
||||
///
|
||||
/// 1. The `transform` closure is called with the first and second elements
|
||||
/// of the sequence, appending the result to an array of results.
|
||||
/// 2. The closure is called again repeatedly with the updated accumulating
|
||||
/// result and the next element of the sequence, adding each result to the
|
||||
/// array.
|
||||
/// 3. When the sequence is exhausted, the results array is returned to the
|
||||
/// caller.
|
||||
///
|
||||
/// If the sequence has no elements, `transform` is never executed and
|
||||
/// an empty array is returned.
|
||||
///
|
||||
/// If the sequence has one element, `transform` is never executed and
|
||||
/// an array containing only that first element is returned.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - transform: A closure that combines the previously reduced result and
|
||||
/// the next element in the receiving sequence.
|
||||
/// - Returns: An array of the reduced elements.
|
||||
///
|
||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||
@inlinable
|
||||
public func reductions(
|
||||
_ transform: (Element, Element) throws -> Element
|
||||
) rethrows -> [Element] {
|
||||
var iterator = makeIterator()
|
||||
guard let initial = iterator.next() else { return [] }
|
||||
return try IteratorSequence(iterator).reductions(initial, transform)
|
||||
}
|
||||
}
|
||||
|
||||
public struct InclusiveReductions<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (Base.Element, Base.Element) -> Base.Element
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
transform: @escaping (Base.Element, Base.Element) -> Base.Element
|
||||
) {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
}
|
||||
}
|
||||
|
||||
extension InclusiveReductions: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal var element: Base.Element?
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (Base.Element, Base.Element) -> Base.Element
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
iterator: Base.Iterator,
|
||||
element: Base.Element? = nil,
|
||||
transform: @escaping (Base.Element, Base.Element) -> Base.Element
|
||||
) {
|
||||
self.iterator = iterator
|
||||
self.element = element
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element? {
|
||||
guard let previous = element else {
|
||||
element = iterator.next()
|
||||
return element
|
||||
}
|
||||
guard let next = iterator.next() else { return nil }
|
||||
element = transform(previous, next)
|
||||
return element
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(
|
||||
iterator: base.makeIterator(),
|
||||
transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension InclusiveReductions: Collection where Base: Collection {
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
_ representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
|
||||
) {
|
||||
self.representation = representation
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.representation < rhs.representation
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
guard base.startIndex != base.endIndex else { return endIndex }
|
||||
return Index(.start)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index { Index(.end) }
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Base.Element {
|
||||
switch position.representation {
|
||||
case .start: return base[base.startIndex]
|
||||
case .base(_, let result): return result
|
||||
case .end: fatalError("Cannot get element of end index.")
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
func index(after i: Base.Index, previous: Base.Element) -> Index {
|
||||
let index = base.index(after: i)
|
||||
guard index != base.endIndex else { return endIndex }
|
||||
return Index(.base(index: index, result: transform(previous, base[index])))
|
||||
}
|
||||
switch i.representation {
|
||||
case .start:
|
||||
return index(after: base.startIndex, previous: base[base.startIndex])
|
||||
case let .base(i, element):
|
||||
return index(after: i, previous: element)
|
||||
case .end:
|
||||
fatalError("Cannot get index after end index.")
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (start.representation, end.representation) {
|
||||
case (.start, .start):
|
||||
return 0
|
||||
case let (.start, .base(index, _)):
|
||||
return base.distance(from: base.startIndex, to: index)
|
||||
case (.start, .end):
|
||||
return base.distance(from: base.startIndex, to: base.endIndex)
|
||||
case let (.base(index, _), .start):
|
||||
return base.distance(from: index, to: base.startIndex)
|
||||
case let (.base(start, _), .base(end, _)):
|
||||
return base.distance(from: start, to: end)
|
||||
case let (.base(index, _), .end):
|
||||
return base.distance(from: index, to: base.endIndex)
|
||||
case (.end, .start):
|
||||
return base.distance(from: base.endIndex, to: base.startIndex)
|
||||
case let (.end, .base(index, _)):
|
||||
return base.distance(from: base.endIndex, to: index)
|
||||
case (.end, .end):
|
||||
return 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension InclusiveReductions: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension InclusiveReductions: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
|
||||
// MARK: - ReductionsIndexRepresentation
|
||||
|
||||
@usableFromInline
|
||||
enum ReductionsIndexRepresentation<BaseIndex: Comparable, Result> {
|
||||
case start
|
||||
case base(index: BaseIndex, result: Result)
|
||||
case end
|
||||
}
|
||||
|
||||
extension ReductionsIndexRepresentation: Equatable {
|
||||
@inlinable
|
||||
static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.start, .start): return true
|
||||
case (.end, .end): return true
|
||||
case let (.base(lhs, _), .base(rhs, _)): return lhs == rhs
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ReductionsIndexRepresentation: Comparable {
|
||||
@inlinable
|
||||
static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (_, .start): return false
|
||||
case (.start, _): return true
|
||||
case (.end, _): return false
|
||||
case (_, .end): return true
|
||||
case let (.base(lhs, _), .base(rhs, _)): return lhs < rhs
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Scan
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
|
||||
@inlinable
|
||||
public func scan<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: @escaping (Result, Element) -> Result
|
||||
) -> ExclusiveReductions<Result, Self> {
|
||||
reductions(initial, transform)
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
|
||||
@inlinable
|
||||
public func scan<Result>(
|
||||
into initial: Result,
|
||||
_ transform: @escaping (inout Result, Element) -> Void
|
||||
) -> ExclusiveReductions<Result, Self> {
|
||||
reductions(into: initial, transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
|
||||
@inlinable
|
||||
public func scan<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: (Result, Element) throws -> Result
|
||||
) rethrows -> [Result] {
|
||||
try reductions(initial, transform)
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
|
||||
@inlinable
|
||||
public func scan<Result>(
|
||||
into initial: Result,
|
||||
_ transform: (inout Result, Element) throws -> Void
|
||||
) rethrows -> [Result] {
|
||||
try reductions(into: initial, transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(_:) instead.")
|
||||
@inlinable
|
||||
public func scan(
|
||||
_ transform: @escaping (Element, Element) -> Element
|
||||
) -> InclusiveReductions<Self> {
|
||||
reductions(transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(_:) instead.")
|
||||
@inlinable
|
||||
public func scan(
|
||||
_ transform: (Element, Element) throws -> Element
|
||||
) rethrows -> [Element] {
|
||||
try reductions(transform)
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
///
|
||||
/// - Postcondition: For returned indices `(lower, upper)`:
|
||||
/// `lower == limit || upper == limit`
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
@discardableResult
|
||||
internal mutating func _reverse(
|
||||
subrange: Range<Index>, until limit: Index
|
||||
@@ -43,7 +43,7 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
}
|
||||
return (lower, upper)
|
||||
}
|
||||
|
||||
|
||||
/// Reverses the elements within the given subrange.
|
||||
///
|
||||
/// This example reverses the numbers within the subrange at the start of the
|
||||
@@ -94,21 +94,20 @@ extension MutableCollection {
|
||||
/// - distance(from: lhs.lowerBound, to: p) == distance(from:
|
||||
/// rhs.lowerBound, to: q)
|
||||
/// - p == lhs.upperBound || q == rhs.upperBound
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal mutating func _swapNonemptySubrangePrefixes(
|
||||
_ lhs: Range<Index>, _ rhs: Range<Index>
|
||||
) -> (Index, Index) {
|
||||
assert(!lhs.isEmpty)
|
||||
assert(!rhs.isEmpty)
|
||||
|
||||
|
||||
var p = lhs.lowerBound
|
||||
var q = rhs.lowerBound
|
||||
repeat {
|
||||
swapAt(p, q)
|
||||
formIndex(after: &p)
|
||||
formIndex(after: &q)
|
||||
}
|
||||
while p != lhs.upperBound && q != rhs.upperBound
|
||||
} while p != lhs.upperBound && q != rhs.upperBound
|
||||
return (p, q)
|
||||
}
|
||||
|
||||
@@ -139,13 +138,14 @@ extension MutableCollection {
|
||||
subrange: Range<Index>,
|
||||
toStartAt newStart: Index
|
||||
) -> Index {
|
||||
var m = newStart, s = subrange.lowerBound
|
||||
var m = newStart
|
||||
var s = subrange.lowerBound
|
||||
let e = subrange.upperBound
|
||||
|
||||
|
||||
// Handle the trivial cases
|
||||
if s == m { return e }
|
||||
if m == e { return s }
|
||||
|
||||
|
||||
// We have two regions of possibly-unequal length that need to be
|
||||
// exchanged. The return value of this method is going to be the
|
||||
// position following that of the element that is currently last
|
||||
@@ -155,7 +155,7 @@ extension MutableCollection {
|
||||
// ^ ^ ^ ^ ^ ^
|
||||
// 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 {
|
||||
// Exchange the leading elements of each region (up to the
|
||||
// length of the shorter region).
|
||||
@@ -167,7 +167,7 @@ extension MutableCollection {
|
||||
// s s1 m m1/e s s1/m m1 e
|
||||
//
|
||||
let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e)
|
||||
|
||||
|
||||
if m1 == e {
|
||||
// Left-hand case: we have moved element j into position. if
|
||||
// we haven't already, we can capture the return value which
|
||||
@@ -177,11 +177,11 @@ extension MutableCollection {
|
||||
// comparison once the return value is known. I'm not sure
|
||||
// it's a worthwhile optimization, though.
|
||||
if ret == e { ret = s1 }
|
||||
|
||||
|
||||
// If both regions were the same size, we're done.
|
||||
if s1 == m { break }
|
||||
}
|
||||
|
||||
|
||||
// Now we have a smaller problem that is also a rotation, so we
|
||||
// can adjust our bounds and repeat.
|
||||
//
|
||||
@@ -191,10 +191,10 @@ extension MutableCollection {
|
||||
s = s1
|
||||
if s == m { m = m1 }
|
||||
}
|
||||
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
|
||||
/// Rotates the elements of this collection so that the element
|
||||
/// at the specified index becomes the start of the collection.
|
||||
///
|
||||
@@ -287,11 +287,11 @@ extension MutableCollection {
|
||||
@discardableResult
|
||||
public mutating func rotate(
|
||||
subrange: Range<Index>,
|
||||
at newStart: Index) -> Index
|
||||
{
|
||||
at newStart: Index
|
||||
) -> Index {
|
||||
rotate(subrange: subrange, toStartAt: newStart)
|
||||
}
|
||||
|
||||
|
||||
@available(*, deprecated, renamed: "rotate(toStartAt:)")
|
||||
@discardableResult
|
||||
public mutating func rotate(at newStart: Index) -> Index {
|
||||
|
||||
@@ -54,14 +54,14 @@ extension Collection {
|
||||
|
||||
/// A wrapper that strides over a base sequence.
|
||||
public struct StrideSequence<Base: Sequence>: Sequence {
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal let stride: Int
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, stride: Int) {
|
||||
precondition(stride > 0, "striding must be greater than zero")
|
||||
self.base = base
|
||||
@@ -70,24 +70,24 @@ public struct StrideSequence<Base: Sequence>: Sequence {
|
||||
}
|
||||
|
||||
extension StrideSequence {
|
||||
|
||||
|
||||
/// An iterator over a `Stride` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal let stride: Int
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal var striding: Bool = false
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal init(iterator: Base.Iterator, stride: Int) {
|
||||
self.iterator = iterator
|
||||
self.stride = stride
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element? {
|
||||
guard striding else {
|
||||
@@ -100,7 +100,7 @@ extension StrideSequence {
|
||||
return iterator.next()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(iterator: base.makeIterator(), stride: stride)
|
||||
@@ -118,11 +118,11 @@ extension StrideSequence {
|
||||
public struct StrideCollection<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal let stride: Int
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, stride: Int) {
|
||||
precondition(stride > 0, "striding must be greater than zero")
|
||||
self.base = base
|
||||
@@ -138,44 +138,44 @@ extension StrideCollection {
|
||||
}
|
||||
|
||||
extension StrideCollection: Collection {
|
||||
|
||||
|
||||
/// A position in a `Stride` collection.
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let base: Base.Index
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal init(_ base: Base.Index) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.base < rhs.base
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(base.startIndex)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(base.endIndex)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public subscript(i: Index) -> Base.Element {
|
||||
base[i.base]
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i.base < base.endIndex, "Advancing past end index")
|
||||
return index(i, offsetBy: 1)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
@@ -184,13 +184,13 @@ extension StrideCollection: Collection {
|
||||
) -> Index? {
|
||||
guard n != 0 else { return i }
|
||||
guard limit != i else { return nil }
|
||||
|
||||
|
||||
return n > 0
|
||||
? offsetForward(i, offsetBy: n, limitedBy: limit)
|
||||
: offsetBackward(i, offsetBy: -n, limitedBy: limit)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ i: Index,
|
||||
offsetBy n: Int,
|
||||
@@ -219,34 +219,35 @@ extension StrideCollection: Collection {
|
||||
: nil
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ i: Index,
|
||||
offsetBy n: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
let distance = i == endIndex
|
||||
let distance =
|
||||
i == endIndex
|
||||
? -((base.count - 1) % stride + 1) + (n - 1) * -stride
|
||||
: n * -stride
|
||||
return base.index(
|
||||
i.base,
|
||||
offsetBy: distance,
|
||||
limitedBy: limit.base
|
||||
i.base,
|
||||
offsetBy: distance,
|
||||
limitedBy: limit.base
|
||||
).map(Index.init)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
base.isEmpty ? 0 : (base.count - 1) / stride + 1
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
let distance = base.distance(from: start.base, to: end.base)
|
||||
return distance / stride + (distance % stride).signum()
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
precondition(distance <= 0 || i.base < base.endIndex, "Advancing past end index")
|
||||
@@ -259,8 +260,8 @@ extension StrideCollection: Collection {
|
||||
}
|
||||
|
||||
extension StrideCollection: BidirectionalCollection
|
||||
where Base: RandomAccessCollection {
|
||||
|
||||
where Base: RandomAccessCollection {
|
||||
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(i.base > base.startIndex, "Incrementing past start index")
|
||||
@@ -269,22 +270,4 @@ extension StrideCollection: BidirectionalCollection
|
||||
}
|
||||
|
||||
extension StrideCollection: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
|
||||
extension StrideCollection: Equatable where Base.Element: Equatable {
|
||||
@inlinable
|
||||
public static func == (lhs: StrideCollection, rhs: StrideCollection) -> Bool {
|
||||
lhs.elementsEqual(rhs, by: ==)
|
||||
}
|
||||
}
|
||||
|
||||
extension StrideCollection: Hashable where Base.Element: Hashable {
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(stride)
|
||||
for element in self {
|
||||
hasher.combine(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension StrideCollection.Index: Hashable where Base.Index: Hashable {}
|
||||
@@ -45,7 +45,7 @@ extension Collection {
|
||||
/// be called again.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal func endOfPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
@@ -71,7 +71,7 @@ extension BidirectionalCollection {
|
||||
/// be called again.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal func startOfSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
|
||||
@@ -9,25 +9,82 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence wrapper that leaves out duplicate elements of a base sequence.
|
||||
public struct Uniqued<Base: Sequence, Subject: Hashable> {
|
||||
/// The base collection.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
/// The projection function.
|
||||
@usableFromInline
|
||||
internal let projection: (Base.Element) -> Subject
|
||||
|
||||
@usableFromInline
|
||||
internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {
|
||||
self.base = base
|
||||
self.projection = projection
|
||||
}
|
||||
}
|
||||
|
||||
extension Uniqued: Sequence {
|
||||
/// The iterator for a `Uniqued` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var base: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal let projection: (Base.Element) -> Subject
|
||||
|
||||
@usableFromInline
|
||||
internal var seen: Set<Subject> = []
|
||||
|
||||
@usableFromInline
|
||||
internal init(
|
||||
base: Base.Iterator,
|
||||
projection: @escaping (Base.Element) -> Subject
|
||||
) {
|
||||
self.base = base
|
||||
self.projection = projection
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element? {
|
||||
while let element = base.next() {
|
||||
if seen.insert(projection(element)).inserted {
|
||||
return element
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(base: base.makeIterator(), projection: projection)
|
||||
}
|
||||
}
|
||||
|
||||
extension Uniqued: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// uniqued()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence where Element: Hashable {
|
||||
/// Returns an array with only the unique elements of this sequence, in the
|
||||
/// Returns a sequence with only the unique elements of this sequence, in the
|
||||
/// order of the first occurrence of each unique element.
|
||||
///
|
||||
/// let animals = ["dog", "pig", "cat", "ox", "dog", "cat"]
|
||||
/// let uniqued = animals.uniqued()
|
||||
/// print(uniqued)
|
||||
/// print(Array(uniqued))
|
||||
/// // Prints '["dog", "pig", "cat", "ox"]'
|
||||
///
|
||||
/// - Returns: An array with only the unique elements of this sequence.
|
||||
/// - Returns: A sequence with only the unique elements of this sequence.
|
||||
/// .
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
/// - Complexity: O(1).
|
||||
@inlinable
|
||||
public func uniqued() -> [Element] {
|
||||
uniqued(on: { $0 })
|
||||
public func uniqued() -> Uniqued<Self, Element> {
|
||||
Uniqued(base: self, projection: { $0 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +97,7 @@ extension Sequence {
|
||||
/// first characters:
|
||||
///
|
||||
/// let animals = ["dog", "pig", "cat", "ox", "cow", "owl"]
|
||||
/// let uniqued = animals.uniqued(on: {$0.first})
|
||||
/// let uniqued = animals.uniqued(on: { $0.first })
|
||||
/// print(uniqued)
|
||||
/// // Prints '["dog", "pig", "cat", "ox"]'
|
||||
///
|
||||
@@ -67,3 +124,21 @@ extension Sequence {
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// lazy.uniqued()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
/// Returns a lazy sequence with the unique elements of this sequence (as
|
||||
/// determined by the given projection), in the order of the first occurrence
|
||||
/// of each unique element.
|
||||
///
|
||||
/// - Complexity: O(1).
|
||||
@inlinable
|
||||
public func uniqued<Subject: Hashable>(
|
||||
on projection: @escaping (Element) -> Subject
|
||||
) -> Uniqued<Self, Subject> {
|
||||
Uniqued(base: self, projection: projection)
|
||||
}
|
||||
}
|
||||
@@ -47,13 +47,16 @@ extension Collection {
|
||||
/// A collection wrapper that presents a sliding window over the elements of
|
||||
/// a collection.
|
||||
public struct Windows<Base: Collection> {
|
||||
public let base: Base
|
||||
public let size: Int
|
||||
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let size: Int
|
||||
|
||||
@usableFromInline
|
||||
internal var firstUpperBound: Base.Index?
|
||||
|
||||
@usableFromInline
|
||||
@inlinable
|
||||
internal init(base: Base, size: Int) {
|
||||
precondition(size > 0, "Windows size must be greater than zero")
|
||||
self.base = base
|
||||
@@ -68,27 +71,27 @@ extension Windows: Collection {
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal var lowerBound: Base.Index
|
||||
|
||||
|
||||
@usableFromInline
|
||||
internal var upperBound: Base.Index
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal init(lowerBound: Base.Index, upperBound: Base.Index) {
|
||||
self.lowerBound = lowerBound
|
||||
self.upperBound = upperBound
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.lowerBound == rhs.lowerBound
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.lowerBound < rhs.lowerBound
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
if let upperBound = firstUpperBound {
|
||||
@@ -97,12 +100,12 @@ extension Windows: Collection {
|
||||
return endIndex
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(lowerBound: base.endIndex, upperBound: base.endIndex)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public subscript(index: Index) -> Base.SubSequence {
|
||||
precondition(
|
||||
@@ -110,7 +113,7 @@ extension Windows: Collection {
|
||||
"Windows index is out of range")
|
||||
return base[index.lowerBound..<index.upperBound]
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(after index: Index) -> Index {
|
||||
precondition(index < endIndex, "Advancing past end index")
|
||||
@@ -120,16 +123,16 @@ extension Windows: Collection {
|
||||
upperBound: base.index(after: index.upperBound)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
guard distance != 0 else { return i }
|
||||
|
||||
|
||||
return distance > 0
|
||||
? offsetForward(i, by: distance)
|
||||
: offsetBackward(i, by: -distance)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
@@ -138,7 +141,7 @@ extension Windows: Collection {
|
||||
) -> Index? {
|
||||
guard distance != 0 else { return i }
|
||||
guard limit != i else { return nil }
|
||||
|
||||
|
||||
if distance > 0 {
|
||||
return limit > i
|
||||
? offsetForward(i, by: distance, limitedBy: limit)
|
||||
@@ -149,28 +152,28 @@ extension Windows: Collection {
|
||||
: offsetBackward(i, by: -distance)
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit > i)
|
||||
|
||||
|
||||
// `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
|
||||
// bound of the output, in order to avoid advancing past the end of `base`
|
||||
@@ -181,31 +184,31 @@ extension Windows: Collection {
|
||||
// input: [x|x x x x x|x x x x] [x x|x x x x x|x x x]
|
||||
// |> > >|>| or |> > >|
|
||||
// output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`)
|
||||
|
||||
|
||||
if distance >= size {
|
||||
// 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
|
||||
// input.
|
||||
|
||||
|
||||
// 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]
|
||||
|
||||
|
||||
guard limit.lowerBound >= i.upperBound,
|
||||
let lowerBound = base.index(
|
||||
i.upperBound,
|
||||
offsetBy: distance - size,
|
||||
limitedBy: limit.lowerBound),
|
||||
let indexBeforeUpperBound = base.index(
|
||||
lowerBound,
|
||||
offsetBy: size - 1,
|
||||
limitedBy: limit.upperBound)
|
||||
let lowerBound = base.index(
|
||||
i.upperBound,
|
||||
offsetBy: distance - size,
|
||||
limitedBy: limit.lowerBound),
|
||||
let indexBeforeUpperBound = base.index(
|
||||
lowerBound,
|
||||
offsetBy: size - 1,
|
||||
limitedBy: limit.upperBound)
|
||||
else { return nil }
|
||||
|
||||
|
||||
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
|
||||
// `endIndex`.
|
||||
guard indexBeforeUpperBound != base.endIndex else { return endIndex }
|
||||
|
||||
|
||||
return Index(
|
||||
lowerBound: lowerBound,
|
||||
upperBound: base.index(after: indexBeforeUpperBound))
|
||||
@@ -213,35 +216,36 @@ extension Windows: Collection {
|
||||
// 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]
|
||||
|
||||
guard let indexBeforeUpperBound = base.index(
|
||||
i.upperBound,
|
||||
offsetBy: distance - 1,
|
||||
limitedBy: limit.upperBound)
|
||||
|
||||
guard
|
||||
let indexBeforeUpperBound = base.index(
|
||||
i.upperBound,
|
||||
offsetBy: distance - 1,
|
||||
limitedBy: limit.upperBound)
|
||||
else { return nil }
|
||||
|
||||
|
||||
// If `indexBeforeUpperBound` equals the limit, the upper bound itself
|
||||
// exceeds it.
|
||||
guard indexBeforeUpperBound != limit.upperBound || limit == endIndex
|
||||
else { return nil }
|
||||
|
||||
else { return nil }
|
||||
|
||||
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
|
||||
// `endIndex`.
|
||||
guard indexBeforeUpperBound != base.endIndex else { return endIndex }
|
||||
|
||||
|
||||
return Index(
|
||||
lowerBound: base.index(i.lowerBound, offsetBy: distance),
|
||||
upperBound: base.index(after: indexBeforeUpperBound))
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit < i)
|
||||
|
||||
|
||||
if i == endIndex {
|
||||
// Advance `base.endIndex` by `distance - 1`, because the index before
|
||||
// `endIndex` also has `base.endIndex` as its upper bound.
|
||||
@@ -251,13 +255,14 @@ extension Windows: Collection {
|
||||
// input: [x x x x x x x x x x] (`endIndex`)
|
||||
// |< < < < <|< < <|
|
||||
// output: [x x|x x x x x|x x x]
|
||||
|
||||
guard let upperBound = base.index(
|
||||
base.endIndex,
|
||||
offsetBy: -(distance - 1),
|
||||
limitedBy: limit.upperBound)
|
||||
|
||||
guard
|
||||
let upperBound = base.index(
|
||||
base.endIndex,
|
||||
offsetBy: -(distance - 1),
|
||||
limitedBy: limit.upperBound)
|
||||
else { return nil }
|
||||
|
||||
|
||||
return Index(
|
||||
lowerBound: base.index(upperBound, offsetBy: -size),
|
||||
upperBound: upperBound)
|
||||
@@ -269,14 +274,14 @@ extension Windows: Collection {
|
||||
// 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]
|
||||
|
||||
|
||||
guard limit.upperBound <= i.lowerBound,
|
||||
let upperBound = base.index(
|
||||
i.lowerBound,
|
||||
offsetBy: -(distance - size),
|
||||
limitedBy: limit.upperBound)
|
||||
let upperBound = base.index(
|
||||
i.lowerBound,
|
||||
offsetBy: -(distance - size),
|
||||
limitedBy: limit.upperBound)
|
||||
else { return nil }
|
||||
|
||||
|
||||
return Index(
|
||||
lowerBound: base.index(upperBound, offsetBy: -size),
|
||||
upperBound: upperBound)
|
||||
@@ -284,19 +289,20 @@ extension Windows: Collection {
|
||||
// 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]
|
||||
|
||||
guard let lowerBound = base.index(
|
||||
i.lowerBound,
|
||||
offsetBy: -distance,
|
||||
limitedBy: limit.lowerBound)
|
||||
|
||||
guard
|
||||
let lowerBound = base.index(
|
||||
i.lowerBound,
|
||||
offsetBy: -distance,
|
||||
limitedBy: limit.lowerBound)
|
||||
else { return nil }
|
||||
|
||||
|
||||
return Index(
|
||||
lowerBound: lowerBound,
|
||||
upperBound: base.index(i.lowerBound, offsetBy: -distance))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
guard start <= end else { return -distance(from: end, to: start) }
|
||||
@@ -314,13 +320,13 @@ extension Windows: Collection {
|
||||
// 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]
|
||||
|
||||
|
||||
return size + base[start.upperBound..<end.lowerBound].count
|
||||
} else {
|
||||
// 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]
|
||||
|
||||
|
||||
return base[start.lowerBound..<end.lowerBound].count
|
||||
}
|
||||
}
|
||||
@@ -347,6 +353,4 @@ extension Windows: BidirectionalCollection where Base: BidirectionalCollection {
|
||||
extension Windows: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension Windows: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
||||
extension Windows: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
extension Windows: Equatable where Base: Equatable {}
|
||||
extension Windows: Hashable where Base: Hashable, Base.Index: Hashable {}
|
||||
extension Windows.Index: Hashable where Base.Index: Hashable {}
|
||||
@@ -1,140 +0,0 @@
|
||||
import Darwin
|
||||
import Algorithms
|
||||
|
||||
struct Benchmark {
|
||||
var name: String
|
||||
var `default`: Int
|
||||
var body: (Int) -> Int
|
||||
}
|
||||
|
||||
let benchmarks = [
|
||||
Benchmark(name: "chain", default: 100) { count in
|
||||
let x = String(repeating: "_", count: 10_000)
|
||||
.chained(with: String(repeating: "-", count: 10_000))
|
||||
.chained(with: "0")
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let i = x.firstIndex(of: "0")!
|
||||
let d = x.distance(from: x.startIndex, to: i)
|
||||
v &+= d
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "chunked", default: 1000) { count in
|
||||
let x = (1...1000).shuffled()
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let y = x.chunked(by: <=)
|
||||
v &+= y.count
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "lazy chunked", default: 1000) { count in
|
||||
let x = (1...1000).shuffled()
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let y = x.lazy.chunked(by: <=)
|
||||
v &+= y.count
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "combinations", default: 100) { count in
|
||||
let x = 1...30
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let y = x.combinations(ofCount: 4)
|
||||
let combo = y.first(where: { combo in combo.allSatisfy { $0.isMultiple(of: 2) }})!
|
||||
v &+= combo.reduce(0, +)
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "stable partition", default: 100) { count in
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
var x = Array(1...10000)
|
||||
let i = x.stablePartition(by: { $0.isMultiple(of: 3) })
|
||||
v &+= i
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "permutations", default: 10) { count in
|
||||
let x = 1...20
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let y = x.permutations(ofCount: 4)
|
||||
let perm = y.first(where: { perm in perm.allSatisfy { $0.isMultiple(of: 2) }})!
|
||||
v &+= perm.reduce(0, +)
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "product", default: 1000) { count in
|
||||
let x = product(1...100, "abcdefghijklmnopqrstuvwxyz")
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let i = x.firstIndex(where: { $0 == 77 && $1 == "m" })!
|
||||
let d = x.distance(from: x.startIndex, to: i)
|
||||
v &+= d
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "sample", default: 1000) { count in
|
||||
let x = 1...10000
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let r = x.randomSample(count: 20)
|
||||
v &+= r.reduce(0, +)
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "stable sample", default: 1000) { count in
|
||||
let x = 1...10000
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let r = x.randomStableSample(count: 20)
|
||||
v &+= r.reduce(0, +)
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "uniqued", default: 1000) { count in
|
||||
let x = repeatElement(1...1000, count: 1000)
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let r = x.uniqued()
|
||||
v &+= r.count
|
||||
}
|
||||
return v
|
||||
},
|
||||
]
|
||||
|
||||
func printChoices() -> Never {
|
||||
print(benchmarks.enumerated().map { "\($0): \($1.name)" }.joined(separator: "\n"))
|
||||
exit(0)
|
||||
}
|
||||
|
||||
if CommandLine.arguments.count <= 1 {
|
||||
printChoices()
|
||||
} else {
|
||||
guard let choice = Int(CommandLine.arguments[1]), benchmarks.indices.contains(choice) else {
|
||||
print("Invalid choice:")
|
||||
printChoices()
|
||||
}
|
||||
|
||||
let bench = benchmarks[choice]
|
||||
let count: Int
|
||||
if CommandLine.arguments.count > 2, let c = Int(CommandLine.arguments[2]) {
|
||||
count = c
|
||||
} else {
|
||||
count = bench.default
|
||||
}
|
||||
|
||||
print(bench.body(count))
|
||||
}
|
||||
@@ -11,9 +11,9 @@
|
||||
|
||||
#error("""
|
||||
|
||||
-----------------------------------------------------
|
||||
-----------------------------------------------------
|
||||
|
||||
Please test with `swift test --enable-test-discovery`
|
||||
Please test with `swift test --enable-test-discovery`
|
||||
|
||||
-----------------------------------------------------
|
||||
""")
|
||||
-----------------------------------------------------
|
||||
""")
|
||||
@@ -10,6 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
|
||||
@testable import Algorithms
|
||||
|
||||
final class ChainTests: XCTestCase {
|
||||
@@ -17,24 +18,24 @@ final class ChainTests: XCTestCase {
|
||||
let run = chain((1...).prefix(10), 20...)
|
||||
XCTAssertEqualSequences(run.prefix(20), Array(1...10) + (20..<30))
|
||||
}
|
||||
|
||||
|
||||
func testChainForwardCollection() {
|
||||
let s1 = Set(0...10)
|
||||
let s2 = Set(20...30)
|
||||
let c = chain(s1, s2)
|
||||
XCTAssertEqualSequences(c, Array(s1) + Array(s2))
|
||||
}
|
||||
|
||||
|
||||
func testChainBidirectionalCollection() {
|
||||
let s1 = "ABCDEFGHIJ"
|
||||
let s2 = "klmnopqrstuv"
|
||||
let c = chain(s1, s2)
|
||||
|
||||
|
||||
XCTAssertEqualSequences(c, "ABCDEFGHIJklmnopqrstuv")
|
||||
XCTAssertEqualSequences(c.reversed(), "ABCDEFGHIJklmnopqrstuv".reversed())
|
||||
XCTAssertEqualSequences(chain(s1.reversed(), s2), "JIHGFEDCBAklmnopqrstuv")
|
||||
}
|
||||
|
||||
|
||||
func testChainIndexTraversals() {
|
||||
validateIndexTraversals(
|
||||
chain("abcd", "XYZ"),
|
||||
@@ -47,21 +48,21 @@ final class ChainTests: XCTestCase {
|
||||
+ [.init(second: chain.base2.endIndex)]
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
func testChainIndexOffsetAcrossBoundary() {
|
||||
let c = chain("abc", "XYZ")
|
||||
|
||||
|
||||
do {
|
||||
let i = c.index(c.startIndex, offsetBy: 3, limitedBy: c.startIndex)
|
||||
XCTAssertNil(i)
|
||||
}
|
||||
|
||||
|
||||
do {
|
||||
let i = c.index(c.startIndex, offsetBy: 4)
|
||||
let j = c.index(i, offsetBy: -2)
|
||||
XCTAssertEqual(c[j], "c")
|
||||
}
|
||||
|
||||
|
||||
do {
|
||||
let i = c.index(c.startIndex, offsetBy: 3)
|
||||
let j = c.index(i, offsetBy: -1, limitedBy: i)
|
||||
|
||||
@@ -9,23 +9,22 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class ChunkedTests: XCTestCase {
|
||||
let fruits = [
|
||||
"Apple", "Apricot", "Avocado", "Banana",
|
||||
"Bilberry", "Blackberry", "Blackcurrant", "Blueberry",
|
||||
"Currant", "Cherry", "Cherimoya", "Clementine",
|
||||
"Date", "Damson", "Dragonfruit", "Durian",
|
||||
"Eggplant", "Elderberry", "Feijoa",
|
||||
"Grape", "Grapefruit", "Guava",
|
||||
"Apple", "Apricot", "Avocado", "Banana",
|
||||
"Bilberry", "Blackberry", "Blackcurrant", "Blueberry",
|
||||
"Currant", "Cherry", "Cherimoya", "Clementine",
|
||||
"Date", "Damson", "Dragonfruit", "Durian",
|
||||
"Eggplant", "Elderberry", "Feijoa",
|
||||
"Grape", "Grapefruit", "Guava",
|
||||
]
|
||||
|
||||
func validateFruitChunks<C: BidirectionalCollection>(_ fruitChunks: C)
|
||||
where C.Element == ArraySlice<String>
|
||||
{
|
||||
let expectedChunks: Array<ArraySlice<String>> = [
|
||||
where C.Element == ArraySlice<String> {
|
||||
let expectedChunks: [ArraySlice<String>] = [
|
||||
fruits[0..<3],
|
||||
fruits[3..<8],
|
||||
fruits[8..<12],
|
||||
@@ -35,21 +34,21 @@ final class ChunkedTests: XCTestCase {
|
||||
fruits[19..<22],
|
||||
]
|
||||
XCTAssertEqualSequences(expectedChunks, fruitChunks, by: ==)
|
||||
|
||||
|
||||
XCTAssertEqual(fruits[19..<22], fruitChunks.last)
|
||||
|
||||
|
||||
XCTAssertEqual("Currant", fruitChunks.first(where: { $0.count == 4 })?.first)
|
||||
XCTAssertEqual("Date", fruitChunks.last(where: { $0.count == 4 })?.first)
|
||||
XCTAssertNil(fruitChunks.first(where: { $0.count == 0 }))
|
||||
XCTAssertNil(fruitChunks.last(where: { $0.count == 0 }))
|
||||
}
|
||||
|
||||
|
||||
func testSimple() {
|
||||
// Example
|
||||
let names = ["David", "Kyle", "Karoy", "Nate"]
|
||||
let chunks = names.chunked(on: { $0.first })
|
||||
XCTAssertEqualSequences([["David"], ["Kyle", "Karoy"], ["Nate"]], chunks)
|
||||
|
||||
|
||||
// Empty sequence
|
||||
XCTAssertEqual(0, names.prefix(0).chunked(on: { $0.first }).count)
|
||||
|
||||
@@ -57,27 +56,26 @@ final class ChunkedTests: XCTestCase {
|
||||
let namesStartingWithD = ["David", "Don", "Darren"]
|
||||
XCTAssertEqual(1, namesStartingWithD.chunked(on: { $0.first }).count)
|
||||
}
|
||||
|
||||
|
||||
func testChunkedOn() {
|
||||
validateFruitChunks(fruits.chunked(on: { $0.first }))
|
||||
|
||||
|
||||
let lazyChunks = fruits.lazy.chunked(on: { $0.first })
|
||||
validateFruitChunks(lazyChunks)
|
||||
}
|
||||
|
||||
func testChunkedBy() {
|
||||
validateFruitChunks(fruits.chunked(by: { $0.first == $1.first }))
|
||||
|
||||
|
||||
let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first })
|
||||
validateFruitChunks(lazyChunks)
|
||||
}
|
||||
|
||||
|
||||
func testChunkedLazy() {
|
||||
XCTAssertLazySequence(fruits.lazy.chunked(by: { $0.first == $1.first }))
|
||||
XCTAssertLazySequence(fruits.lazy.chunked(on: { $0.first }))
|
||||
}
|
||||
|
||||
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Tests for `chunks(ofCount:)`
|
||||
//===----------------------------------------------------------------------===//
|
||||
@@ -86,37 +84,47 @@ final class ChunkedTests: XCTestCase {
|
||||
XCTAssertEqualSequences([Int]().chunks(ofCount: 5), [])
|
||||
|
||||
let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
XCTAssertEqualSequences(collection1.chunks(ofCount: 1),
|
||||
[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
|
||||
XCTAssertEqualSequences(collection1.chunks(ofCount: 3),
|
||||
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]])
|
||||
XCTAssertEqualSequences(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]])
|
||||
|
||||
XCTAssertEqualSequences(
|
||||
collection1.chunks(ofCount: 1),
|
||||
[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
|
||||
XCTAssertEqualSequences(
|
||||
collection1.chunks(ofCount: 3),
|
||||
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]])
|
||||
XCTAssertEqualSequences(
|
||||
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]
|
||||
XCTAssertEqualSequences(collection2.chunks(ofCount: 3),
|
||||
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]])
|
||||
XCTAssertEqualSequences(
|
||||
collection2.chunks(ofCount: 3),
|
||||
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]])
|
||||
}
|
||||
|
||||
|
||||
func testChunksOfCountBidirectional() {
|
||||
let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
|
||||
XCTAssertEqualSequences(collection1.chunks(ofCount: 1).reversed(),
|
||||
[[10], [9], [8], [7], [6], [5], [4], [3], [2], [1]])
|
||||
XCTAssertEqualSequences(collection1.chunks(ofCount: 3).reversed(),
|
||||
[[10], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
|
||||
XCTAssertEqualSequences(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]])
|
||||
|
||||
XCTAssertEqualSequences(
|
||||
collection1.chunks(ofCount: 1).reversed(),
|
||||
[[10], [9], [8], [7], [6], [5], [4], [3], [2], [1]])
|
||||
XCTAssertEqualSequences(
|
||||
collection1.chunks(ofCount: 3).reversed(),
|
||||
[[10], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
|
||||
XCTAssertEqualSequences(
|
||||
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]
|
||||
XCTAssertEqualSequences(collection2.chunks(ofCount: 3).reversed(),
|
||||
[[10, 11], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
|
||||
XCTAssertEqualSequences(
|
||||
collection2.chunks(ofCount: 3).reversed(),
|
||||
[[10, 11], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
|
||||
}
|
||||
|
||||
|
||||
func testChunksOfCountCount() {
|
||||
XCTAssertEqual([Int]().chunks(ofCount: 1).count, 0)
|
||||
XCTAssertEqual([Int]().chunks(ofCount: 5).count, 0)
|
||||
@@ -126,22 +134,22 @@ final class ChunkedTests: XCTestCase {
|
||||
XCTAssertEqual(collection1.chunks(ofCount: 3).count, 4)
|
||||
XCTAssertEqual(collection1.chunks(ofCount: 5).count, 2)
|
||||
XCTAssertEqual(collection1.chunks(ofCount: 11).count, 1)
|
||||
|
||||
|
||||
let collection2 = (1...50).map { $0 }
|
||||
XCTAssertEqual(collection2.chunks(ofCount: 9).count, 6)
|
||||
}
|
||||
|
||||
func testEmptyChunksOfCountTraversal() {
|
||||
let emptyChunks = [Int]().chunks(ofCount: 1)
|
||||
|
||||
|
||||
validateIndexTraversals(emptyChunks)
|
||||
}
|
||||
|
||||
|
||||
func testChunksOfCountTraversal() {
|
||||
for i in 1..<10 {
|
||||
let collection = (1...50).map { $0 }
|
||||
let chunks = collection.chunks(ofCount: i)
|
||||
|
||||
|
||||
validateIndexTraversals(chunks)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,113 +9,131 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class CombinationsTests: XCTestCase {
|
||||
func testCount() {
|
||||
let c = "ABCD"
|
||||
|
||||
|
||||
let c0 = c.combinations(ofCount: 0).count
|
||||
XCTAssertEqual(c0, 1)
|
||||
|
||||
|
||||
let c1 = c.combinations(ofCount: 1).count
|
||||
XCTAssertEqual(c1, 4)
|
||||
|
||||
|
||||
let c2 = c.combinations(ofCount: 2).count
|
||||
XCTAssertEqual(c2, 6)
|
||||
|
||||
|
||||
let c3 = c.combinations(ofCount: 3).count
|
||||
XCTAssertEqual(c3, 4)
|
||||
|
||||
|
||||
let c4 = c.combinations(ofCount: 4).count
|
||||
XCTAssertEqual(c4, 1)
|
||||
|
||||
|
||||
let c5 = c.combinations(ofCount: 0...0).count
|
||||
XCTAssertEqual(c5, 1)
|
||||
|
||||
|
||||
let c6 = c.combinations(ofCount: 1...1).count
|
||||
XCTAssertEqual(c6, 4)
|
||||
|
||||
|
||||
let c7 = c.combinations(ofCount: 1...2).count
|
||||
XCTAssertEqual(c7, 10)
|
||||
|
||||
|
||||
let c8 = c.combinations(ofCount: 1...3).count
|
||||
XCTAssertEqual(c8, 14)
|
||||
|
||||
|
||||
let c9 = c.combinations(ofCount: 2...4).count
|
||||
XCTAssertEqual(c9, 11)
|
||||
|
||||
|
||||
// `k` greater than element count results in same number of combinations
|
||||
let c10 = c.combinations(ofCount: 3...10).count
|
||||
XCTAssertEqual(c10, 5)
|
||||
|
||||
|
||||
// `k` greater than element count results in same number of combinations
|
||||
let c11 = c.combinations(ofCount: 4...10).count
|
||||
XCTAssertEqual(c11, 1)
|
||||
|
||||
|
||||
// `k` entirely greater than element count results in no combinations
|
||||
let c12 = c.combinations(ofCount: 5...10).count
|
||||
XCTAssertEqual(c12, 0)
|
||||
|
||||
|
||||
let c13 = c.combinations(ofCount: 0...).count
|
||||
XCTAssertEqual(c13, 16)
|
||||
|
||||
|
||||
let c14 = c.combinations(ofCount: ...3).count
|
||||
XCTAssertEqual(c14, 15)
|
||||
|
||||
|
||||
let c15 = c.combinations(ofCount: 0...).count
|
||||
XCTAssertEqual(c15, 16)
|
||||
}
|
||||
|
||||
|
||||
func testCombinations() {
|
||||
let c = "ABCD"
|
||||
|
||||
|
||||
let c1 = c.combinations(ofCount: 1)
|
||||
XCTAssertEqual(["A", "B", "C", "D"], c1.map { String($0) })
|
||||
|
||||
|
||||
let c2 = c.combinations(ofCount: 2)
|
||||
XCTAssertEqual(["AB", "AC", "AD", "BC", "BD", "CD"], c2.map { String($0) })
|
||||
|
||||
|
||||
let c3 = c.combinations(ofCount: 3)
|
||||
XCTAssertEqual(["ABC", "ABD", "ACD", "BCD"], c3.map { String($0) })
|
||||
|
||||
|
||||
let c4 = c.combinations(ofCount: 4)
|
||||
XCTAssertEqual(["ABCD"], c4.map { String($0) })
|
||||
|
||||
|
||||
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)
|
||||
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...)
|
||||
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)
|
||||
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)
|
||||
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...)
|
||||
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() {
|
||||
// `k == 0` results in one zero-length combination
|
||||
XCTAssertEqualSequences([[]], "".combinations(ofCount: 0))
|
||||
XCTAssertEqualSequences([[]], "".combinations(ofCount: 0...0))
|
||||
XCTAssertEqualSequences([[]], "ABCD".combinations(ofCount: 0))
|
||||
XCTAssertEqualSequences([[]], "ABCD".combinations(ofCount: 0...0))
|
||||
|
||||
|
||||
// `k` greater than element count results in zero combinations
|
||||
XCTAssertEqualSequences([], "".combinations(ofCount: 5))
|
||||
XCTAssertEqualSequences([], "".combinations(ofCount: 5...10))
|
||||
XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5))
|
||||
XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5...10))
|
||||
}
|
||||
|
||||
|
||||
func testCombinationsLazy() {
|
||||
XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1))
|
||||
XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1...3))
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class CompactedTests: XCTestCase {
|
||||
|
||||
let tests: [[Int?]] =
|
||||
[nil, nil, nil, 0, 1, 2]
|
||||
.uniquePermutations(ofCount: 0...)
|
||||
.map(Array.init)
|
||||
|
||||
func testCompactedCompacted() {
|
||||
for collection in self.tests {
|
||||
let seq = AnySequence(collection)
|
||||
XCTAssertEqualSequences(
|
||||
seq.compactMap({ $0 }), seq.compacted())
|
||||
XCTAssertEqualSequences(
|
||||
collection.compactMap({ $0 }), collection.compacted())
|
||||
}
|
||||
}
|
||||
|
||||
func testCompactedBidirectionalCollection() {
|
||||
for array in self.tests {
|
||||
XCTAssertEqualSequences(
|
||||
array.compactMap({ $0 }).reversed(),
|
||||
array.compacted().reversed())
|
||||
}
|
||||
}
|
||||
|
||||
func testCollectionTraversals() {
|
||||
for array in self.tests {
|
||||
validateIndexTraversals(array.compacted())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,8 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class CycleTests: XCTestCase {
|
||||
func testCycle() {
|
||||
@@ -19,28 +19,71 @@ final class CycleTests: XCTestCase {
|
||||
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
|
||||
cycle.prefix(20)
|
||||
)
|
||||
}
|
||||
|
||||
func testCycleClosedRangePrefix() {
|
||||
let a = Array((0..<17).cycled().prefix(10_000))
|
||||
XCTAssertEqual(10_000, a.count)
|
||||
|
||||
}
|
||||
|
||||
func testEmptyCycle() {
|
||||
let empty = Array("".cycled())
|
||||
XCTAssert(empty.isEmpty)
|
||||
}
|
||||
|
||||
|
||||
func testCycleLazy() {
|
||||
XCTAssertLazySequence((1...4).lazy.cycled())
|
||||
}
|
||||
|
||||
func testRepeated() {
|
||||
let repeats = (1...4).cycled(times: 3)
|
||||
XCTAssertEqualSequences(
|
||||
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
|
||||
repeats)
|
||||
|
||||
}
|
||||
|
||||
func testRepeatedClosedRange() {
|
||||
let repeats = Array((1..<5).cycled(times: 2500))
|
||||
XCTAssertEqual(10_000, repeats.count)
|
||||
}
|
||||
|
||||
func testRepeatedEmptyCollection() {
|
||||
let empty1 = Array("".cycled(times: 100))
|
||||
XCTAssert(empty1.isEmpty)
|
||||
|
||||
}
|
||||
|
||||
func testRepeatedZeroTimesCycle() {
|
||||
let empty2 = Array("Hello".cycled(times: 0))
|
||||
XCTAssert(empty2.isEmpty)
|
||||
}
|
||||
|
||||
func testCycleLazy() {
|
||||
XCTAssertLazySequence((1...4).lazy.cycled())
|
||||
|
||||
func testRepeatedLazy() {
|
||||
XCTAssertLazySequence((1...4).lazy.cycled(times: 3))
|
||||
}
|
||||
|
||||
func testRepeatedIndexMethods() {
|
||||
let cycle = (1..<5).cycled(times: 2)
|
||||
let startIndex = cycle.startIndex
|
||||
var nextIndex = cycle.index(after: startIndex)
|
||||
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 1)
|
||||
|
||||
nextIndex = cycle.index(nextIndex, offsetBy: 5)
|
||||
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 6)
|
||||
|
||||
nextIndex = cycle.index(nextIndex, offsetBy: 2, limitedBy: cycle.endIndex)!
|
||||
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 8)
|
||||
|
||||
let outOfBounds = cycle.index(
|
||||
nextIndex, offsetBy: 1,
|
||||
limitedBy: cycle.endIndex)
|
||||
XCTAssertNil(outOfBounds)
|
||||
|
||||
let previousIndex = cycle.index(before: nextIndex)
|
||||
XCTAssertEqual(cycle.distance(from: startIndex, to: previousIndex), 7)
|
||||
}
|
||||
|
||||
func testRepeatedCount() {
|
||||
let cycle = (1..<5).cycled(times: 2)
|
||||
XCTAssertEqual(cycle.count, 8)
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,8 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class FirstNonNilTests: XCTestCase {
|
||||
func testFirstNonNil() {
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class IndexedTests: XCTestCase {
|
||||
func testIndexed() {
|
||||
@@ -27,7 +27,7 @@ final class IndexedTests: XCTestCase {
|
||||
let indexOfI = si.last(where: { $0.element == "I" })!.index
|
||||
XCTAssertEqual("I", s[indexOfI])
|
||||
}
|
||||
|
||||
|
||||
func testIndexedLazy() {
|
||||
XCTAssertLazyCollection("ABCD".lazy.indexed())
|
||||
}
|
||||
|
||||
@@ -9,13 +9,13 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class IntersperseTests: XCTestCase {
|
||||
func testSequence() {
|
||||
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() {
|
||||
@@ -36,8 +36,8 @@ final class IntersperseTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testArray() {
|
||||
let interspersed = [1,2,3,4].interspersed(with: 0)
|
||||
XCTAssertEqualSequences(interspersed, [1,0,2,0,3,0,4])
|
||||
let interspersed = [1, 2, 3, 4].interspersed(with: 0)
|
||||
XCTAssertEqualSequences(interspersed, [1, 0, 2, 0, 3, 0, 4])
|
||||
validateIndexTraversals(interspersed)
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ final class IntersperseTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testCollection() {
|
||||
let interspersed = ["A","B","C","D"].interspersed(with: "-")
|
||||
let interspersed = ["A", "B", "C", "D"].interspersed(with: "-")
|
||||
XCTAssertEqual(interspersed.count, 7)
|
||||
}
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ final class LazySplitTests: XCTestCase {
|
||||
|
||||
func testAllEEES() {
|
||||
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 {
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class SortedPrefixTests: XCTestCase {
|
||||
func testMinCount() {
|
||||
@@ -25,7 +25,7 @@ final class SortedPrefixTests: XCTestCase {
|
||||
.max(count: 5, sortedBy: { $0.element < $1.element })
|
||||
XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
|
||||
}
|
||||
|
||||
|
||||
func testMaxCount() {
|
||||
// Replacement at start and end
|
||||
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 })
|
||||
XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
|
||||
}
|
||||
|
||||
|
||||
func testEmpty() {
|
||||
let array = [Int]()
|
||||
XCTAssertEqual(array.min(count: 0), [])
|
||||
XCTAssertEqual(array.min(count: 100), [])
|
||||
|
||||
|
||||
XCTAssertEqual(array.max(count: 0), [])
|
||||
XCTAssertEqual(array.max(count: 100), [])
|
||||
}
|
||||
@@ -51,14 +51,14 @@ final class SortedPrefixTests: XCTestCase {
|
||||
func testMinMaxSequences() {
|
||||
let input = (1...100).shuffled().interspersed(with: 50)
|
||||
let seq = AnySequence(input)
|
||||
|
||||
|
||||
XCTAssertEqualSequences(seq.min(count: 0), [])
|
||||
XCTAssertEqualSequences(seq.min(count: 5), 1...5)
|
||||
|
||||
|
||||
XCTAssertEqualSequences(seq.max(count: 0), [])
|
||||
XCTAssertEqualSequences(seq.max(count: 5), 96...100)
|
||||
}
|
||||
|
||||
|
||||
func testSortedPrefixComparable() {
|
||||
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))
|
||||
XCTAssertEqual(array.min(count: 10), array.sorted())
|
||||
}
|
||||
|
||||
|
||||
func testMinMaxWithHugeCount() {
|
||||
XCTAssertEqual([4, 2, 1, 3].min(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() {
|
||||
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: 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: 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: 20)
|
||||
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: 1)
|
||||
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: 20)
|
||||
assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 50)
|
||||
assertStability([0,0], withCount: 1)
|
||||
assertStability([0,0], withCount: 2)
|
||||
assertStability([0,1,0,1,0,1], withCount: 2)
|
||||
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: 3)
|
||||
assertStability([0,0,0,1,1,1], withCount: 4)
|
||||
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: 3)
|
||||
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: 5)
|
||||
assertStability([0, 0], withCount: 1)
|
||||
assertStability([0, 0], withCount: 2)
|
||||
assertStability([0, 1, 0, 1, 0, 1], withCount: 2)
|
||||
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: 3)
|
||||
assertStability([0, 0, 0, 1, 1, 1], withCount: 4)
|
||||
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: 3)
|
||||
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: 5)
|
||||
}
|
||||
|
||||
func assertStability(
|
||||
@@ -165,19 +165,19 @@ final class SortedPrefixTests: XCTestCase {
|
||||
) {
|
||||
func stableOrder(
|
||||
a: (offset: Int, element: Int),
|
||||
b: (offset: Int, element: Int)) -> Bool
|
||||
{
|
||||
b: (offset: Int, element: Int)
|
||||
) -> Bool {
|
||||
a.element == b.element
|
||||
? a.offset < b.offset
|
||||
: a.element < b.element
|
||||
}
|
||||
|
||||
|
||||
do {
|
||||
let sorted = actual.enumerated()
|
||||
.min(count: count) { $0.element < $1.element }
|
||||
XCTAssert(sorted.isSorted(by: stableOrder))
|
||||
}
|
||||
|
||||
|
||||
do {
|
||||
let sorted = actual.enumerated()
|
||||
.max(count: count) { $0.element < $1.element }
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class PartitionTests: XCTestCase {
|
||||
func testStablePartition() {
|
||||
@@ -60,7 +60,7 @@ final class PartitionTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testStablePartitionWithSubrange() {
|
||||
for length in 10...20 {
|
||||
let a = Array(0..<length)
|
||||
@@ -72,13 +72,15 @@ final class PartitionTests: XCTestCase {
|
||||
let p = b.stablePartition(subrange: partitionRange, by: condition)
|
||||
|
||||
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
||||
XCTAssertEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
||||
XCTAssertEqualSequences(
|
||||
b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
||||
XCTAssertEqualSequences(
|
||||
b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testPartitioningIndex() {
|
||||
for i in 0..<7 {
|
||||
for j in i..<11 {
|
||||
@@ -91,7 +93,7 @@ final class PartitionTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testPartitionWithSubrangeBidirectionalCollection() {
|
||||
for length in 10...20 {
|
||||
let a = Array(0..<length)
|
||||
@@ -101,10 +103,12 @@ final class PartitionTests: XCTestCase {
|
||||
let partitionRange = j..<i
|
||||
let condition = { $0 < i - 1 }
|
||||
let p = b.partition(subrange: partitionRange, by: condition)
|
||||
|
||||
|
||||
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
||||
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
||||
XCTAssertEqualSequences(
|
||||
b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
||||
XCTAssertUnorderedEqualSequences(
|
||||
b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -121,14 +125,18 @@ final class PartitionTests: XCTestCase {
|
||||
let condition = { $0 < i - 1 }
|
||||
let p = b.partition(subrange: partitionRange, by: condition)
|
||||
let bdcp = bdc.partition(subrange: partitionRange, by: condition)
|
||||
|
||||
|
||||
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
||||
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
||||
|
||||
XCTAssertEqualSequences(
|
||||
b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
||||
XCTAssertUnorderedEqualSequences(
|
||||
b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
||||
|
||||
// Must produce the same result as the `BidirectionalCollection` specialized overload.
|
||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], bdc[partitionRange.lowerBound..<bdcp])
|
||||
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], bdc[bdcp..<partitionRange.upperBound])
|
||||
XCTAssertEqualSequences(
|
||||
b[partitionRange.lowerBound..<p], bdc[partitionRange.lowerBound..<bdcp])
|
||||
XCTAssertUnorderedEqualSequences(
|
||||
b[p..<partitionRange.upperBound], bdc[bdcp..<partitionRange.upperBound])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,15 +10,16 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
|
||||
@testable import Algorithms
|
||||
|
||||
final class PermutationsTests: XCTestCase {
|
||||
func testPermutations() {
|
||||
let c = "ABCDE"
|
||||
|
||||
|
||||
func t(count: Int?) {
|
||||
let p = c.permutations(ofCount: count)
|
||||
|
||||
|
||||
let count = count ?? c.count
|
||||
let permCount = c.count.factorial() / (c.count - count).factorial()
|
||||
XCTAssertEqual(permCount, p.count)
|
||||
@@ -26,20 +27,20 @@ final class PermutationsTests: XCTestCase {
|
||||
XCTAssertTrue(p.allSatisfy { $0.count == count })
|
||||
XCTAssertTrue(p.isSorted(by: { $0.lexicographicallyPrecedes($1) }))
|
||||
}
|
||||
|
||||
|
||||
func ts<R: RangeExpression>(count: R) where R.Bound == Int {
|
||||
let p = count.relative(to: 0 ..< .max)
|
||||
.clamped(to: 0 ..< c.count + 1)
|
||||
.clamped(to: 0..<c.count + 1)
|
||||
.flatMap {
|
||||
c.permutations(ofCount: $0)
|
||||
}
|
||||
|
||||
|
||||
let p2 = c.permutations(ofCount: count)
|
||||
|
||||
|
||||
XCTAssertEqual(p.count, p2.count)
|
||||
XCTAssertEqualSequences(p, Array(p2))
|
||||
}
|
||||
|
||||
|
||||
t(count: 0)
|
||||
t(count: 1)
|
||||
t(count: 2)
|
||||
@@ -47,7 +48,7 @@ final class PermutationsTests: XCTestCase {
|
||||
t(count: 4)
|
||||
t(count: 5)
|
||||
t(count: nil)
|
||||
|
||||
|
||||
ts(count: 0...0)
|
||||
ts(count: 1...1)
|
||||
ts(count: 0...1)
|
||||
@@ -60,7 +61,7 @@ final class PermutationsTests: XCTestCase {
|
||||
ts(count: ...4)
|
||||
ts(count: ...6)
|
||||
}
|
||||
|
||||
|
||||
func testEmpty() {
|
||||
// `k == 0` results in one zero-length permutation
|
||||
XCTAssertEqual(1, "".permutations().count)
|
||||
@@ -70,7 +71,7 @@ final class PermutationsTests: XCTestCase {
|
||||
XCTAssertEqual(Array("".permutations(ofCount: 0)), [[]])
|
||||
XCTAssertEqual(Array("ABCD".permutations(ofCount: 0)), [[]])
|
||||
XCTAssertEqual(Array("ABCD".permutations(ofCount: 0...0)), [[]])
|
||||
|
||||
|
||||
// `k` greater than element count results in zero permutations
|
||||
XCTAssertEqual(0, "".permutations(ofCount: 5).count)
|
||||
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...)), [])
|
||||
}
|
||||
|
||||
|
||||
func testNextPermutation() {
|
||||
var numbers = Array(1...7)
|
||||
|
||||
|
||||
_ = numbers.nextPermutation()
|
||||
XCTAssertEqual([1, 2, 3, 4, 5, 7, 6], numbers)
|
||||
_ = numbers.nextPermutation()
|
||||
@@ -95,110 +96,122 @@ final class PermutationsTests: XCTestCase {
|
||||
XCTAssertEqual([1, 2, 3, 4, 7, 6, 5], numbers)
|
||||
_ = numbers.nextPermutation()
|
||||
XCTAssertEqual([1, 2, 3, 5, 4, 6, 7], numbers)
|
||||
|
||||
|
||||
// Fast-forward to end of permutations.
|
||||
while numbers.nextPermutation() {}
|
||||
XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], numbers)
|
||||
}
|
||||
|
||||
|
||||
func testPermutationsLazy() {
|
||||
XCTAssertLazySequence("ABCD".lazy.permutations(ofCount: 2))
|
||||
}
|
||||
|
||||
|
||||
func testDocumentationExample1() {
|
||||
// From Guides/Permutations.md
|
||||
let numbers = [10, 20, 30]
|
||||
let permutations = numbers.permutations()
|
||||
XCTAssertEqualSequences(permutations, [
|
||||
[10, 20, 30],
|
||||
[10, 30, 20],
|
||||
[20, 10, 30],
|
||||
[20, 30, 10],
|
||||
[30, 10, 20],
|
||||
[30, 20, 10],
|
||||
])
|
||||
XCTAssertEqualSequences(
|
||||
permutations,
|
||||
[
|
||||
[10, 20, 30],
|
||||
[10, 30, 20],
|
||||
[20, 10, 30],
|
||||
[20, 30, 10],
|
||||
[30, 10, 20],
|
||||
[30, 20, 10],
|
||||
])
|
||||
}
|
||||
|
||||
|
||||
func testDocumentationExample2() {
|
||||
// From Guides/Permutations.md
|
||||
let numbers = [10, 20, 30]
|
||||
let permutations = numbers.permutations(ofCount: 2)
|
||||
XCTAssertEqualSequences(permutations, [
|
||||
[10, 20],
|
||||
[10, 30],
|
||||
[20, 10],
|
||||
[20, 30],
|
||||
[30, 10],
|
||||
[30, 20],
|
||||
])
|
||||
XCTAssertEqualSequences(
|
||||
permutations,
|
||||
[
|
||||
[10, 20],
|
||||
[10, 30],
|
||||
[20, 10],
|
||||
[20, 30],
|
||||
[30, 10],
|
||||
[30, 20],
|
||||
])
|
||||
}
|
||||
|
||||
|
||||
func testDocumentationExample3() {
|
||||
// From Guides/Permutations.md
|
||||
let numbers2 = [20, 10, 10]
|
||||
let permutations = numbers2.permutations()
|
||||
XCTAssertEqualSequences(permutations, [
|
||||
[20, 10, 10],
|
||||
[20, 10, 10],
|
||||
[10, 20, 10],
|
||||
[10, 10, 20],
|
||||
[10, 20, 10],
|
||||
[10, 10, 20],
|
||||
])
|
||||
XCTAssertEqualSequences(
|
||||
permutations,
|
||||
[
|
||||
[20, 10, 10],
|
||||
[20, 10, 10],
|
||||
[10, 20, 10],
|
||||
[10, 10, 20],
|
||||
[10, 20, 10],
|
||||
[10, 10, 20],
|
||||
])
|
||||
}
|
||||
|
||||
|
||||
func testDocumentationExample4() {
|
||||
// From Guides/Permutations.md
|
||||
let numbers = [10, 20, 30]
|
||||
let permutations = numbers.permutations(ofCount: 0...)
|
||||
XCTAssertEqualSequences(permutations, [
|
||||
[],
|
||||
[10],
|
||||
[20],
|
||||
[30],
|
||||
[10, 20],
|
||||
[10, 30],
|
||||
[20, 10],
|
||||
[20, 30],
|
||||
[30, 10],
|
||||
[30, 20],
|
||||
[10, 20, 30],
|
||||
[10, 30, 20],
|
||||
[20, 10, 30],
|
||||
[20, 30, 10],
|
||||
[30, 10, 20],
|
||||
[30, 20, 10],
|
||||
])
|
||||
XCTAssertEqualSequences(
|
||||
permutations,
|
||||
[
|
||||
[],
|
||||
[10],
|
||||
[20],
|
||||
[30],
|
||||
[10, 20],
|
||||
[10, 30],
|
||||
[20, 10],
|
||||
[20, 30],
|
||||
[30, 10],
|
||||
[30, 20],
|
||||
[10, 20, 30],
|
||||
[10, 30, 20],
|
||||
[20, 10, 30],
|
||||
[20, 30, 10],
|
||||
[30, 10, 20],
|
||||
[30, 20, 10],
|
||||
])
|
||||
}
|
||||
|
||||
|
||||
func testDocumentationExample5() {
|
||||
// From Permutations.swift
|
||||
let names = ["Alex", "Celeste", "Davide"]
|
||||
let permutations = names.permutations(ofCount: 2)
|
||||
XCTAssertEqualSequences(permutations, [
|
||||
["Alex", "Celeste"],
|
||||
["Alex", "Davide"],
|
||||
["Celeste", "Alex"],
|
||||
["Celeste", "Davide"],
|
||||
["Davide", "Alex"],
|
||||
["Davide", "Celeste"],
|
||||
])
|
||||
XCTAssertEqualSequences(
|
||||
permutations,
|
||||
[
|
||||
["Alex", "Celeste"],
|
||||
["Alex", "Davide"],
|
||||
["Celeste", "Alex"],
|
||||
["Celeste", "Davide"],
|
||||
["Davide", "Alex"],
|
||||
["Davide", "Celeste"],
|
||||
])
|
||||
}
|
||||
|
||||
|
||||
func testDocumentationExample6() {
|
||||
// From Permutations.swift
|
||||
let names = ["Alex", "Celeste", "Davide"]
|
||||
let permutations = names.permutations(ofCount: 1...2)
|
||||
XCTAssertEqualSequences(permutations, [
|
||||
["Alex"],
|
||||
["Celeste"],
|
||||
["Davide"],
|
||||
["Alex", "Celeste"],
|
||||
["Alex", "Davide"],
|
||||
["Celeste", "Alex"],
|
||||
["Celeste", "Davide"],
|
||||
["Davide", "Alex"],
|
||||
["Davide", "Celeste"],
|
||||
])
|
||||
XCTAssertEqualSequences(
|
||||
permutations,
|
||||
[
|
||||
["Alex"],
|
||||
["Celeste"],
|
||||
["Davide"],
|
||||
["Alex", "Celeste"],
|
||||
["Alex", "Davide"],
|
||||
["Celeste", "Alex"],
|
||||
["Celeste", "Davide"],
|
||||
["Davide", "Alex"],
|
||||
["Davide", "Celeste"],
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
|
||||
@testable import Algorithms
|
||||
|
||||
final class ProductTests: XCTestCase {
|
||||
@@ -22,7 +23,7 @@ final class ProductTests: XCTestCase {
|
||||
XCTAssertEqualSequences(product(1...10, ""), [], by: ==)
|
||||
XCTAssertEqualSequences(product("", 1...10), [], by: ==)
|
||||
}
|
||||
|
||||
|
||||
func testProductReversed() {
|
||||
XCTAssertEqualSequences(
|
||||
[(2, "B" as Character), (2, "A"), (1, "B"), (1, "A")],
|
||||
@@ -32,12 +33,12 @@ final class ProductTests: XCTestCase {
|
||||
XCTAssertEqualSequences(product(1...10, "").reversed(), [], by: ==)
|
||||
XCTAssertEqualSequences(product("", 1...10).reversed(), [], by: ==)
|
||||
}
|
||||
|
||||
|
||||
func testProductDistanceFromTo() {
|
||||
let p = product([1, 2], "abc")
|
||||
XCTAssertEqual(p.distance(from: p.startIndex, to: p.endIndex), 6)
|
||||
}
|
||||
|
||||
|
||||
func testProductIndexTraversals() {
|
||||
validateIndexTraversals(
|
||||
product([1, 2, 3, 4], "abc"),
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
|
||||
@testable import Algorithms
|
||||
|
||||
func validateRandomSamples<S: Sequence>(
|
||||
@@ -18,8 +19,9 @@ func validateRandomSamples<S: Sequence>(
|
||||
expectedValue: Int,
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) where S.Element == Int {
|
||||
let expectedRange = ((expectedValue / 3) * 2) ... ((expectedValue / 3) * 4)
|
||||
XCTAssertEqualSequences(samples.keys.sorted(), elements,
|
||||
let expectedRange = ((expectedValue / 3) * 2)...((expectedValue / 3) * 4)
|
||||
XCTAssertEqualSequences(
|
||||
samples.keys.sorted(), elements,
|
||||
file: file, line: line)
|
||||
for v in samples.values {
|
||||
XCTAssert(expectedRange.contains(v), file: file, line: line)
|
||||
@@ -43,7 +45,7 @@ final class RandomSampleTests: XCTestCase {
|
||||
}
|
||||
validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
|
||||
}
|
||||
|
||||
|
||||
func testRandomSampleCollection() {
|
||||
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
|
||||
for x in c.randomSample(count: k) {
|
||||
@@ -52,7 +54,7 @@ final class RandomSampleTests: XCTestCase {
|
||||
}
|
||||
validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
|
||||
}
|
||||
|
||||
|
||||
func testRandomSampleSequence() {
|
||||
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
|
||||
for x in s.randomSample(count: k) {
|
||||
@@ -61,7 +63,7 @@ final class RandomSampleTests: XCTestCase {
|
||||
}
|
||||
validateRandomSamples(samples, elements: s, expectedValue: (k * iterations) / n)
|
||||
}
|
||||
|
||||
|
||||
func testRandomSampleEdgeCases() {
|
||||
XCTAssert(c.randomStableSample(count: 0).isEmpty)
|
||||
XCTAssertEqualSequences(c.randomStableSample(count: n), c)
|
||||
@@ -70,12 +72,12 @@ final class RandomSampleTests: XCTestCase {
|
||||
XCTAssert(c.randomSample(count: 0).isEmpty)
|
||||
XCTAssertEqualSequences(c.randomSample(count: n).sorted(), c)
|
||||
XCTAssertEqualSequences(c.randomSample(count: n * 2).sorted(), c)
|
||||
|
||||
|
||||
XCTAssert(s.randomSample(count: 0).isEmpty)
|
||||
XCTAssertEqualSequences(s.randomSample(count: n).sorted(), c)
|
||||
XCTAssertEqualSequences(s.randomSample(count: n * 2).sorted(), c)
|
||||
}
|
||||
|
||||
|
||||
func testRandomSampleRepeatable() {
|
||||
var generator = SplitMix64(seed: 0)
|
||||
let sample1a = c.randomSample(count: k, using: &generator)
|
||||
@@ -88,7 +90,7 @@ final class RandomSampleTests: XCTestCase {
|
||||
generator = SplitMix64(seed: 0)
|
||||
let sample2b = s.randomSample(count: k, using: &generator)
|
||||
XCTAssertEqual(sample1b, sample2b)
|
||||
|
||||
|
||||
generator = SplitMix64(seed: 0)
|
||||
let sample1c = c.randomStableSample(count: k, using: &generator)
|
||||
generator = SplitMix64(seed: 0)
|
||||
@@ -101,7 +103,7 @@ final class RandomSampleTests: XCTestCase {
|
||||
mutating func next() -> UInt64 { 0 }
|
||||
}
|
||||
var zero = ZeroGenerator()
|
||||
_ = nextOffset(w: 1, using: &zero) // must not crash
|
||||
_ = nextOffset(w: 1, using: &zero) // must not crash
|
||||
|
||||
struct AlmostAllZeroGenerator: RandomNumberGenerator {
|
||||
private var forward: SplitMix64
|
||||
@@ -119,8 +121,8 @@ final class RandomSampleTests: XCTestCase {
|
||||
}
|
||||
|
||||
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)
|
||||
_ = c.randomSample(count: k, using: &almostAllZero) // must not crash
|
||||
_ = c.randomSample(count: k, using: &almostAllZero) // must not crash
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class ReductionsTests: XCTestCase {
|
||||
|
||||
struct TestError: Error {}
|
||||
|
||||
// MARK: - Exclusive Reductions
|
||||
|
||||
func testExclusiveLazy() {
|
||||
XCTAssertEqualSequences((1...).prefix(4).lazy.reductions(0, +), [0, 1, 3, 6, 10])
|
||||
XCTAssertEqualSequences((1...).prefix(1).lazy.reductions(0, +), [0, 1])
|
||||
XCTAssertEqualSequences((1...).prefix(0).lazy.reductions(0, +), [0])
|
||||
|
||||
XCTAssertEqualCollections([1, 2, 3, 4].lazy.reductions(0, +), [0, 1, 3, 6, 10])
|
||||
XCTAssertEqualCollections([1].lazy.reductions(0, +), [0, 1])
|
||||
XCTAssertEqualCollections(EmptyCollection<Int>().lazy.reductions(0, +), [0])
|
||||
|
||||
XCTAssertEqual([1, 2, 3, 4].lazy.reductions(into: 0, +=), [0, 1, 3, 6, 10])
|
||||
|
||||
XCTAssertEqual([1].lazy.reductions(into: 0, +=), [0, 1])
|
||||
|
||||
XCTAssertEqual(EmptyCollection<Int>().lazy.reductions(into: 0, +=), [0])
|
||||
|
||||
XCTAssertLazySequence((1...).prefix(1).lazy.reductions(0, +))
|
||||
XCTAssertLazySequence([1].lazy.reductions(0, +))
|
||||
XCTAssertLazyCollection([1].lazy.reductions(0, +))
|
||||
}
|
||||
|
||||
func testExclusiveEager() {
|
||||
XCTAssertEqual([1, 2, 3, 4].reductions(0, +), [0, 1, 3, 6, 10])
|
||||
XCTAssertEqual([1].reductions(0, +), [0, 1])
|
||||
XCTAssertEqual(EmptyCollection<Int>().reductions(0, +), [0])
|
||||
|
||||
XCTAssertEqual([1, 2, 3, 4].reductions(into: 0, +=), [0, 1, 3, 6, 10])
|
||||
|
||||
XCTAssertEqual([1].reductions(into: 0, +=), [0, 1])
|
||||
|
||||
XCTAssertEqual(EmptyCollection<Int>().reductions(into: 0, +=), [0])
|
||||
|
||||
XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() })
|
||||
XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() })
|
||||
}
|
||||
|
||||
// MARK: - Inclusive Reductions
|
||||
|
||||
func testInclusiveLazy() {
|
||||
XCTAssertEqualSequences((1...).prefix(4).lazy.reductions(+), [1, 3, 6, 10])
|
||||
XCTAssertEqualSequences((1...).prefix(1).lazy.reductions(+), [1])
|
||||
XCTAssertEqualSequences((1...).prefix(0).lazy.reductions(+), [])
|
||||
|
||||
XCTAssertEqualCollections([1, 2, 3, 4].lazy.reductions(+), [1, 3, 6, 10])
|
||||
XCTAssertEqualCollections([1].lazy.reductions(+), [1])
|
||||
XCTAssertEqualCollections(EmptyCollection<Int>().lazy.reductions(+), [])
|
||||
|
||||
XCTAssertLazySequence((1...).prefix(1).lazy.reductions(+))
|
||||
XCTAssertLazySequence([1].lazy.reductions(+))
|
||||
XCTAssertLazyCollection([1].lazy.reductions(+))
|
||||
}
|
||||
|
||||
func testInclusiveEager() {
|
||||
XCTAssertEqual([1, 2, 3, 4].reductions(+), [1, 3, 6, 10])
|
||||
XCTAssertEqual([1].reductions(+), [1])
|
||||
XCTAssertEqual(EmptyCollection<Int>().reductions(+), [])
|
||||
|
||||
XCTAssertNoThrow(try [].reductions { _, _ in throw TestError() })
|
||||
XCTAssertNoThrow(try [1].reductions { _, _ in throw TestError() })
|
||||
XCTAssertThrowsError(try [1, 1].reductions { _, _ in throw TestError() })
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
|
||||
@testable import Algorithms
|
||||
|
||||
final class RotateTests: XCTestCase {
|
||||
@@ -17,20 +18,21 @@ final class RotateTests: XCTestCase {
|
||||
func testUnderscoreReverse() {
|
||||
var input = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]
|
||||
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"]
|
||||
XCTAssertEqual(input, expected)
|
||||
XCTAssertEqual(lower, input.startIndex.advanced(by: limit))
|
||||
XCTAssertEqual(upper, input.endIndex.advanced(by: -limit))
|
||||
}
|
||||
|
||||
|
||||
/// Tests the example given in `reverse(subrange:)`’s documentation
|
||||
func testReverse() {
|
||||
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
numbers.reverse(subrange: 0..<4)
|
||||
XCTAssertEqual(numbers, [40, 30, 20, 10, 50, 60, 70, 80])
|
||||
}
|
||||
|
||||
|
||||
/// Tests `rotate(subrange:toStartAt:)` with an empty subrange
|
||||
/// The order of elements are unchanged
|
||||
func testRotateEmptySubrange() {
|
||||
@@ -39,7 +41,7 @@ final class RotateTests: XCTestCase {
|
||||
XCTAssertEqual(numbers, [10, 20, 30, 40, 50, 60, 70, 80])
|
||||
XCTAssertEqual(numbers[oldStart], 40)
|
||||
}
|
||||
|
||||
|
||||
/// Tests `rotate(subrange:toStartAt:)` with an empty collection
|
||||
func testRotateSubrangeOnEmptyCollection() {
|
||||
var numbers = [Int]()
|
||||
@@ -47,7 +49,7 @@ final class RotateTests: XCTestCase {
|
||||
XCTAssertEqual(numbers, [])
|
||||
XCTAssertEqual(oldStart, numbers.startIndex)
|
||||
}
|
||||
|
||||
|
||||
/// Tests `rotate(subrange:toStartAt:)` with the full range of the collection
|
||||
func testRotateFullRange() {
|
||||
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[oldStart], 10)
|
||||
}
|
||||
|
||||
|
||||
/// Tests the example given in `rotate(subrange:toStartAt:)`’s documentation
|
||||
func testRotateSubrange() {
|
||||
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[oldStart], 10)
|
||||
}
|
||||
|
||||
|
||||
/// Tests the example given in `rotate(toStartAt:)`’s documentation
|
||||
func testRotateExample() {
|
||||
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[oldStart], 10)
|
||||
}
|
||||
|
||||
|
||||
/// Tests `rotate(toStartAt:)` on collections of varying lengths, at different
|
||||
/// starting points
|
||||
func testRotate() {
|
||||
|
||||
@@ -9,11 +9,11 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class StridingTests: XCTestCase {
|
||||
|
||||
|
||||
func testStride() {
|
||||
let a = 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: 10), [0, 10])
|
||||
XCTAssertEqualSequences(a.striding(by: 11), [0])
|
||||
|
||||
|
||||
let s = (0...).prefix(11)
|
||||
XCTAssertEqualSequences(s.striding(by: 1), (0...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: 10), [0, 10])
|
||||
XCTAssertEqualSequences(s.striding(by: 11), [0])
|
||||
|
||||
|
||||
let empty = (0...).prefix(0)
|
||||
XCTAssertEqualSequences(empty.striding(by: 2), [])
|
||||
}
|
||||
|
||||
|
||||
func testStrideString() {
|
||||
let s = "swift"
|
||||
XCTAssertEqualSequences(s.striding(by: 2), ["s", "i", "t"])
|
||||
}
|
||||
|
||||
|
||||
func testStrideReversed() {
|
||||
let a = [0, 1, 2, 3, 4, 5]
|
||||
XCTAssertEqualSequences(a.striding(by: 3).reversed(), [3, 0])
|
||||
XCTAssertEqualSequences(a.reversed().striding(by: 2), [5, 3, 1])
|
||||
}
|
||||
|
||||
|
||||
func testStrideIndexes() {
|
||||
let a = [0, 1, 2, 3, 4, 5].striding(by: 2)
|
||||
var i = a.startIndex
|
||||
@@ -60,33 +60,20 @@ final class StridingTests: XCTestCase {
|
||||
XCTAssertEqual(a[i], 2)
|
||||
a.formIndex(before: &i)
|
||||
XCTAssertEqual(a[i], 0)
|
||||
// a.formIndex(before: &i) // Precondition failed: Incrementing past start index
|
||||
// a.index(after: a.endIndex) // Precondition failed: Advancing past end index
|
||||
// a.formIndex(before: &i) // Precondition failed: Incrementing past start index
|
||||
// a.index(after: a.endIndex) // Precondition failed: Advancing past end index
|
||||
}
|
||||
|
||||
func testStrideCompositionEquivalence() {
|
||||
let a = (0...10)
|
||||
XCTAssertEqualSequences(a.striding(by: 6), a.striding(by: 2).striding(by: 3))
|
||||
XCTAssertTrue(a.striding(by: 6) == a.striding(by: 2).striding(by: 3))
|
||||
XCTAssert(type(of: a.striding(by: 2).striding(by: 3)) == StrideCollection<ClosedRange<Int>>.self)
|
||||
}
|
||||
|
||||
func testEquality() {
|
||||
let a = [1, 2, 3, 4, 5].striding(by: 2)
|
||||
let b = [1, 0, 3, 0, 5].striding(by: 2)
|
||||
XCTAssertEqual(a, b)
|
||||
}
|
||||
|
||||
|
||||
func testStrideLast() {
|
||||
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: 4).last, 9) // 1, 5, 9
|
||||
XCTAssertEqual((1...10).striding(by: 5).last, 6) // 1, 6
|
||||
XCTAssertEqual((1...100).striding(by: 50).last, 51) // 1, 51
|
||||
XCTAssertEqual((1...5).striding(by: 2).last, 5) // 1, 3, 5
|
||||
XCTAssertEqual([Int]().striding(by: 2).last, nil) // empty
|
||||
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: 4).last, 9) // 1, 5, 9
|
||||
XCTAssertEqual((1...10).striding(by: 5).last, 6) // 1, 6
|
||||
XCTAssertEqual((1...100).striding(by: 50).last, 51) // 1, 51
|
||||
XCTAssertEqual((1...5).striding(by: 2).last, 5) // 1, 3, 5
|
||||
XCTAssertEqual([Int]().striding(by: 2).last, nil) // empty
|
||||
}
|
||||
|
||||
|
||||
func testCount() {
|
||||
let empty = [Int]().striding(by: 2)
|
||||
XCTAssertEqual(empty.count, 0)
|
||||
@@ -99,7 +86,7 @@ final class StridingTests: XCTestCase {
|
||||
XCTAssertEqual(a.striding(by: 10).count, [0, 10].count)
|
||||
XCTAssertEqual(a.striding(by: 11).count, [0].count)
|
||||
}
|
||||
|
||||
|
||||
func testIndexTraversals() {
|
||||
let empty = [Int]()
|
||||
validateIndexTraversals(
|
||||
@@ -126,7 +113,6 @@ final class StridingTests: XCTestCase {
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
func testOffsetBy() {
|
||||
let a = (0...100).striding(by: 22)
|
||||
let b = [0, 22, 44, 66, 88]
|
||||
@@ -134,10 +120,10 @@ final class StridingTests: XCTestCase {
|
||||
XCTAssertEqual(a[a.index(a.startIndex, offsetBy: i)], b[i])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testOffsetByEndIndex() {
|
||||
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)
|
||||
XCTAssertEqual(i, b.endIndex)
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
|
||||
@testable import Algorithms
|
||||
|
||||
final class SuffixTests: XCTestCase {
|
||||
@@ -19,29 +20,29 @@ final class SuffixTests: XCTestCase {
|
||||
XCTAssertEqualSequences(a.suffix(while: { $0 > 10 }), [])
|
||||
XCTAssertEqualSequences(a.suffix(while: { $0 > 9 }), [10])
|
||||
XCTAssertEqualSequences(a.suffix(while: { $0 > -1 }), (0...10))
|
||||
|
||||
|
||||
let empty: [Int] = []
|
||||
XCTAssertEqualSequences(empty.suffix(while: { $0 > 10 }), [])
|
||||
}
|
||||
|
||||
|
||||
func testEndOfPrefix() {
|
||||
let array = Array(0..<10)
|
||||
XCTAssertEqual(array.endOfPrefix(while: { $0 < 3 }), 3)
|
||||
XCTAssertEqual(array.endOfPrefix(while: { _ in false }), array.startIndex)
|
||||
XCTAssertEqual(array.endOfPrefix(while: { _ in true }), array.endIndex)
|
||||
|
||||
|
||||
let empty = [Int]()
|
||||
XCTAssertEqual(empty.endOfPrefix(while: { $0 < 3 }), 0)
|
||||
XCTAssertEqual(empty.endOfPrefix(while: { _ in false }), empty.startIndex)
|
||||
XCTAssertEqual(empty.endOfPrefix(while: { _ in true }), empty.endIndex)
|
||||
}
|
||||
|
||||
|
||||
func testStartOfSuffix() {
|
||||
let array = Array(0..<10)
|
||||
XCTAssertEqual(array.startOfSuffix(while: { $0 >= 3 }), 3)
|
||||
XCTAssertEqual(array.startOfSuffix(while: { _ in false }), array.endIndex)
|
||||
XCTAssertEqual(array.startOfSuffix(while: { _ in true }), array.startIndex)
|
||||
|
||||
|
||||
let empty = [Int]()
|
||||
XCTAssertEqual(empty.startOfSuffix(while: { $0 < 3 }), 0)
|
||||
XCTAssertEqual(empty.startOfSuffix(while: { _ in false }), empty.endIndex)
|
||||
|
||||
@@ -32,16 +32,16 @@ extension Numeric {
|
||||
|
||||
struct SplitMix64: RandomNumberGenerator {
|
||||
private var state: UInt64
|
||||
|
||||
|
||||
init(seed: UInt64) {
|
||||
self.state = seed
|
||||
}
|
||||
|
||||
|
||||
mutating func next() -> UInt64 {
|
||||
self.state &+= 0x9e3779b97f4a7c15
|
||||
self.state &+= 0x9e37_79b9_7f4a_7c15
|
||||
var z: UInt64 = self.state
|
||||
z = (z ^ (z &>> 30)) &* 0xbf58476d1ce4e5b9
|
||||
z = (z ^ (z &>> 27)) &* 0x94d049bb133111eb
|
||||
z = (z ^ (z &>> 30)) &* 0xbf58_476d_1ce4_e5b9
|
||||
z = (z ^ (z &>> 27)) &* 0x94d0_49bb_1331_11eb
|
||||
return z ^ (z &>> 31)
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ struct AnyMutableCollection<Base> where Base: MutableCollection {
|
||||
extension AnyMutableCollection: MutableCollection {
|
||||
typealias Index = Base.Index
|
||||
typealias Element = Base.Element
|
||||
|
||||
|
||||
var startIndex: Base.Index { base.startIndex }
|
||||
var endIndex: Base.Index { base.endIndex }
|
||||
|
||||
@@ -80,7 +80,8 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
|
||||
_ message: @autoclosure () -> String = "",
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
|
||||
try XCTAssertEqualSequences(expression1(), expression2(), by: ==,
|
||||
try XCTAssertEqualSequences(
|
||||
expression1(), expression2(), by: ==,
|
||||
message(), file: file, line: line)
|
||||
}
|
||||
|
||||
@@ -99,7 +100,7 @@ func XCTAssertUnorderedEqualSequences<S1: Sequence, S2: Sequence>(
|
||||
}
|
||||
s1.remove(at: idx)
|
||||
}
|
||||
|
||||
|
||||
XCTAssertTrue(
|
||||
missing.isEmpty, "first sequence missing '\(missing)' elements from second sequence",
|
||||
file: file, line: line
|
||||
@@ -121,8 +122,9 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
|
||||
|
||||
func fail(_ reason: String) {
|
||||
let message = message()
|
||||
XCTFail(message.isEmpty ? reason : "\(message) - \(reason)",
|
||||
file: file, line: line)
|
||||
XCTFail(
|
||||
message.isEmpty ? reason : "\(message) - \(reason)",
|
||||
file: file, line: line)
|
||||
}
|
||||
|
||||
var iter1 = try expression1().makeIterator()
|
||||
@@ -134,7 +136,9 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
|
||||
idx += 1
|
||||
continue
|
||||
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):
|
||||
fail("second sequence shorter than first")
|
||||
case (nil, _?):
|
||||
@@ -148,6 +152,21 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
|
||||
func XCTAssertLazySequence<S: LazySequenceProtocol>(_: S) {}
|
||||
func XCTAssertLazyCollection<S: LazyCollectionProtocol>(_: S) {}
|
||||
|
||||
/// Asserts two collections are equal by using their indices to access elements.
|
||||
func XCTAssertEqualCollections<C1: Collection, C2: Collection>(
|
||||
_ expression1: @autoclosure () throws -> C1,
|
||||
_ expression2: @autoclosure () throws -> C2,
|
||||
_ message: @autoclosure () -> String = "",
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) rethrows where C1.Element: Equatable, C1.Element == C2.Element {
|
||||
let c1 = try expression1()
|
||||
let c2 = try expression2()
|
||||
XCTAssertEqual(c1.indices.count, c2.indices.count, message(), file: file, line: line)
|
||||
for index in zip(c1.indices, c2.indices) {
|
||||
XCTAssertEqual(c1[index.0], c2[index.1], message(), file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests that all index traversal methods behave as expected.
|
||||
///
|
||||
/// Verifies the correctness of the implementations of `startIndex`, `endIndex`,
|
||||
@@ -175,7 +194,7 @@ func validateIndexTraversals<C>(
|
||||
for c in collections {
|
||||
let indicesIncludingEnd = indices?(c) ?? (c.indices + [c.endIndex])
|
||||
let count = indicesIncludingEnd.count - 1
|
||||
|
||||
|
||||
XCTAssertEqual(
|
||||
c.count, count,
|
||||
"Count mismatch",
|
||||
@@ -192,11 +211,11 @@ func validateIndexTraversals<C>(
|
||||
c.endIndex, indicesIncludingEnd.last,
|
||||
"`endIndex` does not equal the last index",
|
||||
file: file, line: line)
|
||||
|
||||
|
||||
// `index(after:)`
|
||||
do {
|
||||
var index = c.startIndex
|
||||
|
||||
|
||||
for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() {
|
||||
c.formIndex(after: &index)
|
||||
XCTAssertEqual(
|
||||
@@ -208,7 +227,7 @@ func validateIndexTraversals<C>(
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// `index(before:)`
|
||||
do {
|
||||
var index = c.endIndex
|
||||
@@ -224,7 +243,7 @@ func validateIndexTraversals<C>(
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// `indices`
|
||||
XCTAssertEqual(c.indices.count, count)
|
||||
for (offset, index) in c.indices.enumerated() {
|
||||
@@ -233,7 +252,7 @@ func validateIndexTraversals<C>(
|
||||
"Index mismatch at offset \(offset) in `indices`",
|
||||
file: file, line: line)
|
||||
}
|
||||
|
||||
|
||||
// index comparison
|
||||
for (offsetA, a) in indicesIncludingEnd.enumerated() {
|
||||
XCTAssertEqual(
|
||||
@@ -244,7 +263,7 @@ func validateIndexTraversals<C>(
|
||||
a < a,
|
||||
"Index at offset \(offsetA) is less than itself",
|
||||
file: file, line: line)
|
||||
|
||||
|
||||
for (offsetB, b) in indicesIncludingEnd[..<offsetA].enumerated() {
|
||||
XCTAssertNotEqual(
|
||||
a, b,
|
||||
@@ -258,12 +277,12 @@ func validateIndexTraversals<C>(
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// `index(_:offsetBy:)` and `distance(from:to:)`
|
||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
||||
for (endOffset, end) in indicesIncludingEnd.enumerated() {
|
||||
let distance = endOffset - startOffset
|
||||
|
||||
|
||||
XCTAssertEqual(
|
||||
c.index(start, offsetBy: distance), end,
|
||||
"""
|
||||
@@ -280,7 +299,7 @@ func validateIndexTraversals<C>(
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// `index(_:offsetBy:limitedBy:)`
|
||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
||||
for (limitOffset, limit) in indicesIncludingEnd.enumerated() {
|
||||
@@ -292,7 +311,7 @@ func validateIndexTraversals<C>(
|
||||
for targetOffset in range {
|
||||
let distance = targetOffset - startOffset
|
||||
let end = c.index(start, offsetBy: distance, limitedBy: limit)
|
||||
|
||||
|
||||
if pastLimit {
|
||||
XCTAssertNil(
|
||||
end,
|
||||
@@ -313,7 +332,7 @@ func validateIndexTraversals<C>(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// forward offsets
|
||||
if limit >= start {
|
||||
// the limit has an effect
|
||||
@@ -323,7 +342,7 @@ func validateIndexTraversals<C>(
|
||||
// the limit has no effect
|
||||
checkTargetRange(startOffset...count, pastLimit: false)
|
||||
}
|
||||
|
||||
|
||||
// backward offsets
|
||||
if limit <= start {
|
||||
// the limit has an effect
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class UniquePermutationsTests: XCTestCase {
|
||||
static let numbers = [1, 1, 1, 2, 3]
|
||||
|
||||
static let numbersPermutations: [[[Int]]] = [
|
||||
// k = 0
|
||||
[[]],
|
||||
// 1
|
||||
[[1], [2], [3]],
|
||||
// 2
|
||||
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]],
|
||||
// 3
|
||||
[
|
||||
[1, 1, 1], [1, 1, 2], [1, 1, 3],
|
||||
[1, 2, 1], [1, 2, 3], [1, 3, 1], [1, 3, 2],
|
||||
[2, 1, 1], [2, 1, 3], [2, 3, 1],
|
||||
[3, 1, 1], [3, 1, 2], [3, 2, 1],
|
||||
],
|
||||
// 4
|
||||
[
|
||||
[1, 1, 1, 2], [1, 1, 1, 3],
|
||||
[1, 1, 2, 1], [1, 1, 2, 3],
|
||||
[1, 1, 3, 1], [1, 1, 3, 2],
|
||||
[1, 2, 1, 1], [1, 2, 1, 3], [1, 2, 3, 1],
|
||||
[1, 3, 1, 1], [1, 3, 1, 2], [1, 3, 2, 1],
|
||||
[2, 1, 1, 1], [2, 1, 1, 3], [2, 1, 3, 1], [2, 3, 1, 1],
|
||||
[3, 1, 1, 1], [3, 1, 1, 2], [3, 1, 2, 1], [3, 2, 1, 1],
|
||||
],
|
||||
// 5
|
||||
[
|
||||
[1, 1, 1, 2, 3], [1, 1, 1, 3, 2],
|
||||
[1, 1, 2, 1, 3], [1, 1, 2, 3, 1],
|
||||
[1, 1, 3, 1, 2], [1, 1, 3, 2, 1],
|
||||
[1, 2, 1, 1, 3], [1, 2, 1, 3, 1], [1, 2, 3, 1, 1],
|
||||
[1, 3, 1, 1, 2], [1, 3, 1, 2, 1], [1, 3, 2, 1, 1],
|
||||
[2, 1, 1, 1, 3], [2, 1, 1, 3, 1], [2, 1, 3, 1, 1], [2, 3, 1, 1, 1],
|
||||
[3, 1, 1, 1, 2], [3, 1, 1, 2, 1], [3, 1, 2, 1, 1], [3, 2, 1, 1, 1],
|
||||
],
|
||||
]
|
||||
}
|
||||
|
||||
extension UniquePermutationsTests {
|
||||
func testEmpty() {
|
||||
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(), [[]])
|
||||
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 0), [[]])
|
||||
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 1), [])
|
||||
XCTAssertEqualSequences(
|
||||
([] as [Int]).uniquePermutations(ofCount: 1...3), [])
|
||||
}
|
||||
|
||||
func testSingleCounts() {
|
||||
for (k, expectation) in Self.numbersPermutations.enumerated() {
|
||||
XCTAssertEqualSequences(
|
||||
expectation,
|
||||
Self.numbers.uniquePermutations(ofCount: k))
|
||||
}
|
||||
|
||||
XCTAssertEqualSequences(
|
||||
Self.numbersPermutations[5],
|
||||
Self.numbers.uniquePermutations())
|
||||
}
|
||||
|
||||
func testRanges() {
|
||||
for lower in Self.numbersPermutations.indices {
|
||||
// upper bounded
|
||||
XCTAssertEqualSequences(
|
||||
Self.numbersPermutations[...lower].joined(),
|
||||
Self.numbers.uniquePermutations(ofCount: ...lower))
|
||||
|
||||
// lower bounded
|
||||
XCTAssertEqualSequences(
|
||||
Self.numbersPermutations[lower...].joined(),
|
||||
Self.numbers.uniquePermutations(ofCount: lower...))
|
||||
|
||||
for upper in lower..<Self.numbersPermutations.count {
|
||||
XCTAssertEqualSequences(
|
||||
Self.numbersPermutations[lower..<upper].joined(),
|
||||
Self.numbers.uniquePermutations(ofCount: lower..<upper))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquePermutationsTests {
|
||||
private final class IntBox: Hashable {
|
||||
var value: Int
|
||||
|
||||
init(_ value: Int) {
|
||||
self.value = value
|
||||
}
|
||||
|
||||
static func == (lhs: IntBox, rhs: IntBox) -> Bool {
|
||||
lhs.value == rhs.value
|
||||
}
|
||||
|
||||
func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(value)
|
||||
}
|
||||
}
|
||||
|
||||
func testFirstUnique() {
|
||||
// When duplicate elements are encountered, all permutations use the first
|
||||
// instance of the duplicated elements.
|
||||
let numbers = Self.numbers.map(IntBox.init)
|
||||
for k in 0...numbers.count {
|
||||
for p in numbers.uniquePermutations(ofCount: k) {
|
||||
XCTAssertTrue(p.filter { $0.value == 1 }.allSatisfy { $0 === numbers[0] })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testLaziness() {
|
||||
XCTAssertLazySequence("ABCD".lazy.uniquePermutations())
|
||||
}
|
||||
}
|
||||
@@ -9,26 +9,45 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class UniqueTests: XCTestCase {
|
||||
func testUnique() {
|
||||
let a = repeatElement(1...10, count: 15).joined().shuffled()
|
||||
let b = a.uniqued()
|
||||
XCTAssertEqual(b.sorted(), Set(a).sorted())
|
||||
XCTAssertEqual(10, b.count)
|
||||
|
||||
XCTAssertEqual(10, Array(b).count)
|
||||
|
||||
let c: [Int] = []
|
||||
XCTAssertEqual(c.uniqued(), [])
|
||||
XCTAssertEqualSequences(c.uniqued(), [])
|
||||
|
||||
let d = Array(repeating: 1, count: 10)
|
||||
XCTAssertEqualSequences(d.uniqued(), [1])
|
||||
}
|
||||
|
||||
|
||||
func testUniqueOn() {
|
||||
let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
|
||||
let b = a.uniqued(on: { $0.first })
|
||||
XCTAssertEqual(["Albemarle", "Brandywine"], b)
|
||||
|
||||
|
||||
let c: [Int] = []
|
||||
XCTAssertEqual(c.uniqued(on: { $0.bitWidth }), [])
|
||||
|
||||
let d = Array(repeating: "Andromeda", count: 10)
|
||||
XCTAssertEqualSequences(d.uniqued(on: { $0.first }), ["Andromeda"])
|
||||
}
|
||||
|
||||
func testLazyUniqueOn() {
|
||||
let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
|
||||
let b = a.lazy.uniqued(on: { $0.first })
|
||||
XCTAssertEqualSequences(b, ["Albemarle", "Brandywine"])
|
||||
XCTAssertLazySequence(b)
|
||||
|
||||
let c: [Int] = []
|
||||
XCTAssertEqualSequences(c.lazy.uniqued(on: { $0.bitWidth }), [])
|
||||
|
||||
let d = Array(repeating: "Andromeda", count: 10)
|
||||
XCTAssertEqualSequences(d.lazy.uniqued(on: { $0.first }), ["Andromeda"])
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,11 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
|
||||
@testable import Algorithms
|
||||
|
||||
final class windowsTests: XCTestCase {
|
||||
|
||||
|
||||
func testWindowsOfString() {
|
||||
let s = "swift"
|
||||
let w = s.windows(ofCount: 2)
|
||||
@@ -27,56 +28,56 @@ final class windowsTests: XCTestCase {
|
||||
w.formIndex(after: &i)
|
||||
XCTAssertEqualSequences(w[i], "ft")
|
||||
|
||||
// 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.formIndex(after: &i); w[i] // ← 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.formIndex(after: &i); w[i] // ← Precondition failed: windows index is out of range
|
||||
}
|
||||
|
||||
|
||||
func testWindowsOfRange() {
|
||||
let a = 0...100
|
||||
|
||||
|
||||
XCTAssertTrue(a.windows(ofCount: 200).isEmpty)
|
||||
|
||||
|
||||
let w = a.windows(ofCount: 10)
|
||||
|
||||
|
||||
XCTAssertEqualSequences(w.first!, 0..<10)
|
||||
XCTAssertEqualSequences(w.last!, 91..<101)
|
||||
}
|
||||
|
||||
|
||||
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.map { $0.reduce(0, +) }, [1, 1, 1])
|
||||
|
||||
|
||||
let a2 = [0, 1, 2, 3, 4, 5, 6].windows(ofCount: 3).map {
|
||||
$0.reduce(0, +)
|
||||
}.reduce(0, +)
|
||||
|
||||
|
||||
XCTAssertEqual(a2, 3 + 6 + 9 + 12 + 15)
|
||||
}
|
||||
|
||||
|
||||
func testWindowsCount() {
|
||||
let a = [0, 1, 2, 3, 4, 5]
|
||||
XCTAssertEqual(a.windows(ofCount: 3).count, 4)
|
||||
|
||||
|
||||
let a2 = [0, 1, 2, 3, 4]
|
||||
XCTAssertEqual(a2.windows(ofCount: 6).count, 0)
|
||||
|
||||
|
||||
let a3 = [Int]()
|
||||
XCTAssertEqual(a3.windows(ofCount: 2).count, 0)
|
||||
}
|
||||
|
||||
|
||||
func testWindowsSecondAndLast() {
|
||||
let a = [0, 1, 2, 3, 4, 5]
|
||||
let w = a.windows(ofCount: 4)
|
||||
let snd = w[w.index(after: w.startIndex)]
|
||||
XCTAssertEqualSequences(snd, [1, 2, 3, 4])
|
||||
|
||||
|
||||
let w2 = a.windows(ofCount: 3)
|
||||
XCTAssertEqualSequences(w2.last!, [3, 4, 5])
|
||||
}
|
||||
|
||||
|
||||
func testWindowsIndexAfterAndBefore() {
|
||||
let a = [0, 1, 2, 3, 4, 5].windows(ofCount: 2)
|
||||
var i = a.startIndex
|
||||
@@ -85,7 +86,7 @@ final class windowsTests: XCTestCase {
|
||||
a.formIndex(before: &i)
|
||||
XCTAssertEqualSequences(a[i], [1, 2])
|
||||
}
|
||||
|
||||
|
||||
func testWindowsIndexTraversals() {
|
||||
validateIndexTraversals(
|
||||
"".windows(ofCount: 1),
|
||||
|
||||
Reference in new issue
Block a user