mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-22 04:10:39 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6011cc5d0 | ||
|
|
993b950250 |
No files matched your search
@@ -16,7 +16,7 @@ about: Something isn't working as expected
|
||||
|
||||
Replace this paragraph with a short description of the incorrect incorrect behavior. If this is a regression, please note the last version that the behavior was correct in addition to your current version.
|
||||
|
||||
**Swift Algorithms version:** `1.0.0` or the `main` branch, for example.
|
||||
**Swift Algorithms version:** `0.0.1` or the `main` branch, for example.
|
||||
**Swift version:** Paste the output of `swift --version` here.
|
||||
|
||||
### Checklist
|
||||
|
||||
@@ -17,5 +17,5 @@ Replace this paragraph with a description of your changes and rationale. Provide
|
||||
### Checklist
|
||||
- [ ] I've added at least one test that validates that my change is working, if appropriate
|
||||
- [ ] I've followed the code style of the rest of the project
|
||||
- [ ] I've read the [Contribution Guidelines](../blob/main/CONTRIBUTING.md)
|
||||
- [ ] I've read the [Contribution Guidelines](../CONTRIBUTING.md)
|
||||
- [ ] I've updated the documentation if necessary
|
||||
@@ -34,5 +34,5 @@ What is the impact of this change on existing users? Does it deprecate or remove
|
||||
### Checklist
|
||||
- [ ] I've added at least one test that validates that my change is working, if appropriate
|
||||
- [ ] I've followed the code style of the rest of the project
|
||||
- [ ] I've read the [Contribution Guidelines](../../blob/main/CONTRIBUTING.md)
|
||||
- [ ] I've read the [Contribution Guidelines](../../CONTRIBUTING.md)
|
||||
- [ ] I've updated the documentation if necessary
|
||||
@@ -1,34 +0,0 @@
|
||||
name: Pull request
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
|
||||
jobs:
|
||||
validate_format_config:
|
||||
name: Validate Format Config
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repo
|
||||
uses: actions/checkout@v4
|
||||
- name: Install apt dependencies
|
||||
run: sudo apt-get -qq update && sudo apt-get -qq -y install curl
|
||||
- name: Compare against swift-mmio swift-format config
|
||||
run: |
|
||||
curl -sL https://raw.githubusercontent.com/apple/swift-mmio/refs/heads/main/.swift-format -o .swift-format-mmio
|
||||
diff .swift-format .swift-format-mmio
|
||||
|
||||
tests:
|
||||
name: Test
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
|
||||
with:
|
||||
enable_wasm_sdk_build: true
|
||||
enable_android_sdk_build: true
|
||||
enable_android_sdk_checks: true
|
||||
|
||||
soundness:
|
||||
name: Soundness
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
|
||||
@@ -1,10 +0,0 @@
|
||||
@@===----------------------------------------------------------------------===@@
|
||||
@@
|
||||
@@ This source file is part of the Swift Algorithms open source project
|
||||
@@
|
||||
@@ Copyright (c) YEARS 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
|
||||
@@
|
||||
@@===----------------------------------------------------------------------===@@
|
||||
@@ -1,30 +0,0 @@
|
||||
.gitignore
|
||||
**/.gitignore
|
||||
.licenseignore
|
||||
.gitattributes
|
||||
.git-blame-ignore-revs
|
||||
.mailfilter
|
||||
.mailmap
|
||||
.spi.yml
|
||||
.swift-format
|
||||
.editorconfig
|
||||
.github/*
|
||||
*.md
|
||||
*.mdoc
|
||||
*.txt
|
||||
*.yml
|
||||
*.yaml
|
||||
*.json
|
||||
*.png
|
||||
*.bash
|
||||
*.cmake
|
||||
*.cmake.in
|
||||
Package.swift
|
||||
**/Package.swift
|
||||
Package@*.swift
|
||||
**/Package@*.swift
|
||||
Package.resolved
|
||||
**/Package.resolved
|
||||
.unacceptablelanguageignore
|
||||
**/Snapshots/*
|
||||
Xcode/*
|
||||
@@ -1,4 +0,0 @@
|
||||
version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [Algorithms]
|
||||
+9
-26
@@ -5,27 +5,20 @@
|
||||
"indentation" : {
|
||||
"spaces" : 2
|
||||
},
|
||||
"indentConditionalCompilationBlocks" : false,
|
||||
"indentConditionalCompilationBlocks" : true,
|
||||
"indentSwitchCaseLabels" : false,
|
||||
"lineBreakAroundMultilineExpressionChainComponents" : false,
|
||||
"lineBreakBeforeControlFlowKeywords" : false,
|
||||
"lineBreakBeforeEachArgument" : false,
|
||||
"lineBreakBeforeEachGenericRequirement" : false,
|
||||
"lineLength" : 80,
|
||||
"lineLength" : 100,
|
||||
"maximumBlankLines" : 1,
|
||||
"multiElementCollectionTrailingCommas" : true,
|
||||
"noAssignmentInExpressions" : {
|
||||
"allowedFunctions" : [
|
||||
"XCTAssertNoThrow"
|
||||
]
|
||||
},
|
||||
"prioritizeKeepingFunctionOutputTogether" : false,
|
||||
"respectsExistingLineBreaks" : true,
|
||||
"respectsExistingLineBreaks" : false,
|
||||
"rules" : {
|
||||
"AllPublicDeclarationsHaveDocumentation" : false,
|
||||
"AlwaysUseLiteralForEmptyCollectionInit" : true,
|
||||
"AlwaysUseLowerCamelCase" : true,
|
||||
"AmbiguousTrailingClosureOverload" : false,
|
||||
"AmbiguousTrailingClosureOverload" : true,
|
||||
"BeginDocumentationCommentWithOneLineSummary" : true,
|
||||
"DoNotUseSemicolons" : true,
|
||||
"DontRepeatTypeInStaticProperties" : true,
|
||||
@@ -33,39 +26,29 @@
|
||||
"FullyIndirectEnum" : true,
|
||||
"GroupNumericLiterals" : true,
|
||||
"IdentifiersMustBeASCII" : true,
|
||||
"NeverForceUnwrap" : true,
|
||||
"NeverUseForceTry" : true,
|
||||
"NeverUseImplicitlyUnwrappedOptionals" : true,
|
||||
"NeverForceUnwrap" : false,
|
||||
"NeverUseForceTry" : false,
|
||||
"NeverUseImplicitlyUnwrappedOptionals" : false,
|
||||
"NoAccessLevelOnExtensionDeclaration" : true,
|
||||
"NoAssignmentInExpressions" : true,
|
||||
"NoBlockComments" : true,
|
||||
"NoCasesWithOnlyFallthrough" : true,
|
||||
"NoEmptyTrailingClosureParentheses" : true,
|
||||
"NoLabelsInCasePatterns" : true,
|
||||
"NoLeadingUnderscores" : false,
|
||||
"NoParensAroundConditions" : true,
|
||||
"NoPlaygroundLiterals" : true,
|
||||
"NoVoidReturnOnFunctionSignature" : true,
|
||||
"OmitExplicitReturns" : true,
|
||||
"OneCasePerLine" : true,
|
||||
"OneVariableDeclarationPerLine" : true,
|
||||
"OnlyOneTrailingClosureArgument" : true,
|
||||
"OrderedImports" : true,
|
||||
"ReplaceForEachWithForLoop" : true,
|
||||
"ReturnVoidInsteadOfEmptyTuple" : true,
|
||||
"TypeNamesShouldBeCapitalized" : true,
|
||||
"UseEarlyExits" : false,
|
||||
"UseExplicitNilCheckInConditions" : true,
|
||||
"UseLetInEveryBoundCaseVariable" : true,
|
||||
"UseShorthandTypeNames" : true,
|
||||
"UseSingleLinePropertyGetter" : true,
|
||||
"UseSynthesizedInitializer" : true,
|
||||
"UseTripleSlashForDocumentationComments" : true,
|
||||
"UseWhereClausesInForLoops" : false,
|
||||
"ValidateDocumentationComments" : true
|
||||
"ValidateDocumentationComments" : false
|
||||
},
|
||||
"spacesBeforeEndOfLineComments": 2,
|
||||
"spacesAroundRangeFormationOperators" : false,
|
||||
"tabWidth" : 2,
|
||||
"tabWidth" : 8,
|
||||
"version" : 1
|
||||
}
|
||||
+9
-264
@@ -4,226 +4,18 @@
|
||||
Add new items at the end of the relevant section under **Unreleased**.
|
||||
-->
|
||||
|
||||
This project follows semantic versioning.
|
||||
This project follows semantic versioning. While still in major version `0`,
|
||||
source-stability is only guaranteed within minor versions (e.g. between
|
||||
`0.0.3` and `0.0.4`). If you want to guard against potentially source-breaking
|
||||
package updates, you can specify your package dependency using
|
||||
`.upToNextMinor(from: "0.1.0")` as the requirement.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Additions
|
||||
|
||||
- Bidirectional collections have a new `ends(with:)` method that matches
|
||||
the behavior of the standard library's `starts(with:)` method. ([#224])
|
||||
|
||||
<!-- *No new changes.* -->
|
||||
|
||||
## [1.2.1] - 2025-02-10
|
||||
|
||||
### Changes
|
||||
|
||||
- The package now has a minimum Swift version of Swift 5.7. ([#240])
|
||||
- Adds a project for building with Xcode. ([#246])
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fix for Swift 6 language mode errors. ([#230])
|
||||
- Minor improvements to documentation and performance. ([#220], [#222], [#223], [#225], [#227], [#228])
|
||||
|
||||
The 1.2.1 release includes contributions from [b1ackturtle], [CheATSlark], [dabrahams], [glessard], [j-f1], [marcosgriselli], [mrs1669], [natecook1000], [rex4539], and [schlagelk]. Thank you!
|
||||
|
||||
## [1.2.0] - 2023-11-14
|
||||
|
||||
### Additions
|
||||
|
||||
- Sequences have new `grouped(by:)` and `keyed(by:)` methods, which simplify
|
||||
building dictionaries based on sequence elements: ([#197])
|
||||
|
||||
```swift
|
||||
let evensOdds = (1...10).grouped(by: { $0.isMultiple(of: 2) ? "even" : "odd" })
|
||||
// ["even": [2, 4, 6, 8, 10], "odd": [1, 3, 5, 7, 9]]
|
||||
|
||||
let animals = ["Aardvark", "Alpaca", "Armadillo", "Barracuda", "Buffalo", ...]
|
||||
let alphaAnimals = animals.keyed(by: \.first!, resolvingConflictsWith: { _, first, _ in first })
|
||||
// ["A": "Aardvark", "B": "Barracuda", ...]
|
||||
```
|
||||
- The `endOfPrefix(while:)` and `startOfSuffix(while)` methods are now public.
|
||||
These methods were previously implementation details of the `trimming` group
|
||||
of methods. ([#211])
|
||||
|
||||
### Fixes
|
||||
|
||||
- Documentation and performance improvements. ([#202], [#210])
|
||||
|
||||
The 1.2.0 release includes contributions from [amomchilov], [mattyoung], [natecook1000], [stephentyrone], and [ttsugriy].
|
||||
Thank you!
|
||||
*No changes yet.*
|
||||
|
||||
---
|
||||
|
||||
## [1.1.0] - 2023-10-05
|
||||
|
||||
### Additions
|
||||
|
||||
- New nonmutating `partitioned(by:)` methods that return both the failing and passing elements of a sequence or collection in separate arrays. ([#152])
|
||||
|
||||
```swift
|
||||
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
||||
let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
||||
|
||||
print(longNames)
|
||||
// Prints "["Vivien", "Marlon"]"
|
||||
print(shortNames)
|
||||
// Prints "["Kim", "Karl"]"
|
||||
```
|
||||
|
||||
- A new `evenlyChunked(in:)` method that chunks a sequence or collection into the specified number of evenly-sized subsequences. ([#96])
|
||||
|
||||
```swift
|
||||
let numbers = Array(0..<10)
|
||||
for chunk in numbers.evenlyChunked(in: 4) {
|
||||
print(chunk)
|
||||
}
|
||||
// Prints:
|
||||
// [0, 1, 2]
|
||||
// [3, 4, 5]
|
||||
// [6, 7]
|
||||
// [8, 9]
|
||||
```
|
||||
|
||||
### Changes
|
||||
|
||||
- The package now has a minimum Swift version of Swift 5.4.
|
||||
|
||||
### Fixes
|
||||
|
||||
- Improvements to documentation, including a new DocC-based documentation structure.
|
||||
|
||||
The 1.1.0 release includes contributions from [dickoff], [gwynne], [mdznr], [natecook1000], [ole], [stephentyrone], and [timvermeulen].
|
||||
Thank you!
|
||||
|
||||
---
|
||||
|
||||
## [1.0.0] - 2021-09-08
|
||||
|
||||
### Changes
|
||||
|
||||
- Most sequence and collection types have been renamed, following a more
|
||||
consistent naming structure:
|
||||
- The `Lazy` prefix was dropped.
|
||||
- Either a `Sequence` or `Collection` suffix was added depending on whether or
|
||||
not the type is unconditionally a collection.
|
||||
- The base name was derived from the name of the method that produces it,
|
||||
including an argument label to disambiguate if necessary.
|
||||
```
|
||||
Chain2 -> Chain2Sequence
|
||||
ChunkedBy -> ChunkedByCollection
|
||||
ChunkedOn -> ChunkedOnCollection
|
||||
ChunkedByCount -> ChunksOfCountCollection
|
||||
Combinations -> CombinationsSequence
|
||||
Cycle -> CycledSequence
|
||||
FiniteCycle -> CycledTimesCollection
|
||||
Indexed -> IndexedCollection
|
||||
Intersperse -> InterspersedSequence
|
||||
LazySplitSequence -> SplitSequence
|
||||
LazySplitCollection -> SplitCollection
|
||||
Permutations -> PermutationsSequence
|
||||
UniquePermutations -> UniquePermutationsSequence
|
||||
Product2 -> Product2Sequence
|
||||
ExclusiveReductions -> ExclusiveReductionsSequence
|
||||
InclusiveReductions -> InclusiveReductionsSequence
|
||||
StrideSequence -> StridingSequence
|
||||
StrideCollection -> StridingCollection
|
||||
Uniqued -> UniquedSequence
|
||||
Windows -> WindowsOfCountCollection
|
||||
```
|
||||
- Types that can only be produced from a lazy sequence chain now unconditionally
|
||||
conform to `LazySequenceProtocol` and wrap the base sequence instead of the
|
||||
lazy wrapper, making some return types slightly simpler.
|
||||
- e.g. `[1, 2, 3].lazy.reductions(+)` now returns
|
||||
`ExclusiveReductionsSequence<[Int]>`, not
|
||||
`ExclusiveReductionsSequence<LazySequence<[Int]>>`.
|
||||
- This concerns `JoinedByClosureSequence`, `JoinedByClosureCollection`,
|
||||
`ExclusiveReductionsSequence`, `InclusiveReductionsSequence`.
|
||||
- The generic parameters of the `ExclusiveReductions` type have been swapped,
|
||||
putting the base collection first and the result type second.
|
||||
- The `Indices` associated type of `IndexedCollection` now matches
|
||||
`Base.Indices`.
|
||||
|
||||
### Removals
|
||||
|
||||
- Previously deprecated type and method names have been removed:
|
||||
- The `Chain` type alias for `Chain2Sequence`
|
||||
- The `chained(with:)` method which was replaced with the `chain(_:_:)` free
|
||||
function
|
||||
- The `LazyChunked` and `Chunked` type aliases for `ChunkedByCollection`
|
||||
- The `rotate(subrange:at:)` and `rotate(at:)` methods which were renamed to
|
||||
`rotate(subrange:toStartAt:)` and `rotate(toStartAt:)` respectively
|
||||
|
||||
### Fixes
|
||||
|
||||
- The `StridingSequence` and `StridingCollection` types now conditionally
|
||||
conform to `LazySequenceProtocol`, allowing the `striding(by:)` method to
|
||||
properly propagate laziness in a lazy sequence chain.
|
||||
- Fixed `chunked(by:)` to always compare two consecutive elements rather than
|
||||
each element with the first element of the current chunk. ([#162])
|
||||
|
||||
The 1.0.0 release includes contributions from [iainsmith], [mdznr], and
|
||||
[timvermeulen]. Thank you!
|
||||
|
||||
## [0.2.1] - 2021-06-01
|
||||
|
||||
### Additions
|
||||
|
||||
Expanded versatility for two existing operations:
|
||||
|
||||
- A series of `joined(by:)` overloads concatenate a sequence of sequences using
|
||||
an element or a collection, either passed in or generated from consecutive
|
||||
elements via a closure. ([#138])
|
||||
- Additional `trimming(while:)` methods for trimming only the start or end of a
|
||||
collection, as well as mutating versions of all three variants. ([#104])
|
||||
|
||||
The 0.2.1 release includes contributions from [fedeci] and [timvermeulen].
|
||||
Thank you!
|
||||
|
||||
## [0.2.0] - 2021-05-17
|
||||
|
||||
### Additions
|
||||
|
||||
Two new additions to the list of algorithms:
|
||||
|
||||
- `adjacentPairs()` lazily iterates over tuples of adjacent elements of a
|
||||
sequence. ([#119])
|
||||
- `minAndMax()` finds both the smallest and largest elements of a sequence in
|
||||
a single pass. ([#90])
|
||||
|
||||
### Changes
|
||||
|
||||
- When calling `chunked(on:)`, the resulting collection has an element type of
|
||||
`(Subject, SubSequence)` instead of just `SubSequence`, making the subject
|
||||
value available when iterating.
|
||||
|
||||
```swift
|
||||
let numbers = [5, 6, -3, -9, -11, 2, 7, 6]
|
||||
for (signum, values) in numbers.chunked(on: { $0.signum() }) {
|
||||
print(signum, values)
|
||||
}
|
||||
// 1 [5, 6]
|
||||
// -1 [-3, -9, -11]
|
||||
// 1 [2, 7, 6]
|
||||
```
|
||||
|
||||
### Fixes
|
||||
|
||||
- Improvements to the documentation and PR templates.
|
||||
|
||||
The 0.2.0 release includes contributions from [CTMacUser], [LemonSpike],
|
||||
[mpangburn], and [natecook1000]. Thank you!
|
||||
|
||||
---
|
||||
|
||||
## [0.1.1] - 2021-04-14
|
||||
|
||||
### Fixes
|
||||
|
||||
- `Product2` associated type inference error in release build ([#130])
|
||||
|
||||
## [0.1.0] - 2021-04-13
|
||||
|
||||
### Additions
|
||||
@@ -241,7 +33,7 @@ The 0.2.0 release includes contributions from [CTMacUser], [LemonSpike],
|
||||
- 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 currency type
|
||||
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.
|
||||
|
||||
@@ -335,7 +127,7 @@ The 0.0.3 release includes contributions from [benrimmington], [danielctull],
|
||||
### Fixes
|
||||
|
||||
- `Algorithms` now builds under SwiftPM on Windows.
|
||||
- A wide variety of errors, misspellings, and omissions in the documentation
|
||||
- A wide variety of errors, misspellings, and ommissions in the documentation
|
||||
and guides have been fixed.
|
||||
- Index/distance calculations for the `Product2` and `Chain` types have been
|
||||
corrected.
|
||||
@@ -357,14 +149,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
|
||||
<!-- Link references for releases -->
|
||||
|
||||
[Unreleased]: https://github.com/apple/swift-algorithms/compare/1.2.1...HEAD
|
||||
[1.2.0]: https://github.com/apple/swift-algorithms/compare/1.2.0...1.2.1
|
||||
[1.2.0]: https://github.com/apple/swift-algorithms/compare/1.1.0...1.2.0
|
||||
[1.1.0]: https://github.com/apple/swift-algorithms/compare/1.0.0...1.1.0
|
||||
[1.0.0]: https://github.com/apple/swift-algorithms/compare/0.2.1...1.0.0
|
||||
[0.2.1]: https://github.com/apple/swift-algorithms/compare/0.2.0...0.2.1
|
||||
[0.2.0]: https://github.com/apple/swift-algorithms/compare/0.1.1...0.2.0
|
||||
[0.1.1]: https://github.com/apple/swift-algorithms/compare/0.1.0...0.1.1
|
||||
[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
|
||||
@@ -388,75 +173,36 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
[#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
|
||||
[#90]: https://github.com/apple/swift-algorithms/pull/90
|
||||
[#91]: https://github.com/apple/swift-algorithms/pull/91
|
||||
[#96]: https://github.com/apple/swift-algorithms/pull/96
|
||||
[#104]: https://github.com/apple/swift-algorithms/pull/104
|
||||
[#106]: https://github.com/apple/swift-algorithms/pull/106
|
||||
[#112]: https://github.com/apple/swift-algorithms/pull/112
|
||||
[#119]: https://github.com/apple/swift-algorithms/pull/119
|
||||
[#124]: https://github.com/apple/swift-algorithms/pull/124
|
||||
[#125]: https://github.com/apple/swift-algorithms/pull/125
|
||||
[#130]: https://github.com/apple/swift-algorithms/pull/130
|
||||
[#138]: https://github.com/apple/swift-algorithms/pull/138
|
||||
[#152]: https://github.com/apple/swift-algorithms/pull/152
|
||||
[#162]: https://github.com/apple/swift-algorithms/pull/162
|
||||
[#197]: https://github.com/apple/swift-algorithms/pull/197
|
||||
[#202]: https://github.com/apple/swift-algorithms/pull/202
|
||||
[#210]: https://github.com/apple/swift-algorithms/pull/210
|
||||
[#211]: https://github.com/apple/swift-algorithms/pull/211
|
||||
[#224]: https://github.com/apple/swift-algorithms/pull/224
|
||||
[#220]: https://github.com/apple/swift-algorithms/pull/220
|
||||
[#222]: https://github.com/apple/swift-algorithms/pull/222
|
||||
[#223]: https://github.com/apple/swift-algorithms/pull/223
|
||||
[#225]: https://github.com/apple/swift-algorithms/pull/225
|
||||
[#227]: https://github.com/apple/swift-algorithms/pull/227
|
||||
[#228]: https://github.com/apple/swift-algorithms/pull/228
|
||||
[#230]: https://github.com/apple/swift-algorithms/pull/230
|
||||
[#240]: https://github.com/apple/swift-algorithms/pull/240
|
||||
[#246]: https://github.com/apple/swift-algorithms/pull/246
|
||||
|
||||
<!-- Link references for contributors -->
|
||||
|
||||
[amomchilov]: https://github.com/apple/swift-algorithms/commits?author=amomchilov
|
||||
[AustinConlon]: https://github.com/apple/swift-algorithms/commits?author=AustinConlon
|
||||
[b1ackturtle]: https://github.com/apple/swift-algorithms/commits?author=b1ackturtle
|
||||
[benrimmington]: https://github.com/apple/swift-algorithms/commits?author=benrimmington
|
||||
[bjhomer]: https://github.com/apple/swift-algorithms/commits?author=bjhomer
|
||||
[CheATSlark]: https://github.com/apple/swift-algorithms/commits?author=CheATSlark
|
||||
[CTMacUser]: https://github.com/apple/swift-algorithms/commits?author=CTMacUser
|
||||
[dabrahams]: https://github.com/apple/swift-algorithms/commits?author=dabrahams
|
||||
[danielctull]: https://github.com/apple/swift-algorithms/commits?author=danielctull
|
||||
[dhruvshah8]: https://github.com/apple/swift-algorithms/commits?author=dhruvshah8
|
||||
[dickoff]: https://github.com/apple/swift-algorithms/commits?author=dickoff
|
||||
[egorzhdan]: https://github.com/apple/swift-algorithms/commits?author=egorzhdan
|
||||
[fedeci]: https://github.com/apple/swift-algorithms/commits?author=fedeci
|
||||
[glessard]: https://github.com/apple/swift-algorithms/commits?author=glessard
|
||||
[gwynne]: https://github.com/apple/swift-algorithms/commits?author=gwynne
|
||||
[hashemi]: https://github.com/apple/swift-algorithms/commits?author=hashemi
|
||||
[iainsmith]: https://github.com/apple/swift-algorithms/commits?author=iainsmith
|
||||
[IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen
|
||||
[iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7
|
||||
[j-f1]: https://github.com/apple/swift-algorithms/commits?author=j-f1
|
||||
[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
|
||||
[marcosgriselli]: https://github.com/apple/swift-algorithms/commits?author=marcosgriselli
|
||||
[markuswntr]: https://github.com/apple/swift-algorithms/commits?author=markuswntr
|
||||
[mattyoung]: https://github.com/apple/swift-algorithms/commits?author=mattyoung
|
||||
[mdznr]: https://github.com/apple/swift-algorithms/commits?author=mdznr
|
||||
[michiboo]: https://github.com/apple/swift-algorithms/commits?author=michiboo
|
||||
[mpangburn]: https://github.com/apple/swift-algorithms/commits?author=mpangburn
|
||||
[mrs1669]: https://github.com/apple/swift-algorithms/commits?author=mrs1669
|
||||
[natecook1000]: https://github.com/apple/swift-algorithms/commits?author=natecook1000
|
||||
[nordicio]: https://github.com/apple/swift-algorithms/commits?author=nordicio
|
||||
[ole]: https://github.com/apple/swift-algorithms/commits?author=ole
|
||||
[ollieatkinson]: https://github.com/apple/swift-algorithms/commits?author=ollieatkinson
|
||||
[pmtao]: https://github.com/apple/swift-algorithms/commits?author=pmtao
|
||||
[Qata]: https://github.com/apple/swift-algorithms/commits?author=Qata
|
||||
[rakaramos]: https://github.com/apple/swift-algorithms/commits?author=rakaramos
|
||||
[rex4539]: https://github.com/apple/swift-algorithms/commits?author=rex4539
|
||||
[rockbruno]: https://github.com/apple/swift-algorithms/commits?author=rockbruno
|
||||
[Roshankumar350]: https://github.com/apple/swift-algorithms/commits?author=Roshankumar350
|
||||
[schlagelk]: https://github.com/apple/swift-algorithms/commits?author=schlagelk
|
||||
@@ -464,4 +210,3 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
[stephentyrone]: https://github.com/apple/swift-algorithms/commits?author=stephentyrone
|
||||
[timvermeulen]: https://github.com/apple/swift-algorithms/commits?author=timvermeulen
|
||||
[toddthomas]: https://github.com/apple/swift-algorithms/commits?author=toddthomas
|
||||
[ttsugriy]: https://github.com/apple/swift-algorithms/commits?author=ttsugriy
|
||||
@@ -1,60 +0,0 @@
|
||||
# AdjacentPairs
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/AdjacentPairs.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/AdjacentPairsTests.swift)]
|
||||
|
||||
Lazily iterates over tuples of adjacent elements.
|
||||
|
||||
```swift
|
||||
let numbers = (1...5)
|
||||
let pairs = numbers.adjacentPairs()
|
||||
// Array(pairs) == [(1, 2), (2, 3), (3, 4), (4, 5)]
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `adjacentPairs()` method is declared as a `Sequence` extension returning
|
||||
`AdjacentPairsSequence` and as a `Collection` extension returning
|
||||
`AdjacentPairsCollection`.
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func adjacentPairs() -> AdjacentPairsSequence<Self>
|
||||
}
|
||||
```
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
public func adjacentPairs() -> AdjacentPairsCollection<Self>
|
||||
}
|
||||
```
|
||||
|
||||
The `AdjacentPairsSequence` type is a sequence, and the
|
||||
`AdjacentPairsCollection` type is a collection with conditional conformance to
|
||||
`BidirectionalCollection` and `RandomAccessCollection` when the underlying
|
||||
collection conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling `adjacentPairs` is an O(1) operation.
|
||||
|
||||
### Naming
|
||||
|
||||
This method is named for clarity while remaining agnostic to any particular
|
||||
domain of programming. In natural language processing, this operation is akin to
|
||||
computing a list of bigrams; however, this algorithm is not specific to this use
|
||||
case.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
This function is often written as a `zip` of a sequence together with itself,
|
||||
minus its first element.
|
||||
|
||||
**Haskell:** This operation is spelled ``s `zip` tail s``.
|
||||
|
||||
**Python:** Python users may write `zip(s, s[1:])` for a list with at least one
|
||||
element. For natural language processing, the `nltk` package offers a `bigrams`
|
||||
function akin to this method.
|
||||
|
||||
Note that in Swift, the spelling `zip(s, s.dropFirst())` is undefined behavior
|
||||
for a single-pass sequence `s`.
|
||||
+4
-4
@@ -25,13 +25,13 @@ the shared conformances of the two underlying types.
|
||||
The `chain(_:_:)` function takes two sequences as arguments:
|
||||
|
||||
```swift
|
||||
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2Sequence<S1, S2>
|
||||
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2<S1, S2>
|
||||
where S1.Element == S2.Element
|
||||
```
|
||||
|
||||
The resulting `Chain2Sequence` type is a sequence, with conditional conformance
|
||||
to `Collection`, `BidirectionalCollection`, and `RandomAccessCollection` when
|
||||
both the first and second arguments conform.
|
||||
The resulting `Chain2` type is a sequence, with conditional conformance to
|
||||
`Collection`, `BidirectionalCollection`, and `RandomAccessCollection` when both
|
||||
the first and second arguments conform.
|
||||
|
||||
### Naming
|
||||
|
||||
|
||||
+37
-69
@@ -3,16 +3,16 @@
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Chunked.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ChunkedTests.swift)]
|
||||
|
||||
Break a collection into nonoverlapping subsequences:
|
||||
Break a collection into subsequences where consecutive elements pass a binary
|
||||
predicate, or where all elements in each chunk project to the same value.
|
||||
|
||||
* `chunked(by:)` forms chunks of consecutive elements that pass a binary predicate,
|
||||
* `chunked(on:)` forms chunks of consecutive elements that project to equal values,
|
||||
* `chunks(ofCount:)` forms chunks of a given size, and
|
||||
* `evenlyChunked(in:)` forms a given number of equally-sized chunks.
|
||||
Also, includes a `chunks(ofCount:)` that breaks a collection into subsequences
|
||||
of a given `count`.
|
||||
|
||||
`chunked(by:)` uses a binary predicate to test consecutive elements, separating
|
||||
chunks where the predicate returns `false`. For example, you can chunk a
|
||||
collection into ascending sequences using this method:
|
||||
There are two variations of the `chunked` method: `chunked(by:)` and
|
||||
`chunked(on:)`. `chunked(by:)` uses a binary predicate to test consecutive
|
||||
elements, separating chunks where the predicate returns `false`. For example,
|
||||
you can chunk a collection into ascending sequences using this method:
|
||||
|
||||
```swift
|
||||
let numbers = [10, 20, 30, 10, 40, 40, 10, 20]
|
||||
@@ -20,21 +20,20 @@ let chunks = numbers.chunked(by: { $0 <= $1 })
|
||||
// [[10, 20, 30], [10, 40, 40], [10, 20]]
|
||||
```
|
||||
|
||||
The `chunked(on:)` method, by contrast, takes a projection of each element and
|
||||
The `chunk(on:)` method, by contrast, takes a projection of each element and
|
||||
separates chunks where the projection of two consecutive elements is not equal.
|
||||
The result includes both the projected value and the subsequence that groups
|
||||
elements with that projected value:
|
||||
|
||||
```swift
|
||||
let names = ["David", "Kyle", "Karoy", "Nate"]
|
||||
let chunks = names.chunked(on: \.first!)
|
||||
// [("D", ["David"]), ("K", ["Kyle", "Karoy"]), ("N", ["Nate"])]
|
||||
// [["David"], ["Kyle", "Karoy"], ["Nate"]]
|
||||
```
|
||||
|
||||
The `chunks(ofCount:)` method takes a `count` parameter (required to be > 0) and
|
||||
separates the collection into chunks of this given count. If the length of the
|
||||
collection is a multiple of the `count` parameter, all chunks will have the
|
||||
a count equal to the parameter. Otherwise, the last chunk will contain the remaining elements.
|
||||
The `chunks(ofCount:)` takes a `count` parameter (required to be > 0) and separates
|
||||
the collection into `n` chunks of this given count. If the `count` parameter is
|
||||
evenly divided by the count of the base `Collection` all the chunks will have
|
||||
the count equals to the parameter. Otherwise, the last chunk will contain the
|
||||
remaining elements.
|
||||
|
||||
```swift
|
||||
let names = ["David", "Kyle", "Karoy", "Nate"]
|
||||
@@ -45,39 +44,23 @@ let remaining = names.chunks(ofCount: 3)
|
||||
// equivalent to [["David", "Kyle", "Karoy"], ["Nate"]]
|
||||
```
|
||||
|
||||
The `chunks(ofCount:)` method was previously [proposed](proposal) for inclusion
|
||||
in the standard library.
|
||||
|
||||
The `evenlyChunked(in:)` method takes a `count` parameter and divides the
|
||||
collection into `count` number of equally-sized chunks. If the length of the
|
||||
collection is not a multiple of the `count` parameter, the chunks at the start
|
||||
will be longer than the chunks at the end.
|
||||
|
||||
```swift
|
||||
let evenChunks = (0..<15).evenlyChunked(in: 3)
|
||||
// equivalent to [0..<5, 5..<10, 10..<15]
|
||||
|
||||
let nearlyEvenChunks = (0..<15).evenlyChunked(in: 4)
|
||||
// equivalent to [0..<4, 4..<8, 8..<12, 12..<15]
|
||||
```
|
||||
|
||||
When "chunking" a collection, the entire collection is included in the result,
|
||||
unlike the `split` family of methods, where separators are dropped.
|
||||
Joining the result of a chunking method call results in a collection equivalent
|
||||
to the original.
|
||||
The `chunks(ofCount:)` is the method of the [existing SE proposal][proposal].
|
||||
Unlike the `split` family of methods, the entire collection is included in the
|
||||
chunked result — joining the resulting chunks recreates the original collection.
|
||||
|
||||
```swift
|
||||
c.elementsEqual(c.chunked(...).joined())
|
||||
// true
|
||||
```
|
||||
|
||||
Check the [proposal][proposal] detailed design section for more info.
|
||||
|
||||
[proposal]: https://github.com/apple/swift-evolution/pull/935
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The four methods are added to `Collection`, with matching versions of
|
||||
`chunked(by:)` and `chunked(on:)` that return a lazy wrapper added to
|
||||
`LazyCollectionProtocol`.
|
||||
The two methods are added as extension to `Collection`, with two matching
|
||||
versions that return a lazy wrapper added to `LazyCollectionProtocol`.
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
@@ -86,56 +69,41 @@ extension Collection {
|
||||
) -> [SubSequence]
|
||||
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: (Element) -> Subject
|
||||
on projection: (Element) -> Subject
|
||||
) -> [SubSequence]
|
||||
|
||||
public func chunks(ofCount count: Int) -> ChunkedByCount<Self>
|
||||
|
||||
public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection<Self>
|
||||
}
|
||||
}
|
||||
|
||||
extension LazyCollectionProtocol {
|
||||
extension LazyCollectionProtocol {
|
||||
public func chunked(
|
||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||
) -> ChunkedByCollection<Elements>
|
||||
) -> Chunked<Elements>
|
||||
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: @escaping (Element) -> Subject
|
||||
) -> ChunkedOnCollection<Elements, Subject>
|
||||
) -> Chunked<Elements>
|
||||
}
|
||||
```
|
||||
|
||||
Each of the "chunked" collection types are bidirectional when the wrapped
|
||||
collection is bidirectional. `ChunksOfCountCollection` and
|
||||
`EvenlyChunkedCollection` also conform to `RandomAccessCollection` and
|
||||
`LazySequenceProtocol` when their base collections conform.
|
||||
The `Chunked` type is bidirectional when the wrapped collection is
|
||||
bidirectional.
|
||||
|
||||
### Complexity
|
||||
|
||||
The eager methods are O(_n_) where _n_ is the number of elements in the
|
||||
collection. The lazy methods are O(_n_) because the start index is pre-computed.
|
||||
The eager methods are O(_n_), the lazy methods are O(_1_).
|
||||
|
||||
### Naming
|
||||
|
||||
The operation performed by these methods is similar to other ways of breaking a
|
||||
collection up into subsequences. In particular, the predicate-based
|
||||
`split(where:)` method looks similar to `chunked(on:)`. You can draw a
|
||||
distinction between these different operations based on the resulting
|
||||
subsequences:
|
||||
The operation performed by these methods is similar to other ways of breaking a collection up into subsequences. In particular, the predicate-based `split(where:)` method looks similar to `chunked(on:)`. You can draw a distinction between these different operations based on the resulting subsequences:
|
||||
|
||||
- `split`: *In the standard library.* Breaks a collection into subsequences, removing any elements that are considered "separators". The original collection cannot be recovered from the result of splitting.
|
||||
- `chunked`: *In this package.* Breaks a collection into subsequences, preserving each element in its initial ordering. Joining the resulting subsequences re-forms the original collection.
|
||||
- `sliced`: *Not included in this package or the stdlib.* Breaks a collection into potentially overlapping subsequences.
|
||||
|
||||
- `split`: *In the standard library.* Breaks a collection into subsequences,
|
||||
removing any elements that are considered "separators". The original collection
|
||||
cannot be recovered from the result of splitting.
|
||||
- `chunked`: *In this package.* Breaks a collection into subsequences,
|
||||
preserving each element in its initial ordering. Joining the resulting
|
||||
subsequences re-forms the original collection.
|
||||
- `sliced`: *Not included in this package or the stdlib.* Breaks a collection
|
||||
into potentially overlapping subsequences.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
**Ruby:** Ruby’s `Enumerable` class defines `chunk_while` and `chunk`, which map
|
||||
to the proposed `chunked(by:)` and `chunked(on:)` methods.
|
||||
|
||||
**Rust:** Rust defines a variety of size-based `chunks` methods, of which the
|
||||
standard version corresponds to the `chunks(ofCount:)` method defined here.
|
||||
**Rust:** Rust defines a variety of size-based `chunks` methods, but doesn’t
|
||||
include any with the functionality described here.
|
||||
+11
-12
@@ -60,33 +60,32 @@ for combo in numbers.combinations(ofCount: 2...3) {
|
||||
## Detailed Design
|
||||
|
||||
The `combinations(ofCount:)` method is declared as a `Collection` extension,
|
||||
and returns a `CombinationsSequence` type:
|
||||
and returns a `Combinations` type:
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
public func combinations(ofCount k: Int) -> CombinationsSequence<Self>
|
||||
public func combinations(ofCount k: Int) -> Combinations<Self>
|
||||
}
|
||||
```
|
||||
|
||||
Since the `CombinationsSequence` type needs to store an array of the
|
||||
collection’s indices and mutate the array to generate each permutation,
|
||||
`CombinationsSequence` only has `Sequence` conformance. Adding `Collection`
|
||||
conformance would require storing the array in the index type, which would in
|
||||
turn lead to copying the array at every index advancement.
|
||||
`CombinationsSequence` does conform to `LazySequenceProtocol` when the base type
|
||||
conforms.
|
||||
Since the `Combinations` type needs to store an array of the collection’s
|
||||
indices and mutate the array to generate each permutation, `Combinations` only
|
||||
has `Sequence` conformance. Adding `Collection` conformance would require
|
||||
storing the array in the index type, which would in turn lead to copying the
|
||||
array at every index advancement. `Combinations` does conform to
|
||||
`LazySequenceProtocol` when the base type conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling `combinations(ofCount:)` accesses the count of the collection, so it’s
|
||||
an O(1) operation for random-access collections, or an O(_n_) operation
|
||||
otherwise. Creating the iterator for a `CombinationsSequence` instance and each
|
||||
call to `CombinationsSequence.Iterator.next()` is an O(_n_) operation.
|
||||
otherwise. Creating the iterator for a `Combinations` instance and each call to
|
||||
`Combinations.Iterator.next()` is an O(_n_) operation.
|
||||
|
||||
### Naming
|
||||
|
||||
The parameter label in `combination(ofCount:)` is the best match for the
|
||||
[Swift's API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/). A few other options were considered:
|
||||
Swift API guidelines. A few other options were considered:
|
||||
|
||||
- When the standard library uses `of` as a label, the parameter is generally
|
||||
the object of the operation, as in `type(of:)` and `firstIndex(of:)`, and
|
||||
|
||||
+2
-3
@@ -37,9 +37,8 @@ extension Collection {
|
||||
|
||||
The `Sequence` version of `compacted()` returns a `CompactedSequence` type,
|
||||
while the `Collection` version returns `CompactedCollection`. The collection
|
||||
has conditional conformance to `BidirectionalCollection` when the base
|
||||
collection conforms, and both have conditional conformance to
|
||||
`LazySequenceProtocol` when the base collection conforms.
|
||||
has conditional conformance to `BidirectionalCollection` and
|
||||
`LazyCollectionProtocol` when the base collection conforms.
|
||||
|
||||
### Naming
|
||||
|
||||
|
||||
+9
-9
@@ -26,20 +26,20 @@ Two new methods are added to collections:
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
func cycled() -> CycledSequence<Self>
|
||||
func cycled() -> Cycle<Self>
|
||||
|
||||
func cycled(times: Int) -> CycledTimesCollection<Self>
|
||||
func cycled(times: Int) -> FiniteCycle<Self>
|
||||
}
|
||||
```
|
||||
|
||||
The new `CycledSequence` type is a sequence only, given that the `Collection`
|
||||
protocol design makes infinitely large types impossible/impractical.
|
||||
`CycledSequence` also conforms to `LazySequenceProtocol` when the base type
|
||||
conforms.
|
||||
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.
|
||||
|
||||
The `CycledTimesCollection` type always has `Collection` conformance, with
|
||||
`BidirectionalCollection`, `RandomAccessCollection`, and `LazySequenceProtocol`
|
||||
conformance when the base type conforms.
|
||||
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
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
# EndsWith
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/EndsWith.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/EndsWithTests.swift)]
|
||||
|
||||
This function checks whether the final elements of the one collection are the same as the elements in another collection.
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `ends(with:)` and `ends(with:by:)` functions are added as methods on an extension of
|
||||
`BidirectionalCollection`.
|
||||
|
||||
```swift
|
||||
extension BidirectionalCollection {
|
||||
public func ends<PossibleSuffix: BidirectionalCollection>(
|
||||
with possibleSuffix: PossibleSuffix
|
||||
) -> Bool where PossibleSuffix.Element == Element
|
||||
|
||||
public func ends<PossibleSuffix: BidirectionalCollection>(
|
||||
with possibleSuffix: PossibleSuffix,
|
||||
by areEquivalent: (Element, PossibleSuffix.Element) throws -> Bool
|
||||
) rethrows -> Bool
|
||||
}
|
||||
```
|
||||
|
||||
This method requires `BidirectionalCollection` for being able to traverse back from the end of the collection. It also requires the `possibleSuffix` to be `BidirectionalCollection`, because it too needs to be traverse backwards, to compare its elements against `self` from back to front.
|
||||
|
||||
### Complexity
|
||||
|
||||
O(*m*), where *m* is the lesser of the length of the collection and the length of `possibleSuffix`.
|
||||
|
||||
### Naming
|
||||
|
||||
The function's name resembles that of an existing Swift function
|
||||
`starts(with:)`, which performs same operation however in the forward direction
|
||||
of the collection.
|
||||
@@ -1,68 +0,0 @@
|
||||
# Grouped
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Grouped.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/GroupedTests.swift)]
|
||||
|
||||
Groups up elements of a sequence into a new Dictionary, whose values are Arrays of grouped elements, each keyed by the result of the given closure.
|
||||
|
||||
```swift
|
||||
let fruits = ["Apricot", "Banana", "Apple", "Cherry", "Avocado", "Coconut"]
|
||||
let fruitsByLetter = fruits.grouped(by: { $0.first! })
|
||||
// Results in:
|
||||
// [
|
||||
// "B": ["Banana"],
|
||||
// "A": ["Apricot", "Apple", "Avocado"],
|
||||
// "C": ["Cherry", "Coconut"],
|
||||
// ]
|
||||
```
|
||||
|
||||
If you wish to achieve a similar effect but for single values (instead of Arrays of grouped values), see [`keyed(by:)`](Keyed.md).
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `grouped(by:)` method is declared as a `Sequence` extension returning
|
||||
`[GroupKey: [Element]]`.
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func grouped<GroupKey>(
|
||||
by keyForValue: (Element) throws -> GroupKey
|
||||
) rethrows -> [GroupKey: [Element]]
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling `grouped(by:)` is an O(_n_) operation.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
| Language | Grouping API |
|
||||
|---------------|--------------|
|
||||
| Java | [`groupingBy`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/stream/Collectors.html#groupingBy(java.util.function.Function)) |
|
||||
| Kotlin | [`groupBy`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/group-by.html) |
|
||||
| C# | [`GroupBy`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupby?view=net-7.0#system-linq-enumerable-groupby) |
|
||||
| Rust | [`group_by`](https://doc.rust-lang.org/std/primitive.slice.html#method.group_by) |
|
||||
| Ruby | [`group_by`](https://ruby-doc.org/3.2.2/Enumerable.html#method-i-group_by) |
|
||||
| Python | [`groupby`](https://docs.python.org/3/library/itertools.html#itertools.groupby) |
|
||||
| PHP (Laravel) | [`groupBy`](https://laravel.com/docs/10.x/collections#method-groupby) |
|
||||
|
||||
#### Naming
|
||||
|
||||
All the surveyed languages name this operation with a variant of "grouped" or "grouping". The past tense `grouped(by:)` best fits [Swift's API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/).
|
||||
|
||||
#### Customization points
|
||||
|
||||
Java and C# are interesting in that they provide multiple overloads with several points of customization:
|
||||
|
||||
1. Changing the type of the groups.
|
||||
1. E.g. the groups can be Sets instead of Arrays.
|
||||
1. Akin to calling `.transformValues { group in Set(group) }` on the resultant dictionary, but avoiding the intermediate allocation of Arrays of each group.
|
||||
2. Picking which elements end up in the groupings.
|
||||
1. The default is the elements of the input sequence, but can be changed.
|
||||
2. Akin to calling `.transformValues { group in group.map(someTransform) }` on the resultant dictionary, but avoiding the intermediate allocation of Arrays of each group.
|
||||
3. Changing the type of the outermost collection.
|
||||
1. E.g using an `OrderedDictionary`, `SortedDictionary` or `TreeDictionary` instead of the default (hashed, unordered) `Dictionary`.
|
||||
2. There's no great way to achieve this with the `grouped(by:)`. One could wrap the resultant dictionary in an initializer to one of the other dictionary types, but that isn't sufficient: Once the `Dictionary` loses the ordering, there's no way to get it back when constructing one of the ordered dictionary variants.
|
||||
|
||||
It is not clear which of these points of customization are worth supporting, or what the best way to express them might be.
|
||||
+5
-5
@@ -21,15 +21,15 @@ for (i, n) in numbers.indexed() {
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `indexed` method returns an `IndexedCollection` type:
|
||||
The `indexed` method returns an `Indexed` type:
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
func indexed() -> IndexedCollection<Self>
|
||||
func indexed() -> Indexed<Self>
|
||||
}
|
||||
```
|
||||
|
||||
`IndexedCollection` scales from a collection up to a random-access collection,
|
||||
depending on its base type. `Indexed` also conforms to `LazySequenceProtocol`
|
||||
when the base type conforms.
|
||||
`Indexed` scales from a collection up to a random-access collection, depending on
|
||||
its base type. `Indexed` also conforms to `LazySequenceProtocol` and
|
||||
`LazyCollectionProtocol` when the base type conforms.
|
||||
|
||||
@@ -25,14 +25,14 @@ A new method is added to sequence:
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
func interspersed(with separator: Element) -> InterspersedSequence<Self>
|
||||
func interspersed(with separator: Element) -> Intersperse<Self>
|
||||
}
|
||||
```
|
||||
|
||||
The new `InterspersedSequence` type represents the sequence when the separator
|
||||
is inserted between each element. `InterspersedSequence` conforms to
|
||||
`Collection`, `BidirectionalCollection`, `RandomAccessCollection` and
|
||||
`LazySequenceProtocol` when the base sequence conforms to those respective
|
||||
The new `Intersperse` type represents the sequence when the separator is
|
||||
inserted between each element. `Intersperse` conforms to `Collection`,
|
||||
`BidirectionalCollection`, `RandomAccessCollection`, `LazySequenceProtocol` and
|
||||
`LazyCollectionProtocol` when the base sequence conforms to those respective
|
||||
protocols.
|
||||
|
||||
### Complexity
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
# Joined
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Joined.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/JoinedTests.swift)]
|
||||
|
||||
Concatenate a sequence of sequences, inserting a separator between each element.
|
||||
|
||||
The separator can be either a single element or a sequence of elements, and it
|
||||
can optionally depend on the sequences right before and after it by returning it
|
||||
from a closure:
|
||||
|
||||
```swift
|
||||
for number in [[1], [2, 3], [4, 5, 6]].joined(by: 100) {
|
||||
print(number)
|
||||
}
|
||||
// 1, 100, 2, 3, 100, 4, 5, 6
|
||||
|
||||
for number in [[10], [20, 30], [40, 50, 60]].joined(by: { [$0.count, $1.count] }) {
|
||||
print(number)
|
||||
}
|
||||
// 10, 1, 2, 20, 30, 2, 3, 40, 50, 60
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The versions that take a closure are executed eagerly and are defined on
|
||||
`Sequence`:
|
||||
|
||||
```swift
|
||||
extension Sequence where Element: Sequence {
|
||||
public func joined(
|
||||
by separator: (Element, Element) throws -> Element.Element
|
||||
) rethrows -> [Element.Element]
|
||||
|
||||
public func joined<Separator>(
|
||||
by separator: (Element, Element) throws -> Separator
|
||||
) rethrows -> [Element.Element]
|
||||
where Separator: Sequence, Separator.Element == Element.Element
|
||||
}
|
||||
```
|
||||
|
||||
The versions that do not take a closure are defined on both `Sequence` and
|
||||
`Collection` because the resulting collections need to precompute their start
|
||||
index to ensure O(1) access:
|
||||
|
||||
```swift
|
||||
extension Sequence where Element: Sequence {
|
||||
public func joined(by separator: Element.Element)
|
||||
-> JoinedBySequence<Self, CollectionOfOne<Element.Element>>
|
||||
|
||||
public func joined<Separator>(
|
||||
by separator: Separator
|
||||
) -> JoinedBySequence<Self, Separator>
|
||||
where Separator: Collection, Separator.Element == Element.Element
|
||||
}
|
||||
|
||||
extension Collection where Element: Sequence {
|
||||
public func joined(by separator: Element.Element)
|
||||
-> JoinedByCollection<Self, CollectionOfOne<Element.Element>>
|
||||
|
||||
public func joined<Separator>(
|
||||
by separator: Separator
|
||||
) -> JoinedByCollection<Self, Separator>
|
||||
where Separator: Collection, Separator.Element == Element.Element
|
||||
}
|
||||
```
|
||||
|
||||
Note that the sequence separator of the closure-less version defined on
|
||||
`Sequence` is required to be a `Collection`, because a plain `Sequence` cannot in
|
||||
general be iterated over multiple times.
|
||||
|
||||
The closure-based versions also have lazy variants that are defined on both
|
||||
lazy sequences and collections for the same reason as explained above:
|
||||
|
||||
```swift
|
||||
extension LazySequenceProtocol where Element: Sequence {
|
||||
public func joined(
|
||||
by separator: @escaping (Element, Element) -> Element.Element
|
||||
) -> JoinedByClosureSequence<Self, CollectionOfOne<Element.Element>>
|
||||
|
||||
public func joined<Separator>(
|
||||
by separator: @escaping (Element, Element) -> Separator
|
||||
) -> JoinedByClosureSequence<Self, Separator>
|
||||
}
|
||||
|
||||
extension LazySequenceProtocol where Self: Collection, Element: Collection {
|
||||
public func joined(
|
||||
by separator: @escaping (Element, Element) -> Element.Element
|
||||
) -> JoinedByClosureCollection<Self, CollectionOfOne<Element.Element>>
|
||||
|
||||
public func joined<Separator>(
|
||||
by separator: @escaping (Element, Element) -> Separator
|
||||
) -> JoinedByClosureCollection<Self, Separator>
|
||||
}
|
||||
```
|
||||
|
||||
`JoinedBySequence`, `JoinedByClosureSequence`, `JoinedByCollection`, and
|
||||
`JoinedByClosureCollection` conform to `LazySequenceProtocol` when the base
|
||||
sequence conforms. `JoinedByCollection` and `JoinedByClosureCollection` also
|
||||
conform to `BidirectionalCollection` when the base collection conforms.
|
||||
@@ -1,78 +0,0 @@
|
||||
# Keyed
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Keyed.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/KeyedTests.swift)]
|
||||
|
||||
Stores the elements of a sequence as the values of a Dictionary, keyed by the result of the given closure.
|
||||
|
||||
```swift
|
||||
let fruits = ["Apricot", "Banana", "Apple", "Cherry", "Blackberry", "Avocado", "Coconut"]
|
||||
let fruitByLetter = fruits.keyed(by: { $0.first! })
|
||||
// Results in:
|
||||
// [
|
||||
// "A": "Avocado",
|
||||
// "B": "Blackberry",
|
||||
// "C": "Coconut",
|
||||
// ]
|
||||
```
|
||||
|
||||
On a key-collision, the latest element is kept by default. Alternatively, you can provide a closure which specifies which value to keep:
|
||||
|
||||
```swift
|
||||
let fruits = ["Apricot", "Banana", "Apple", "Cherry", "Blackberry", "Avocado", "Coconut"]
|
||||
let fruitsByLetter = fruits.keyed(
|
||||
by: { $0.first! },
|
||||
resolvingConflictsWith: { key, old, new in old } // Always pick the first fruit
|
||||
)
|
||||
// Results in:
|
||||
// [
|
||||
// "A": "Apricot",
|
||||
// "B": "Banana",
|
||||
// "C": "Cherry",
|
||||
// ]
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `keyed(by:)` and `keyed(by:resolvingConflictsWith:)` methods are declared in an `Sequence` extension, both returning `[Key: Element]`.
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func keyed<Key>(
|
||||
by keyForValue: (Element) throws -> Key
|
||||
) rethrows -> [Key: Element]
|
||||
|
||||
public func keyed<Key>(
|
||||
by keyForValue: (Element) throws -> Key,
|
||||
resolvingConflictsWith resolve: ((Key, Element, Element) throws -> Element)? = nil
|
||||
) rethrows -> [Key: Element]
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling `keyed(by:)` is an O(_n_) operation.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
| Language | "Keying" API |
|
||||
|---------------|-------------|
|
||||
| Java | [`toMap`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/stream/Collectors.html#toMap(java.util.function.Function,java.util.function.Function)) |
|
||||
| Kotlin | [`associatedBy`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/associate-by.html) |
|
||||
| C# | [`ToDictionary`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.todictionary?view=net-7.0#system-linq-enumerable-todictionary) |
|
||||
| Ruby (ActiveSupport) | [`index_by`](https://rubydoc.info/gems/activesupport/7.0.5/Enumerable#index_by-instance_method) |
|
||||
| PHP (Laravel) | [`keyBy`](https://laravel.com/docs/10.x/collections#method-keyby) |
|
||||
|
||||
#### Rejected alternative names
|
||||
|
||||
1. Java's `toMap` is referring to `Map`/`HashMap`, their naming for Dictionaries and other associative collections. It's easy to confuse with the transformation function, `Sequence.map(_:)`.
|
||||
2. C#'s `toXXX()` naming doesn't suite Swift well, which tends to prefer `Foo.init` over `toFoo()` methods.
|
||||
3. Ruby's `index_by` naming doesn't fit Swift well, where "index" is a specific term (e.g. the `associatedtype Index` on `Collection`). There is also a [`index(by:)`](Index.md) method in swift-algorithms, is specifically to do with matching elements up with their indices, and not any arbitrary derived value.
|
||||
|
||||
#### Alternative names
|
||||
|
||||
Kotlin's `associatedBy` naming is a good alternative, and matches the past tense of [Swift's API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/), though perhaps we'd spell it `associated(by:)`.
|
||||
|
||||
#### Customization points
|
||||
|
||||
Java and C# are interesting in that they provide overloads that let you customize the type of the outermost collection. E.g. using an `OrderedDictionary` instead of the default (hashed, unordered) `Dictionary`.
|
||||
@@ -0,0 +1,80 @@
|
||||
# LazySplit
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/LazySplit.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/LazySplitTests.swift)]
|
||||
|
||||
Lazily-evaluating versions of
|
||||
[`split(maxSplits:omittingEmptySubsequences:whereSeparator:)`](https://developer.apple.com/documentation/swift/sequence/3128814-split)
|
||||
and [`split(separator:maxSplits:omittingEmptySubsequences:)`](https://developer.apple.com/documentation/swift/sequence/3128818-split),
|
||||
performing the same operation as their counterparts defined on
|
||||
`Sequence` and `Collection`, are added to `LazySequence` and
|
||||
`LazyCollection`. The `LazyCollection` methods allow splitting a
|
||||
collection without allocating additional storage on the heap.
|
||||
|
||||
```swift
|
||||
// Splitting a lazy sequence.
|
||||
let numbers = stride(from: 1, through: 16, by: 1)
|
||||
for subsequence in numbers.lazy.split(
|
||||
whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 }
|
||||
) {
|
||||
print(subsequence)
|
||||
}
|
||||
/* Prints:
|
||||
[1, 2]
|
||||
[4]
|
||||
[7, 8]
|
||||
[11]
|
||||
[13, 14]
|
||||
[16]
|
||||
*/
|
||||
|
||||
// Splitting a lazy collection.
|
||||
let line = "BLANCHE: I don't want realism. I want magic!"
|
||||
for subsequence in line.lazy.split(separator: " ") {
|
||||
print(subsequence)
|
||||
}
|
||||
/* Prints
|
||||
BLANCHE:
|
||||
I
|
||||
don't
|
||||
want
|
||||
realism.
|
||||
I
|
||||
want
|
||||
magic!
|
||||
*/
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
`LazySequence` and `LazyCollection` are each extended with
|
||||
`split(maxSplits:omittingEmptySubsequences:whereSeparator:)` and
|
||||
`split(separator:maxSplits:omittingEmptySubsequences:)`.
|
||||
|
||||
The `LazySequence` versions of those methods return an instance of
|
||||
`LazySplitSequence`. The `LazyCollection` versions return an instance of
|
||||
`LazySplitCollection`.
|
||||
|
||||
`LazySplitSequence` wraps the sequence to be split, and provides an
|
||||
iterator whose `next` method returns a newly-allocated array containing
|
||||
the elements of each subsequence in the split sequence in turn.
|
||||
|
||||
`LazySplitCollection` wraps the collection to be split. Its `Index`
|
||||
wraps a range of base collection indices. `startIndex` is computed at
|
||||
initialization. Subscripting a `LazySplitCollection` instance returns
|
||||
the slice of the original collection which is the subsequence of the
|
||||
split collection at the given index's position.
|
||||
|
||||
### Complexity
|
||||
|
||||
Iterating a `LazySplitSequence` instance is O(_n_) in time and space,
|
||||
since each subsequence returned is a newly-allocated array.
|
||||
|
||||
Iterating a `LazySplitCollection` instance is O(_n_) in time and O(1) in
|
||||
space, since each subsequence returned is a slice of the base
|
||||
collection. Since `startIndex` is computed at initialization, some or
|
||||
all of the time cost may be paid at initialization. For example, if the
|
||||
base collection contains no elements determined to be separators, it
|
||||
will be iterated entirely on initialization of the split collection, and
|
||||
all subsequent operations on the split collection, such as
|
||||
`index(after:)`, will have complexity O(1).
|
||||
+8
-59
@@ -1,15 +1,11 @@
|
||||
# Minima and/or Maxima
|
||||
# Min/Max with Count
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/MinMax.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/MinMaxTests.swift)]
|
||||
|
||||
Returns the smallest or largest elements of this collection, sorted by a
|
||||
predicate or in the order defined by `Comparable` conformance.
|
||||
Returns the smallest or largest elements of this collection, sorted by a predicate or in the order defined by `Comparable` conformance.
|
||||
|
||||
If you need to sort a collection but only need access to a prefix or suffix of
|
||||
the sorted elements, using these methods can give you a performance boost over
|
||||
sorting the entire collection. The order of equal elements is guaranteed to be
|
||||
preserved.
|
||||
If you need to sort a collection but only need access to a prefix or suffix of the sorted elements, using these methods can give you a performance boost over sorting the entire collection. The order of equal elements is guaranteed to be preserved.
|
||||
|
||||
```swift
|
||||
let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
@@ -17,20 +13,6 @@ let smallestThree = numbers.min(count: 3, sortedBy: <)
|
||||
// [1, 2, 3]
|
||||
```
|
||||
|
||||
Return the smallest and largest elements of this sequence, determined by a
|
||||
predicate or in the order defined by `Comparable` conformance.
|
||||
|
||||
If you need both the minimum and maximum values of a collection, using these
|
||||
methods can give you a performance boost over running the `min` method followed
|
||||
by the `max` method. Plus they work with single-pass sequences.
|
||||
|
||||
```swift
|
||||
let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
if let (smallest, largest) = numbers.minAndMax(by: <) {
|
||||
// Work with 1 and 9....
|
||||
}
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
This adds the `Collection` methods shown below:
|
||||
@@ -49,18 +31,7 @@ extension Collection {
|
||||
}
|
||||
```
|
||||
|
||||
And the `Sequence` method:
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func minAndMax(
|
||||
by areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> (min: Element, max: Element)?
|
||||
}
|
||||
```
|
||||
|
||||
Additionally, versions of these methods for `Comparable` types are also
|
||||
provided:
|
||||
Additionally, versions of these methods for `Comparable` types are also provided:
|
||||
|
||||
```swift
|
||||
extension Collection where Element: Comparable {
|
||||
@@ -68,42 +39,20 @@ extension Collection where Element: Comparable {
|
||||
|
||||
public func max(count: Int) -> [Element]
|
||||
}
|
||||
|
||||
extension Sequence where Element: Comparable {
|
||||
public func minAndMax() -> (min: Element, max: Element)?
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
The algorithm used for minimal- or maximal-ordered subsets is based on
|
||||
[Soroush Khanlou's research on this matter](https://khanlou.com/2018/12/analyzing-complexity/).
|
||||
The total complexity is `O(k log k + nk)`, which will result in a runtime close
|
||||
to `O(n)` if *k* is a small amount. If *k* is a large amount (more than 10% of
|
||||
the collection), we fall back to sorting the entire array. Realistically, this
|
||||
means the worst case is actually `O(n log n)`.
|
||||
The algorithm used is based on [Soroush Khanlou's research on this matter](https://khanlou.com/2018/12/analyzing-complexity/). The total complexity is `O(k log k + nk)`, which will result in a runtime close to `O(n)` if *k* is a small amount. If *k* is a large amount (more than 10% of the collection), we fall back to sorting the entire array. Realistically, this means the worst case is actually `O(n log n)`.
|
||||
|
||||
Here are some benchmarks we made that demonstrates how this implementation
|
||||
(SmallestM) behaves when *k* increases (before implementing the fallback):
|
||||
Here are some benchmarks we made that demonstrates how this implementation (SmallestM) behaves when *k* increases (before implementing the fallback):
|
||||
|
||||

|
||||

|
||||
|
||||
The algorithm used for simultaneous minimum and maximum is slightly optimized.
|
||||
At each iteration, two elements are read, their relative order is determined,
|
||||
then each is compared against exactly one of the current extrema for potential
|
||||
replacement. When a comparison predicate has to analyze every component of both
|
||||
operands, the optimized algorithm isn't much faster than the straightforward
|
||||
approach. But when a predicate only needs to compare a small part of each
|
||||
instance, the optimization shines through.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
**C++:** The `<algorithm>` library defines a `partial_sort` function where the
|
||||
entire array is returned using a partial heap sort. It also defines a
|
||||
`minmax_element` function that scans a range for its minimal and maximal
|
||||
elements.
|
||||
**C++:** The `<algorithm>` library defines a `partial_sort` function where the entire array is returned using a partial heap sort.
|
||||
|
||||
**Python:** Defines a `heapq` priority queue that can be used to manually
|
||||
achieve the same result.
|
||||
**Python:** Defines a `heapq` priority queue that can be used to manually achieve the same result.
|
||||
|
||||
+1
-24
@@ -42,20 +42,6 @@ let p = numbers.partitioningIndex(where: { $0.isMultiple(of: 20) })
|
||||
// numbers[p...] = [20, 40, 60]
|
||||
```
|
||||
|
||||
The standard library’s existing `filter(_:)` method provides functionality to
|
||||
get the elements that do match a given predicate. `partitioned(by:)` returns
|
||||
both the elements that match the predicate as well as those that don’t, as a
|
||||
tuple.
|
||||
|
||||
```swift
|
||||
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
||||
let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
||||
print(longNames)
|
||||
// Prints "["Vivien", "Marlon"]"
|
||||
print(shortNames)
|
||||
// Prints "["Kim", "Karl"]"
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
All mutating methods are declared as extensions to `MutableCollection`.
|
||||
@@ -83,17 +69,11 @@ extension Collection {
|
||||
where belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
public func partitioned(
|
||||
by predicate: (Element) throws -> Bool
|
||||
) rethrows -> (falseElements: [Element], trueElements: [Element])
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
The existing partition is an O(_n_) operation, where _n_ is the length of the
|
||||
The existing partition is an O(_n_) operations, where _n_ is the length of the
|
||||
range to be partitioned, while the stable partition is O(_n_ log _n_). Both
|
||||
partitions have algorithms with improved performance for bidirectional
|
||||
collections, so it would be ideal for those to be customization points were they
|
||||
@@ -102,9 +82,6 @@ to eventually land in the standard library.
|
||||
`partitioningIndex(where:)` is a slight generalization of a binary search, and
|
||||
is an O(log _n_) operation for random-access collections; O(_n_) otherwise.
|
||||
|
||||
`partitioned(by:)` is an O(_n_) operation, where _n_ is the number of elements
|
||||
in the original sequence.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
**C++:** The `<algorithm>` library defines `partition`, `stable_partition`, and
|
||||
|
||||
+13
-15
@@ -98,20 +98,19 @@ for perm in numbers.permutations(ofCount: 0...) {
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `permutations(ofCount:)` and `uniquePermutations(ofCount:)` methods are
|
||||
declared as `Collection` extensions, and return `PermutationsSequence` and
|
||||
`UniquePermutationsSequence` instances, respectively:
|
||||
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) -> PermutationsSequence<Self>
|
||||
public func permutations<R>(ofCount kRange: R) -> PermutationsSequence<Self>
|
||||
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) -> UniquePermutationsSequence<Self>
|
||||
public func uniquePermutations<R>(ofCount kRange: R) -> UniquePermutationsSequence<Self>
|
||||
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self>
|
||||
public func uniquePermutations<R>(ofCount kRange: R) -> UniquePermutations<Self>
|
||||
where R: RangeExpression, R.Bound == Int
|
||||
}
|
||||
```
|
||||
@@ -120,19 +119,18 @@ Since both result types need to store an array of the collection’s
|
||||
indices and mutate the array to generate each permutation, they only
|
||||
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. The `PermutationsSequence` and
|
||||
`UniquePermutationsSequence` types conforms to `LazySequenceProtocol` when their
|
||||
base type conforms.
|
||||
array at every index advancement. The `Permutations` type
|
||||
conforms to `LazySequenceProtocol` when its base type conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling `permutations()` is an O(1) operation. Creating the iterator for a
|
||||
`PermutationsSequence` instance and each call to
|
||||
`PermutationsSequence.Iterator.next()` is an O(_n_) operation.
|
||||
`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.
|
||||
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
|
||||
|
||||
|
||||
+7
-7
@@ -25,26 +25,26 @@ When either collection is empty, the resulting wrapper collection is also empty.
|
||||
## Detailed Design
|
||||
|
||||
The `product` function takes (at minimum) a sequence and a collection and
|
||||
returns a `Product2Sequence` type:
|
||||
returns a `Product2` type:
|
||||
|
||||
```swift
|
||||
public func product<Base1: Sequence, Base2: Collection>(
|
||||
_ s1: Base1, _ s2: Base2
|
||||
) -> Product2Sequence<Base1, Base2>
|
||||
) -> Product2<Base1, Base2>
|
||||
```
|
||||
|
||||
We require `Collection` conformance for `Base2`, since it needs to be iterated
|
||||
over multiple times. `Base1`, by contrast, is only iterated over a single time,
|
||||
so it can be a sequence.
|
||||
|
||||
The `Product2Sequence` type wraps the base sequence and collection, and acts as
|
||||
a sequence in the base case, upgrading to a collection, a bidirectional
|
||||
The `Product2` type wraps the base sequence and collection, and acts as a
|
||||
sequence in the base case, upgrading to a collection, a bidirectional
|
||||
collection, and a random-access collection when both base collections have those
|
||||
conformances.
|
||||
|
||||
We don't provide higher arities (like `Product3Sequence`, `Product4Sequence`,
|
||||
etc.) at this time to match the standard library's `Zip2Sequence` type. Users
|
||||
can compose multiple calls to `product` if they would like higher arities.
|
||||
We don't provide higher arities (like `Product3`, `Product4`, etc.) at this
|
||||
time to match the standard library's `Zip2` type. Users can compose multiple
|
||||
calls to `product` if they would like higher arities.
|
||||
|
||||
### Complexity
|
||||
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
# Guides
|
||||
|
||||
These guides describe the design and intention behind the APIs included in the `Algorithms` library. For further reading, see the [announcement on swift.org](https://swift.org/blog/swift-algorithms/) and the [official documentation](https://swiftpackageindex.com/apple/swift-algorithms/documentation/algorithms).
|
||||
|
||||
## Contents
|
||||
|
||||
#### Combinations / permutations
|
||||
|
||||
- [`combinations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Combinations.md): Combinations of particular sizes of the elements in a collection.
|
||||
- [`permutations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md): Permutations of a particular size of the elements in a collection, or of the full collection.
|
||||
- [`uniquePermutations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md): Permutations of a collection's elements, skipping any duplicate permutations.
|
||||
|
||||
#### Mutating algorithms
|
||||
|
||||
- [`rotate(toStartAt:)`, `rotate(subrange:toStartAt:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Rotate.md): In-place rotation of elements.
|
||||
- [`stablePartition(by:)`, `stablePartition(subrange:by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): A partition that preserves the relative order of the resulting prefix and suffix.
|
||||
|
||||
#### Combining collections
|
||||
|
||||
- [`chain(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chain.md): Concatenates two collections with the same element type.
|
||||
- [`cycled()`, `cycled(times:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Cycle.md): Repeats the elements of a collection forever or a set number of times.
|
||||
- [`joined(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Joined.md): Concatenate sequences of sequences, using an element or sequence as a separator, or using a closure to generate each separator.
|
||||
- [`product(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Product.md): Iterates over all the pairs of two collections; equivalent to nested `for`-`in` loops.
|
||||
|
||||
#### Subsetting operations
|
||||
|
||||
- [`compacted()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Compacted.md): Drops the `nil`s from a sequence or collection, unwrapping the remaining elements.
|
||||
- [`partitioned(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the elements in a sequence or collection that do and do not match a given predicate.
|
||||
- [`randomSample(count:)`, `randomSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection.
|
||||
- [`randomStableSample(count:)`, `randomStableSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection, preserving their original relative order.
|
||||
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
|
||||
- [`suffix(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Suffix.md): Returns the suffix of a collection where all element pass a given predicate.
|
||||
- [`trimmingPrefix(while:)`, `trimmingSuffix(while)`, `trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start, end, or both. The mutating `trim...` methods trim a collection in place.
|
||||
- [`uniqued()`, `uniqued(on:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Unique.md): The unique elements of a collection, preserving their order.
|
||||
- [`minAndMax()`, `minAndMax(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest and largest elements of a sequence.
|
||||
|
||||
#### Partial sorting
|
||||
|
||||
- [`min(count:)`, `max(count:)`, `min(count:sortedBy:)`, `max(count:sortedBy:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest or largest elements of a collection, sorted by a predicate.
|
||||
|
||||
#### Other useful operations
|
||||
|
||||
- [`adjacentPairs()`](https://github.com/apple/swift-algorithms/blob/main/Guides/AdjacentPairs.md): Lazily iterates over tuples of adjacent elements.
|
||||
- [`chunked(by:)`, `chunked(on:)`, `chunks(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chunked.md): Eager and lazy operations that break a collection into chunks based on either a binary predicate or when the result of a projection changes or chunks of a given count.
|
||||
- [`firstNonNil(_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/FirstNonNil.md): Returns the first non-`nil` result from transforming a sequence's elements.
|
||||
- [`grouped(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Grouped.md): Group up elements using the given closure, returning a Dictionary of those groups, keyed by the results of the closure.
|
||||
- [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements.
|
||||
- [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence.
|
||||
- [`keyed(by:)`, `keyed(by:resolvingConflictsBy:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Keyed.md): Returns a Dictionary that associates elements of a sequence with the keys returned by the given closure.
|
||||
- [`partitioningIndex(where:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the starting index of the partition of a collection that matches a predicate.
|
||||
- [`reductions(_:)`, `reductions(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Reductions.md): Returns all the intermediate states of reducing the elements of a sequence or collection.
|
||||
- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Split.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element.
|
||||
- [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection.
|
||||
@@ -17,7 +17,7 @@ source.randomSample(count: 4)
|
||||
// e.g. [30, 10, 70, 50]
|
||||
source.randomStableSample(count: 4)
|
||||
// e.g. [20, 30, 80, 100]
|
||||
|
||||
//
|
||||
var rng = SplitMix64(seed: 0)
|
||||
source.randomSample(count: 4, using: &rng)
|
||||
```
|
||||
@@ -146,4 +146,4 @@ performance characteristics as the collection itself, so a user can call
|
||||
The stable version of sampling could theoretically return a lazy wrapper
|
||||
instead of eagerly creating the sample. However, this isn’t well-motivated and
|
||||
poses some challenges, such as needing to store a copy of the random generator
|
||||
and potentially needing to cache the randomly-generated values.
|
||||
and potentially needing to cache the randomly-generated values.
|
||||
+26
-25
@@ -3,8 +3,7 @@
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Reductions.swift) |
|
||||
[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.
|
||||
Produces all the intermediate results of reducing a sequence's elements using a closure.
|
||||
|
||||
```swift
|
||||
let exclusiveRunningTotal = (1...5).reductions(0, +)
|
||||
@@ -27,37 +26,39 @@ 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
|
||||
) -> ExclusiveReductionsSequence<Result, Self>
|
||||
|
||||
public func reductions<Result>(
|
||||
into initial: Result,
|
||||
_ transform: @escaping (inout Result, Element) -> Void
|
||||
) -> ExclusiveReductionsSequence<Result, Self>
|
||||
public func reductions<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: @escaping (Result, Element) -> Result
|
||||
) -> ExclusiveReductions<Result, Self>
|
||||
|
||||
public func reductions(
|
||||
_ transform: @escaping (Element, Element) -> Element
|
||||
) -> InclusiveReductionsSequence<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<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: (Result, Element) throws -> Result
|
||||
) rethrows -> [Result]
|
||||
|
||||
public func reductions(
|
||||
_ transform: (Element, Element) throws -> Element
|
||||
) rethrows -> [Element]
|
||||
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]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -101,7 +102,7 @@ takes an initial value to use for the first element in the returned sequence,
|
||||
and another which uses the first value of the base sequence as the initial
|
||||
value. C++ calls these variants exclusive and inclusive respectively and so
|
||||
these terms carry through as the name for the lazy sequences;
|
||||
`ExclusiveReductionsSequence` and `InclusiveReductionsSequence`.
|
||||
`ExclusiveReductions` and `InclusiveReductions`.
|
||||
|
||||
[SE-0045]: https://forums.swift.org/t/review-se-0045-add-scan-prefix-while-drop-while-and-iterate-to-the-stdlib/2382
|
||||
[Issue 25]: https://github.com/apple/swift-algorithms/issues/25
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 64 KiB After Width: | Height: | Size: 74 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 69 KiB After Width: | Height: | Size: 77 KiB |
@@ -1,79 +0,0 @@
|
||||
# Split
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Split.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/SplitTests.swift)]
|
||||
|
||||
Lazily-evaluating versions of
|
||||
[`split(maxSplits:omittingEmptySubsequences:whereSeparator:)`](https://developer.apple.com/documentation/swift/sequence/3128814-split)
|
||||
and [`split(separator:maxSplits:omittingEmptySubsequences:)`](https://developer.apple.com/documentation/swift/sequence/3128818-split),
|
||||
performing the same operation as their counterparts defined on
|
||||
`Sequence` and `Collection`, are added to `LazySequence` and
|
||||
`LazyCollection`. The `LazyCollection` methods allow splitting a
|
||||
collection without allocating additional storage on the heap.
|
||||
|
||||
```swift
|
||||
// Splitting a lazy sequence.
|
||||
let numbers = stride(from: 1, through: 16, by: 1)
|
||||
for subsequence in numbers.lazy.split(
|
||||
whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 }
|
||||
) {
|
||||
print(subsequence)
|
||||
}
|
||||
/* Prints:
|
||||
[1, 2]
|
||||
[4]
|
||||
[7, 8]
|
||||
[11]
|
||||
[13, 14]
|
||||
[16]
|
||||
*/
|
||||
|
||||
// Splitting a lazy collection.
|
||||
let line = "BLANCHE: I don't want realism. I want magic!"
|
||||
for subsequence in line.lazy.split(separator: " ") {
|
||||
print(subsequence)
|
||||
}
|
||||
/* Prints
|
||||
BLANCHE:
|
||||
I
|
||||
don't
|
||||
want
|
||||
realism.
|
||||
I
|
||||
want
|
||||
magic!
|
||||
*/
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
`LazySequence` and `LazyCollection` are each extended with
|
||||
`split(maxSplits:omittingEmptySubsequences:whereSeparator:)` and
|
||||
`split(separator:maxSplits:omittingEmptySubsequences:)`.
|
||||
|
||||
The `LazySequence` versions of those methods return an instance of
|
||||
`SplitSequence`. The `LazyCollection` versions return an instance of
|
||||
`SplitCollection`.
|
||||
|
||||
`SplitSequence` wraps the sequence to be split, and provides an iterator whose
|
||||
`next` method returns a newly-allocated array containing the elements of each
|
||||
subsequence in the split sequence in turn.
|
||||
|
||||
`SplitCollection` wraps the collection to be split. Its `Index` wraps a range of
|
||||
base collection indices. `startIndex` is computed at initialization.
|
||||
Subscripting a `SplitCollection` instance returns the slice of the original
|
||||
collection which is the subsequence of the split collection at the given index's
|
||||
position.
|
||||
|
||||
### Complexity
|
||||
|
||||
Iterating a `SplitSequence` instance is O(_n_) in time and space, since each
|
||||
subsequence returned is a newly-allocated array.
|
||||
|
||||
Iterating a `SplitCollection` instance is O(_n_) in time and O(1) in space,
|
||||
since each subsequence returned is a slice of the base collection. Since
|
||||
`startIndex` is computed at initialization, some or all of the time cost may be
|
||||
paid at initialization. For example, if the base collection contains no elements
|
||||
determined to be separators, it will be iterated entirely on initialization of
|
||||
the split collection, and all subsequent operations on the split collection,
|
||||
such as `index(after:)`, will have complexity O(1).
|
||||
+18
-25
@@ -3,7 +3,7 @@
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Stride.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/StrideTests.swift)]
|
||||
|
||||
Step over the elements of a sequence elements by a specified amount.
|
||||
A type that steps over sequence elements by the specified amount.
|
||||
|
||||
This is available through the `striding(by:)` method on any `Sequence`.
|
||||
|
||||
@@ -11,39 +11,33 @@ This is available through the `striding(by:)` method on any `Sequence`.
|
||||
(0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]
|
||||
```
|
||||
|
||||
If the stride is larger than the length of the sequence, the resulting wrapper
|
||||
only contains the first element.
|
||||
If the stride is larger than the count, the resulting wrapper only contains the
|
||||
first element.
|
||||
|
||||
The stride amount must be a positive value.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `striding(by:)` method is declared in extension of both `Sequence` and
|
||||
`Collection`:
|
||||
The `striding(by:)` method is declared as a `Sequence` extension, and returns a
|
||||
`Stride` type:
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func striding(by step: Int) -> StridingSequence<Self>
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
public func striding(by step: Int) -> StridingCollection<Self>
|
||||
public func striding(by step: Int) -> Stride<Self>
|
||||
}
|
||||
```
|
||||
|
||||
The reason for this distinction is subtle. The `StridingSequence.Iterator` type
|
||||
is unable to skip over multiple elements of the wrapped iterator at once since
|
||||
that's not part of `IteratorProtocol`'s interface. In order to efficiently
|
||||
stride over collections that provide a fast way of skipping multiple elements at
|
||||
once, the `StridingCollection` type was added which does not provide a custom
|
||||
`Iterator` type and therefore always strides over the underlying collection in
|
||||
the fastest way possible. See the related
|
||||
[GitHub issue](https://github.com/apple/swift-algorithms/issues/63) for more
|
||||
information.
|
||||
A custom `Index` type is defined so that it's not possible to get confused when trying
|
||||
to access an index of the stride collection.
|
||||
|
||||
A careful thought was given to the composition of these strides by giving a
|
||||
custom implementation to `index(_:offsetBy:limitedBy)` which multiplies the
|
||||
offset by the stride amount.
|
||||
```swift
|
||||
[0, 1, 2, 3, 4].striding(by: 2)[1] // == 1
|
||||
[0, 1, 2, 3, 4].striding(by: 2).map { $0 }[1] // == 2
|
||||
```
|
||||
|
||||
A careful thought was given to the composition of these strides by giving a custom
|
||||
implementation to `index(_:offsetBy:limitedBy)` which multiplies the offset by the
|
||||
stride amount.
|
||||
|
||||
```swift
|
||||
base.index(i.base, offsetBy: distance * stride, limitedBy: base.endIndex)
|
||||
@@ -58,9 +52,8 @@ The following two lines of code are equivalent, including performance:
|
||||
|
||||
### Complexity
|
||||
|
||||
The call to `striding(by: k)` is always O(_1_) and access to the next value in
|
||||
the stride is O(_1_) if the collection conforms to `RandomAccessCollection`,
|
||||
otherwise O(_k_).
|
||||
The call to `striding(by: k)` is always O(_1_) and access to the next value in the stride
|
||||
is O(_1_) if the collection conforms to `RandomAccessCollection`, otherwise O(_k_).
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
|
||||
+15
-15
@@ -3,37 +3,37 @@
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Suffix.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/SuffixTests.swift)]
|
||||
|
||||
This function returns a subsequence containing the elements from the end of the
|
||||
collection until predicate returns `false` and skipping the remaining elements.
|
||||
|
||||
This example uses `suffix(while: )` to iterate through collection of integers
|
||||
from the end until the predicate returns false, in this case when `$0 <= 5`
|
||||
This function returns a subsequence containing the elements from the end of the collection until predicate returns `false` and skipping the remaining elements.
|
||||
|
||||
This example uses `suffix(while: )` to iterate through collection of integers from the end until the predicate returns false, in this case when `$0 <= 5`
|
||||
```swift
|
||||
(0...10).suffix(while: { $0 > 5 }) // == [6,7,8,9,10]
|
||||
(0...10).suffix(while: { $0 > 5 } // == [6,7,8,9,10]
|
||||
```
|
||||
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `suffix(while:)` function is added as a method on an extension of
|
||||
`BidirectionalCollection`.
|
||||
The `suffix(while:)` function is added as a method on an extension of `BidirectionalCollection`.
|
||||
|
||||
|
||||
```swift
|
||||
extension BidirectionalCollection {
|
||||
public func suffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
|
||||
public func suffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
}
|
||||
```
|
||||
|
||||
This method requires `BidirectionalCollection` for an efficient implementation
|
||||
which visits as few elements as possible. Swift's protocol allows for backward
|
||||
traversal of a collection as well as access to *last* property of a collection.
|
||||
This method requires `BidirectionalCollection` for an efficient implementation which visits as few elements as possible. Swift's protocol allows for backward traversal of a collection as well as access to *last* property of a collection.
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling this method is O(*n*), where *n* is the length of the collection.
|
||||
|
||||
|
||||
### Naming
|
||||
|
||||
The function's name resembles that of an existing Swift function
|
||||
`prefix(while:)`, which performs same operation however in the forward direction
|
||||
of the collection. Hence, as this function traverses from the end of the
|
||||
collection, `suffix(while:)` is an appropriate name.
|
||||
The function's name resembles that of an existing Swift function `prefix(while:)`, which performs same operation however in the forward direction of the collection. Hence, as this function traverses from the end of the collection, `suffix(while:)` is an appropriate name.
|
||||
|
||||
|
||||
|
||||
+31
-87
@@ -3,11 +3,10 @@
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Trim.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/TrimTests.swift)]
|
||||
|
||||
A group of methods that return the `SubSequence` formed by discarding elements
|
||||
at the start and/or end of the collection which satisfy the given predicate.
|
||||
Returns a `SubSequence` formed by discarding all elements at the start and end of the collection
|
||||
which satisfy the given predicate.
|
||||
|
||||
This example uses `trimming(while:)` to get a substring without the white space
|
||||
at the beginning and end of the string.
|
||||
This example uses `trimming(while:)` to get a substring without the white space at the beginning and end of the string.
|
||||
|
||||
```swift
|
||||
let myString = " hello, world "
|
||||
@@ -17,83 +16,37 @@ let results = [2, 10, 11, 15, 20, 21, 100].trimming(while: { $0.isMultiple(of: 2
|
||||
print(results) // [11, 15, 20, 21]
|
||||
```
|
||||
|
||||
The `Algorithms` library also includes methods that trim from each end,
|
||||
as well as mutating versions of all three methods.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
New methods are added to `Collection` and `BidirectionalCollection`:
|
||||
A new method is added to `BidirectionalCollection`:
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
func trimmingPrefix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
}
|
||||
|
||||
extension BidirectionalCollection {
|
||||
func trimmingSuffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
|
||||
func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
}
|
||||
|
||||
extension Collection where Self: RangeReplaceableCollection {
|
||||
mutating func trimPrefix(while predicate: (Element) throws -> Bool) rethrows
|
||||
}
|
||||
|
||||
extension BidirectionalCollection where Self: RangeReplaceableCollection {
|
||||
mutating func trimSuffix(while predicate: (Element) throws -> Bool) rethrows
|
||||
|
||||
mutating func trim(while predicate: (Element) throws -> Bool) rethrows
|
||||
public func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
}
|
||||
```
|
||||
|
||||
There are also overloads of the mutating methods when `Self == Self.SubSequence`,
|
||||
for non-range-replaceable self-slicing types.
|
||||
This method requires `BidirectionalCollection` for an efficient implementation which visits as few elements as possible.
|
||||
|
||||
Though the `trimming` and `trimmingSuffix` methods are declared on
|
||||
`BidirectionalCollection`, a less-efficient implementation is _possible_ for
|
||||
any `Collection`, which would involve always traversing the entire collection.
|
||||
This implementation is not provided, as it would mean developers of generic
|
||||
algorithms who forget to add the `BidirectionalCollection` constraint will
|
||||
receive that inefficient implementation:
|
||||
A less-efficient implementation is _possible_ for any `Collection`, which would involve always traversing the
|
||||
entire collection. This implementation is not provided, as it would mean developers of generic algorithms who forget
|
||||
to add the `BidirectionalCollection` constraint will receive that inefficient implementation:
|
||||
|
||||
```swift
|
||||
func myAlgorithm<Input>(input: Input) where Input: Collection {
|
||||
let trimmedInput = input.trimming(while: { ... }) // Uses least-efficient implementation.
|
||||
|
||||
let trimmedInput = input.trimming(while: { ... }) // Uses least-efficient implementation.
|
||||
}
|
||||
|
||||
func myAlgorithm2<Input>(input: Input) where Input: BidirectionalCollection {
|
||||
let trimmedInput = input.trimming(while: { ... }) // Uses most-efficient implementation.
|
||||
|
||||
let trimmedInput = input.trimming(while: { ... }) // Uses most-efficient implementation.
|
||||
}
|
||||
```
|
||||
|
||||
Swift provides the `BidirectionalCollection` protocol for marking types which
|
||||
support reverse traversal, and generic types and algorithms which want to make
|
||||
use of that should add it to their constraints.
|
||||
|
||||
#### Supporting Methods
|
||||
|
||||
The `endOfPrefix(while:)` and `startOfSuffix(while:)` methods are used
|
||||
in the implementation of the trimming methods described above. As these
|
||||
supporting methods are independently useful, they are included in the library
|
||||
as well.
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
/// Returns the exclusive upper bound of the prefix of elements that satisfy
|
||||
/// the predicate.
|
||||
func endOfPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index
|
||||
}
|
||||
|
||||
extension BidirectionalCollection {
|
||||
/// Returns the inclusive lower bound of the suffix of elements that satisfy
|
||||
/// the predicate.
|
||||
func startOfSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index
|
||||
}
|
||||
```
|
||||
Swift provides the `BidirectionalCollection` protocol for marking types which support reverse traversal,
|
||||
and generic types and algorithms which want to make use of that should add it to their constraints.
|
||||
|
||||
### Complexity
|
||||
|
||||
@@ -101,8 +54,7 @@ Calling this method is O(_n_).
|
||||
|
||||
### Naming
|
||||
|
||||
The name `trim` has precedent in other programming languages. Another popular
|
||||
alternative might be `strip`.
|
||||
The name `trim` has precedent in other programming languages. Another popular alternative might be `strip`.
|
||||
|
||||
| Example usage | Languages |
|
||||
|-|-|
|
||||
@@ -127,38 +79,30 @@ alternative might be `strip`.
|
||||
| TRIM(''string'') | SQL |
|
||||
| String.trim ''string'' | OCaml 4+ |
|
||||
|
||||
Note: This is an abbreviated list from Wikipedia.
|
||||
[Full table](https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(string_functions)#trim)
|
||||
Note: This is an abbreviated list from Wikipedia. [Full table](https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(string_functions)#trim)
|
||||
|
||||
The standard library includes a variety of methods which perform similar
|
||||
operations:
|
||||
The standard library includes a variety of methods which perform similar operations:
|
||||
|
||||
- Firstly, there are `dropFirst(Int)` and `dropLast(Int)`. These return slices
|
||||
but do not support user-defined predicates. If the collection's `count` is less
|
||||
than the number of elements to drop, they return an empty slice.
|
||||
- Secondly, there is `drop(while:)`, which also returns a slice and is
|
||||
equivalent to a 'left-trim' (trimming from the head but not the tail). If the
|
||||
entire collection is dropped, this method returns an empty slice.
|
||||
- Thirdly, there are `removeFirst(Int)` and `removeLast(Int)` which do not
|
||||
return slices and actually mutate the collection. If the collection's `count` is
|
||||
less than the number of elements to remove, this method triggers a runtime
|
||||
error.
|
||||
- Lastly, there are the `popFirst()` and `popLast()` methods, which work like
|
||||
`removeFirst()` and `removeLast()`, except they do not trigger a runtime error
|
||||
for empty collections.
|
||||
- Firstly, there are `dropFirst(Int)` and `dropLast(Int)`. These return slices but do not support user-defined predicates.
|
||||
If the collection's `count` is less than the number of elements to drop, they return an empty slice.
|
||||
- Secondly, there is `drop(while:)`, which also returns a slice and is equivalent to a 'left-trim' (trimming from the head but not the tail).
|
||||
If the entire collection is dropped, this method returns an empty slice.
|
||||
- Thirdly, there are `removeFirst(Int)` and `removeLast(Int)` which do not return slices and actually mutate the collection.
|
||||
If the collection's `count` is less than the number of elements to remove, this method triggers a runtime error.
|
||||
- Lastly, there are the `popFirst()` and `popLast()` methods, which work like `removeFirst()` and `removeLast()`,
|
||||
except they do not trigger a runtime error for empty collections.
|
||||
|
||||
The closest neighbours to this function would be the `drop` family of methods.
|
||||
Unfortunately, unlike `dropFirst(Int)`,the name `drop(while:)` does not specify
|
||||
which end(s) of the collection it operates on. Moreover, one could easily
|
||||
The closest neighbours to this function would be the `drop` family of methods. Unfortunately, unlike `dropFirst(Int)`,
|
||||
the name `drop(while:)` does not specify which end(s) of the collection it operates on. Moreover, one could easily
|
||||
mistake code such as:
|
||||
|
||||
```swift
|
||||
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
|
||||
concise code, which is more aligned with other programming languages:
|
||||
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 concise code, which is more aligned with other programming
|
||||
languages:
|
||||
|
||||
```swift
|
||||
// Does `result` contain the input, trimmed of certain elements?
|
||||
|
||||
+12
-11
@@ -5,9 +5,10 @@
|
||||
|
||||
Methods to strip repeated elements from a sequence or collection.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
```swift
|
||||
let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1]
|
||||
@@ -18,14 +19,14 @@ let unique = numbers.uniqued()
|
||||
|
||||
## 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. `uniqued(on:)` has a matching lazy version that is added to
|
||||
`LazySequenceProtocol`.
|
||||
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. `uniqued(on:)` has a matching lazy
|
||||
version that is added to `LazySequenceProtocol`.
|
||||
|
||||
```swift
|
||||
extension Sequence where Element: Hashable {
|
||||
func uniqued() -> UniquedSequence<Self, Element>
|
||||
func uniqued() -> Uniqued<Self, Element>
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
@@ -34,15 +35,15 @@ extension Sequence {
|
||||
}
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
func uniqued<Subject>(on projection: @escaping (Element) -> Subject) -> UniquedSequence<Self, Subject>
|
||||
func uniqued<Subject>(on projection: @escaping (Element) -> Subject) -> Uniqued<Self, Subject>
|
||||
where Subject: Hashable
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
The eager `uniqued(on:)` method is O(_n_) in both time and space complexity. The
|
||||
lazy versions are O(_1_).
|
||||
The eager `uniqued(on:)` method is O(_n_) in both time and space complexity.
|
||||
The lazy versions are O(_1_).
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
|
||||
+8
-12
@@ -6,9 +6,7 @@
|
||||
Break a collection into overlapping subsequences where
|
||||
elements are slices from the original collection.
|
||||
|
||||
The `windows(ofCount:)` method takes a size as a parameter and returns a
|
||||
collection of subsequences. Each element of the returned collection is a
|
||||
successive overlapping slice of the given size.
|
||||
The `windows(ofCount:)` method takes a size as a parameter and returns a collection of subsequences. Each element of the returned collection is a successive overlapping slice of the given size.
|
||||
|
||||
```swift
|
||||
let swift = "swift"
|
||||
@@ -23,26 +21,24 @@ The `windows(ofCount:)` method is added as an extension `Collection` method:
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
public func windows(ofCount count: Int) -> WindowsOfCountCollection<Self>
|
||||
public func windows(ofCount count: Int) -> Windows<Self>
|
||||
}
|
||||
```
|
||||
|
||||
If a size larger than the collection's length is specified, the returned
|
||||
collection is empty.
|
||||
If a size larger than the collection's length is specified, the returned collection is empty.
|
||||
|
||||
```swift
|
||||
[1, 2, 3].windows(ofCount: 5).isEmpty // true
|
||||
```
|
||||
|
||||
The resulting `WindowsOfCountCollection` type is a collection, with conditional
|
||||
conformance to the `BidirectionalCollection`, `RandomAccessCollection`, and
|
||||
`LazySequenceProtocol` protocols when the base collection conforms.
|
||||
The resulting `Windows` type is a collection, with conditional conformance to the
|
||||
`BidirectionalCollection`, `RandomAccessCollection`, and
|
||||
`LazyCollectionProtocol` protocols when the base collection conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
The call to `windows(ofCount: k)` is O(1) if the collection conforms to
|
||||
`RandomAccessCollection`, otherwise O(_k_). Access to each successive window is
|
||||
O(1).
|
||||
`RandomAccessCollection`, otherwise O(_k_). Access to each successive window is O(1).
|
||||
|
||||
### Naming
|
||||
|
||||
@@ -55,5 +51,5 @@ and `permutations(ofCount:)`.
|
||||
### Comparison with other languages
|
||||
|
||||
[rust](https://doc.rust-lang.org/std/slice/struct.Windows.html) has
|
||||
`std::slice::Windows` which is a method available on slices. It has the same
|
||||
`std::slice::Windows` which is a method available on slices. It has the same
|
||||
semantics as described here.
|
||||
+6
-19
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:5.7
|
||||
// swift-tools-version:5.1
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
@@ -13,23 +13,10 @@
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "swift-algorithms",
|
||||
products: [
|
||||
.library(
|
||||
name: "Algorithms",
|
||||
targets: ["Algorithms"])
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-numerics.git", from: "1.0.0")
|
||||
],
|
||||
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"]),
|
||||
]
|
||||
)
|
||||
name: "Algorithms", dependencies: [.product(name: "RealModule", package: "swift-numerics")]),
|
||||
.testTarget(name: "SwiftAlgorithmsTests", dependencies: ["Algorithms"]),
|
||||
])
|
||||
@@ -2,35 +2,50 @@
|
||||
|
||||
**Swift Algorithms** is an open-source package of sequence and collection algorithms, along with their related types.
|
||||
|
||||
## Overview
|
||||
Read more about the package, and the intent behind it, in the [announcement on swift.org](https://swift.org/blog/swift-algorithms/).
|
||||
|
||||
The Algorithms package provides a variety of sequence and collection operations, letting you cycle over a collection's elements, find combinations and permutations, create a random sample, and more.
|
||||
## Contents
|
||||
|
||||
For example, the package includes a group of "chunking" methods, each of which breaks a collection into consecutive subsequences. One version tests adjacent elements to find the breaking point between chunks — you can use it to quickly separate an array into ascending runs:
|
||||
#### Combinations / permutations
|
||||
|
||||
```swift
|
||||
let numbers = [10, 20, 30, 10, 40, 40, 10, 20]
|
||||
let chunks = numbers.chunked(by: { $0 <= $1 })
|
||||
// [[10, 20, 30], [10, 40, 40], [10, 20]]
|
||||
```
|
||||
- [`combinations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Combinations.md): Combinations of particular sizes of the elements in a collection.
|
||||
- [`permutations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md): Permutations of a particular size of the elements in a collection, or of the full collection.
|
||||
- [`uniquePermutations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md): Permutations of a collection's elements, skipping any duplicate permutations.
|
||||
|
||||
Another version looks for a change in the transformation of each successive value. You can use that to separate a list of names into groups by the first character:
|
||||
#### Mutating algorithms
|
||||
|
||||
```swift
|
||||
let names = ["Cassie", "Chloe", "Jasmine", "Jordan", "Taylor"]
|
||||
let chunks = names.chunked(on: \.first)
|
||||
// [["Cassie", "Chloe"], ["Jasmine", "Jordan"], ["Taylor"]]
|
||||
```
|
||||
- [`rotate(toStartAt:)`, `rotate(subrange:toStartAt:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Rotate.md): In-place rotation of elements.
|
||||
- [`stablePartition(by:)`, `stablePartition(subrange:by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): A partition that preserves the relative order of the resulting prefix and suffix.
|
||||
|
||||
Explore more chunking methods and the remainder of the `Algorithms` package in the links below.
|
||||
#### Combining collections
|
||||
|
||||
## Documentation
|
||||
- [`chain(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chain.md): Concatenates two collections with the same element type.
|
||||
- [`product(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Product.md): Iterates over all the pairs of two collections; equivalent to nested `for`-`in` loops.
|
||||
- [`cycled()`, `cycled(times:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Cycle.md): Repeats the elements of a collection forever or a set number of times.
|
||||
|
||||
For API documentation, see the library's official documentation in Xcode or on the Web.
|
||||
#### Subsetting operations
|
||||
|
||||
- [API documentation][docs]
|
||||
- [Swift.org announcement][announcement]
|
||||
- [API Proposals/Guides][guides]
|
||||
- [`compacted()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Compacted.md): Drops the `nil`s from a sequence or collection, unwrapping the remaining elements.
|
||||
- [`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
|
||||
|
||||
- [`min(count:)`, `max(count:)`, `min(count:sortedBy:)`, `max(count:sortedBy:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest or largest elements of a collection, sorted by a predicate.
|
||||
|
||||
#### Other useful operations
|
||||
|
||||
- [`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.
|
||||
- [`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
|
||||
|
||||
@@ -38,29 +53,32 @@ To use the `Algorithms` library in a SwiftPM project,
|
||||
add the following line to the dependencies in your `Package.swift` file:
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/apple/swift-algorithms", from: "1.2.0"),
|
||||
.package(url: "https://github.com/apple/swift-algorithms", from: "0.0.1"),
|
||||
```
|
||||
|
||||
Include `"Algorithms"` as a dependency for your executable target:
|
||||
Because `Algorithms` is under active development,
|
||||
source-stability is only guaranteed within minor versions (e.g. between `0.0.3` and `0.0.4`).
|
||||
If you don't want potentially source-breaking package updates,
|
||||
use this dependency specification instead:
|
||||
|
||||
```swift
|
||||
.target(name: "<target>", dependencies: [
|
||||
.product(name: "Algorithms", package: "swift-algorithms"),
|
||||
]),
|
||||
.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.1.0")),
|
||||
```
|
||||
|
||||
Finally, add `import Algorithms` to your source code.
|
||||
Finally, include `"Algorithms"` as a dependency for your executable target:
|
||||
|
||||
## Source Stability
|
||||
|
||||
The Swift Algorithms package is source stable; version numbers follow [Semantic Versioning](https://semver.org/). Source breaking changes to public API can only land in a new major version.
|
||||
|
||||
The public API of the `swift-algorithms` package consists of non-underscored declarations that are marked `public` in the `Algorithms` module. Interfaces that aren't part of the public API may continue to change in any release, including patch releases.
|
||||
|
||||
Future minor versions of the package may introduce changes to these rules as needed.
|
||||
|
||||
We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release. Requiring a new Swift release will only require a minor version bump.
|
||||
|
||||
[docs]: https://swiftpackageindex.com/apple/swift-algorithms/documentation/algorithms
|
||||
[announcement]: https://swift.org/blog/swift-algorithms/
|
||||
[guides]: https://github.com/apple/swift-algorithms/tree/main/Guides
|
||||
```swift
|
||||
let package = Package(
|
||||
// name, platforms, products, etc.
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-algorithms", from: "0.1.0"),
|
||||
// other dependencies
|
||||
],
|
||||
targets: [
|
||||
.target(name: "<target>", dependencies: [
|
||||
.product(name: "Algorithms", package: "swift-algorithms"),
|
||||
]),
|
||||
// other targets
|
||||
]
|
||||
)
|
||||
```
|
||||
@@ -1,20 +0,0 @@
|
||||
#!/bin/bash
|
||||
##===----------------------------------------------------------------------===##
|
||||
##
|
||||
## This source file is part of the Swift Algorithms open source project
|
||||
##
|
||||
## Copyright (c) 2025 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
|
||||
##
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
# Move to the project root
|
||||
cd "$(dirname "$0")" || exit
|
||||
cd ..
|
||||
echo "Formatting Swift sources in $(pwd)"
|
||||
|
||||
# Run the format / lint commands
|
||||
git ls-files -z '*.swift' | xargs -0 swift format format --parallel --in-place
|
||||
git ls-files -z '*.swift' | xargs -0 swift format lint --strict --parallel
|
||||
@@ -1,323 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Returns a sequence of overlapping adjacent pairs of the elements of this
|
||||
/// sequence.
|
||||
///
|
||||
/// In the `AdjacentPairsSequence` returned by this method, the elements of
|
||||
/// the *i*th pair are the *i*th and *(i+1)*th elements of the underlying
|
||||
/// sequence. The following example uses the `adjacentPairs()` method to
|
||||
/// iterate over adjacent pairs of integers:
|
||||
///
|
||||
/// for pair in (1...).prefix(5).adjacentPairs() {
|
||||
/// print(pair)
|
||||
/// }
|
||||
/// // Prints "(1, 2)"
|
||||
/// // Prints "(2, 3)"
|
||||
/// // Prints "(3, 4)"
|
||||
/// // Prints "(4, 5)"
|
||||
///
|
||||
/// The resulting sequence is empty when called on an empty or single-element
|
||||
/// sequence.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func adjacentPairs() -> AdjacentPairsSequence<Self> {
|
||||
AdjacentPairsSequence(base: self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
/// Returns a collection of overlapping adjacent pairs of the elements of this
|
||||
/// collection.
|
||||
///
|
||||
/// In an `AdjacentPairsCollection`, the elements of the *i*th pair are the
|
||||
/// *i*th and *(i+1)*th elements of the underlying sequence. The following
|
||||
/// example uses the `adjacentPairs()` method to iterate over adjacent pairs
|
||||
/// of integers:
|
||||
///
|
||||
/// for pair in (1...5).adjacentPairs() {
|
||||
/// print(pair)
|
||||
/// }
|
||||
/// // Prints "(1, 2)"
|
||||
/// // Prints "(2, 3)"
|
||||
/// // Prints "(3, 4)"
|
||||
/// // Prints "(4, 5)"
|
||||
///
|
||||
/// The resulting collection is empty when called on an empty or
|
||||
/// single-element collection.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func adjacentPairs() -> AdjacentPairsCollection<Self> {
|
||||
AdjacentPairsCollection(base: self)
|
||||
}
|
||||
}
|
||||
|
||||
/// A sequence of adjacent pairs of elements built from an underlying sequence.
|
||||
///
|
||||
/// Use the `adjacentPairs()` method on a sequence to create an
|
||||
/// `AdjacentPairsSequence` instance.
|
||||
public struct AdjacentPairsSequence<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
/// Creates an instance that makes pairs of adjacent elements from `base`.
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsSequence {
|
||||
/// The iterator for an `AdjacentPairsSequence` or `AdjacentPairsCollection`
|
||||
/// instance.
|
||||
public struct Iterator {
|
||||
@usableFromInline
|
||||
internal var base: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal var previousElement: Base.Element?
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base.Iterator) {
|
||||
self.base = base
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsSequence.Iterator: IteratorProtocol {
|
||||
public typealias Element = (Base.Element, Base.Element)
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Element? {
|
||||
if previousElement == nil {
|
||||
previousElement = base.next()
|
||||
}
|
||||
|
||||
guard let previous = previousElement, let next = base.next() else {
|
||||
return nil
|
||||
}
|
||||
|
||||
previousElement = next
|
||||
return (previous, next)
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsSequence: Sequence {
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(base: base.makeIterator())
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var underestimatedCount: Int {
|
||||
Swift.max(0, base.underestimatedCount - 1)
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
/// A collection of adjacent pairs of elements built from an underlying
|
||||
/// collection.
|
||||
///
|
||||
/// Use the `adjacentPairs()` method on a collection to create an
|
||||
/// `AdjacentPairsCollection` instance.
|
||||
public struct AdjacentPairsCollection<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let secondBaseIndex: Base.Index
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
self.secondBaseIndex =
|
||||
base.isEmpty
|
||||
? base.endIndex
|
||||
: base.index(after: base.startIndex)
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsCollection {
|
||||
/// A position in an `AdjacentPairsCollection` instance.
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal var first: Base.Index
|
||||
|
||||
@usableFromInline
|
||||
internal var second: Base.Index
|
||||
|
||||
@inlinable
|
||||
internal init(first: Base.Index, second: Base.Index) {
|
||||
self.first = first
|
||||
self.second = second
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.first == rhs.first
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.first < rhs.first
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsCollection: Collection {
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(
|
||||
first: secondBaseIndex == base.endIndex ? base.endIndex : base.startIndex,
|
||||
second: secondBaseIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(first: base.endIndex, second: base.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> (Base.Element, Base.Element) {
|
||||
(base[position.first], base[position.second])
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i != endIndex, "Can't advance beyond endIndex")
|
||||
let next = base.index(after: i.second)
|
||||
return next == base.endIndex
|
||||
? endIndex
|
||||
: Index(first: i.second, second: next)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
guard distance != 0 else { return i }
|
||||
|
||||
guard
|
||||
let result = distance > 0
|
||||
? offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
: offsetBackward(i, by: -distance, limitedBy: startIndex)
|
||||
else { fatalError("Index out of bounds") }
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
guard distance != 0 else { return i }
|
||||
guard limit != i else { return nil }
|
||||
|
||||
if distance > 0 {
|
||||
let limit = limit > i ? limit : endIndex
|
||||
return offsetForward(i, by: distance, limitedBy: limit)
|
||||
} else {
|
||||
let limit = limit < i ? limit : startIndex
|
||||
return offsetBackward(i, by: -distance, limitedBy: limit)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ i: Index,
|
||||
by distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit > i)
|
||||
|
||||
let newFirst = base.index(
|
||||
i.second,
|
||||
offsetBy: distance - 1,
|
||||
limitedBy: limit.first)
|
||||
guard let newFirst, newFirst != base.endIndex
|
||||
else { return nil }
|
||||
|
||||
let newSecond = base.index(after: newFirst)
|
||||
|
||||
precondition(newSecond <= base.endIndex, "Can't advance beyond endIndex")
|
||||
return newSecond == base.endIndex
|
||||
? endIndex
|
||||
: Index(first: newFirst, second: newSecond)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ i: Index,
|
||||
by distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit < i)
|
||||
|
||||
let offset = i == endIndex ? 0 : 1
|
||||
let newSecond = base.index(
|
||||
i.first,
|
||||
offsetBy: -(distance - offset),
|
||||
limitedBy: limit.second)
|
||||
guard let newSecond
|
||||
else { return nil }
|
||||
|
||||
let newFirst = base.index(newSecond, offsetBy: -1)
|
||||
precondition(newFirst >= base.startIndex, "Can't move before startIndex")
|
||||
return Index(first: newFirst, second: newSecond)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
// While there's a 2-step gap between the `first` base index values in
|
||||
// `endIndex` and the penultimate index of this collection, the `second`
|
||||
// base index values are consistently one step apart throughout the
|
||||
// entire collection.
|
||||
base.distance(from: start.second, to: end.second)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
Swift.max(0, base.count - 1)
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(i != startIndex, "Can't offset before startIndex")
|
||||
let second =
|
||||
i == endIndex
|
||||
? base.index(before: base.endIndex)
|
||||
: i.first
|
||||
let first = base.index(before: second)
|
||||
return Index(first: first, second: second)
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsCollection: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
extension AdjacentPairsCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension AdjacentPairsCollection.Index: Hashable where Base.Index: Hashable {
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(first)
|
||||
}
|
||||
}
|
||||
+98
-154
@@ -10,286 +10,220 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A concatenation of two sequences with the same element type.
|
||||
public struct Chain2Sequence<Base1: Sequence, Base2: Sequence>
|
||||
where Base1.Element == Base2.Element {
|
||||
public struct Chain2<Base1: Sequence, Base2: Sequence> where Base1.Element == Base2.Element {
|
||||
/// The first sequence in this chain.
|
||||
@usableFromInline
|
||||
internal let base1: Base1
|
||||
@usableFromInline internal let base1: Base1
|
||||
|
||||
/// The second sequence in this chain.
|
||||
@usableFromInline
|
||||
internal let base2: Base2
|
||||
@usableFromInline internal let base2: Base2
|
||||
|
||||
@inlinable
|
||||
internal init(base1: Base1, base2: Base2) {
|
||||
@inlinable internal init(base1: Base1, base2: Base2) {
|
||||
self.base1 = base1
|
||||
self.base2 = base2
|
||||
}
|
||||
}
|
||||
|
||||
extension Chain2Sequence: Sequence {
|
||||
/// The iterator for a `Chain2Sequence` instance.
|
||||
extension Chain2: Sequence {
|
||||
/// The iterator for a `Chain2` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator1: Base1.Iterator
|
||||
@usableFromInline internal var iterator1: Base1.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal var iterator2: Base2.Iterator
|
||||
@usableFromInline internal var iterator2: Base2.Iterator
|
||||
|
||||
@inlinable
|
||||
internal init(_ concatenation: Chain2Sequence) {
|
||||
@inlinable internal init(_ concatenation: Chain2) {
|
||||
iterator1 = concatenation.base1.makeIterator()
|
||||
iterator2 = concatenation.base2.makeIterator()
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base1.Element? {
|
||||
iterator1.next() ?? iterator2.next()
|
||||
@inlinable public mutating func next() -> Base1.Element? {
|
||||
return iterator1.next() ?? iterator2.next()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(self)
|
||||
}
|
||||
@inlinable public func makeIterator() -> Iterator { Iterator(self) }
|
||||
}
|
||||
|
||||
extension Chain2Sequence: Collection
|
||||
where Base1: Collection, Base2: Collection {
|
||||
/// A position in a `Chain2Sequence` instance.
|
||||
extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
/// A position in a `Chain2` collection.
|
||||
public struct Index: Comparable {
|
||||
// The internal index representation, which can either be an index of the
|
||||
// first collection or the second. The `endIndex` of the first collection
|
||||
// is not to be used as a value - iterating over indices should go straight
|
||||
// from the penultimate index of the first collection to the start of the
|
||||
// second.
|
||||
@usableFromInline
|
||||
internal enum Representation: Equatable {
|
||||
@usableFromInline internal enum Representation: Equatable {
|
||||
case first(Base1.Index)
|
||||
case second(Base2.Index)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal let position: Representation
|
||||
@usableFromInline internal let position: Representation
|
||||
|
||||
/// Creates a new index into the first underlying collection.
|
||||
@inlinable
|
||||
internal init(first i: Base1.Index) {
|
||||
position = .first(i)
|
||||
}
|
||||
@inlinable internal init(first i: Base1.Index) { position = .first(i) }
|
||||
|
||||
/// Creates a new index into the second underlying collection.
|
||||
@inlinable
|
||||
internal init(second i: Base2.Index) {
|
||||
position = .second(i)
|
||||
}
|
||||
@inlinable internal init(second i: Base2.Index) { position = .second(i) }
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
switch (lhs.position, rhs.position) {
|
||||
case (.first, .second):
|
||||
return true
|
||||
case (.second, .first):
|
||||
return false
|
||||
case (.first(let l), .first(let r)):
|
||||
return l < r
|
||||
case (.second(let l), .second(let r)):
|
||||
return l < r
|
||||
case (.first, .second): return true
|
||||
case (.second, .first): return false
|
||||
case let (.first(l), .first(r)): return l < r
|
||||
case let (.second(l), .second(r)): return l < r
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts an index of `Base1` to the corresponding `Index` by mapping
|
||||
/// `base1.endIndex` to `base2.startIndex`.
|
||||
@inlinable
|
||||
internal func normalizeIndex(_ i: Base1.Index) -> Index {
|
||||
@inlinable internal func normalizeIndex(_ i: Base1.Index) -> Index {
|
||||
i == base1.endIndex ? Index(second: base2.startIndex) : Index(first: i)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
@inlinable public var startIndex: Index {
|
||||
// if `base1` is empty, this will return `base2.startIndex` - if `base2` is
|
||||
// also empty, this will correctly equal `base2.endIndex`
|
||||
normalizeIndex(base1.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(second: base2.endIndex)
|
||||
}
|
||||
@inlinable public var endIndex: Index { return Index(second: base2.endIndex) }
|
||||
|
||||
@inlinable
|
||||
public subscript(i: Index) -> Base1.Element {
|
||||
@inlinable public subscript(i: Index) -> Base1.Element {
|
||||
switch i.position {
|
||||
case .first(let i):
|
||||
return base1[i]
|
||||
case .second(let i):
|
||||
return base2[i]
|
||||
case let .first(i): return base1[i]
|
||||
case let .second(i): return base2[i]
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
@inlinable public func index(after i: Index) -> Index {
|
||||
switch i.position {
|
||||
case .first(let i):
|
||||
case let .first(i):
|
||||
assert(i != base1.endIndex)
|
||||
return normalizeIndex(base1.index(after: i))
|
||||
case .second(let i):
|
||||
return Index(second: base2.index(after: i))
|
||||
case let .second(i): return Index(second: base2.index(after: i))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
@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)
|
||||
return distance > 0 ? offsetForward(i, by: distance) : offsetBackward(i, by: -distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@inlinable public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index?
|
||||
{
|
||||
if distance >= 0 {
|
||||
return limit >= i
|
||||
? offsetForward(i, by: distance, limitedBy: limit)
|
||||
: offsetForward(i, by: distance)
|
||||
? offsetForward(i, by: distance, limitedBy: limit) : offsetForward(i, by: distance)
|
||||
} else {
|
||||
return limit <= i
|
||||
? offsetBackward(i, by: -distance, limitedBy: limit)
|
||||
: offsetBackward(i, by: -distance)
|
||||
? offsetBackward(i, by: -distance, limitedBy: limit) : offsetBackward(i, by: -distance)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
@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") }
|
||||
@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 distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@inlinable internal func offsetForward(_ i: Index, by distance: Int, limitedBy limit: Index)
|
||||
-> Index?
|
||||
{
|
||||
assert(distance >= 0)
|
||||
assert(limit >= i)
|
||||
|
||||
switch (i.position, limit.position) {
|
||||
case (.first(let i), .first(let limit)):
|
||||
return base1.index(i, offsetBy: distance, limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
case let (.first(i), .first(limit)):
|
||||
return base1.index(i, offsetBy: distance, limitedBy: limit).map(Index.init(first:))
|
||||
|
||||
case (.first(let i), .second(let limit)):
|
||||
guard
|
||||
let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex)
|
||||
else {
|
||||
case let (.first(i), .second(limit)):
|
||||
if let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) {
|
||||
// the offset stays within the bounds of `base1`
|
||||
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: distance - d, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
return base2.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit).map(
|
||||
Index.init(second:))
|
||||
}
|
||||
// the offset stays within the bounds of `base1`
|
||||
return normalizeIndex(j)
|
||||
|
||||
case (.second, .first):
|
||||
// impossible because `limit >= i`
|
||||
fatalError()
|
||||
|
||||
case (.second(let i), .second(let limit)):
|
||||
return base2.index(i, offsetBy: distance, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
case let (.second(i), .second(limit)):
|
||||
return base2.index(i, offsetBy: distance, limitedBy: limit).map(Index.init(second:))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ i: Index,
|
||||
by distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@inlinable internal func offsetBackward(_ i: Index, by distance: Int, limitedBy limit: Index)
|
||||
-> Index?
|
||||
{
|
||||
assert(distance >= 0)
|
||||
assert(limit <= i)
|
||||
|
||||
switch (i.position, limit.position) {
|
||||
case (.first(let i), .first(let limit)):
|
||||
return base1.index(i, offsetBy: -distance, limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
case let (.first(i), .first(limit)):
|
||||
return base1.index(i, offsetBy: -distance, limitedBy: limit).map(Index.init(first:))
|
||||
|
||||
case (.first, .second):
|
||||
// impossible because `limit <= i`
|
||||
fatalError()
|
||||
|
||||
case (.second(let i), .first(let limit)):
|
||||
guard
|
||||
let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex)
|
||||
else {
|
||||
case let (.second(i), .first(limit)):
|
||||
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: -(distance - d), limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
return base1.index(base1.endIndex, offsetBy: -(distance - d), limitedBy: limit).map(
|
||||
Index.init(first:))
|
||||
}
|
||||
// the offset stays within the bounds of `base2`
|
||||
return Index(second: j)
|
||||
|
||||
case (.second(let i), .second(let limit)):
|
||||
case let (.second(i), .second(limit)):
|
||||
// `limit` is relevant, so `base1` cannot be reached
|
||||
return base2.index(i, offsetBy: -distance, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
return base2.index(i, offsetBy: -distance, limitedBy: limit).map(Index.init(second:))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
@inlinable public func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (start.position, end.position) {
|
||||
case (.first(let i), .first(let j)):
|
||||
return base1.distance(from: i, to: j)
|
||||
case (.second(let i), .second(let j)):
|
||||
return base2.distance(from: i, to: j)
|
||||
case (.first(let i), .second(let j)):
|
||||
case let (.first(i), .first(j)): return base1.distance(from: i, to: j)
|
||||
case let (.second(i), .second(j)): return base2.distance(from: i, to: j)
|
||||
case let (.first(i), .second(j)):
|
||||
return base1.distance(from: i, to: base1.endIndex)
|
||||
+ base2.distance(from: base2.startIndex, to: j)
|
||||
case (.second(let i), .first(let j)):
|
||||
case let (.second(i), .first(j)):
|
||||
return base2.distance(from: i, to: base2.startIndex)
|
||||
+ base1.distance(from: base1.endIndex, to: j)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Chain2Sequence: BidirectionalCollection
|
||||
extension Chain2: BidirectionalCollection
|
||||
where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
@inlinable public func index(before i: Index) -> Index {
|
||||
assert(i != startIndex, "Can't advance before startIndex")
|
||||
switch i.position {
|
||||
case .first(let i):
|
||||
return Index(first: base1.index(before: i))
|
||||
case .second(let i):
|
||||
case let .first(i): return Index(first: base1.index(before: i))
|
||||
case let .second(i):
|
||||
return i == base2.startIndex
|
||||
? Index(first: base1.index(before: base1.endIndex))
|
||||
: Index(second: base2.index(before: i))
|
||||
? Index(first: base1.index(before: base1.endIndex)) : Index(second: base2.index(before: i))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Chain2Sequence: RandomAccessCollection
|
||||
extension Chain2: RandomAccessCollection
|
||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
@@ -322,7 +256,17 @@ where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||
/// then over the elements of `s2`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2Sequence<S1, S2> {
|
||||
Chain2Sequence(base1: s1, base2: s2)
|
||||
@inlinable public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2<S1, S2> {
|
||||
Chain2(base1: s1, base2: s2)
|
||||
}
|
||||
|
||||
// MARK: - Deprecations
|
||||
|
||||
@available(*, deprecated, renamed: "Chain2") public typealias Chain = Chain2
|
||||
|
||||
extension Sequence {
|
||||
@available(*, deprecated, message: "Use the chain(_:_:) function, instead.")
|
||||
public func chained<S: Sequence>(with other: S) -> Chain2<Self, S> where Element == S.Element {
|
||||
Chain2(base1: self, base2: other)
|
||||
}
|
||||
}
|
||||
+166
-683
File diff suppressed because it is too large.
Load diff
@@ -10,62 +10,42 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection wrapper that generates combinations of a base collection.
|
||||
public struct CombinationsSequence<Base: Collection> {
|
||||
public struct Combinations<Base: Collection> {
|
||||
/// The collection to iterate over for combinations.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let baseCount: Int
|
||||
@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>?
|
||||
@usableFromInline internal let kRange: Range<Int>?
|
||||
|
||||
/// Initializes a `CombinationsSequence` for all combinations of `base` of
|
||||
/// size `k`.
|
||||
///
|
||||
/// 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.
|
||||
@inlinable
|
||||
internal init(_ base: Base, k: Int) {
|
||||
self.init(base, kRange: k...k)
|
||||
}
|
||||
@inlinable internal init(_ base: Base, k: Int) { self.init(base, kRange: k...k) }
|
||||
|
||||
/// Initializes a `CombinationsSequence` for all combinations of `base` of
|
||||
/// sizes within a given range.
|
||||
///
|
||||
/// 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.
|
||||
@inlinable
|
||||
internal init<R: RangeExpression>(
|
||||
_ base: Base,
|
||||
kRange: R
|
||||
) where R.Bound == Int {
|
||||
@inlinable internal init<R: RangeExpression>(_ base: Base, kRange: R) where R.Bound == Int {
|
||||
let range = kRange.relative(to: 0 ..< .max)
|
||||
self.base = base
|
||||
let baseCount = base.count
|
||||
self.baseCount = baseCount
|
||||
let upperBound = baseCount + 1
|
||||
self.kRange =
|
||||
range.lowerBound < upperBound
|
||||
? range.clamped(to: 0..<upperBound)
|
||||
: nil
|
||||
self.kRange = range.lowerBound < upperBound ? range.clamped(to: 0..<upperBound) : nil
|
||||
}
|
||||
|
||||
/// The total number of combinations.
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
@inlinable public var count: Int {
|
||||
guard let k = self.kRange else { return 0 }
|
||||
let n = baseCount
|
||||
if k == 0..<(n + 1) {
|
||||
return 1 << n
|
||||
}
|
||||
if k == 0..<(n + 1) { return 1 << n }
|
||||
|
||||
func binomial(n: Int, k: Int) -> Int {
|
||||
switch k {
|
||||
@@ -76,41 +56,27 @@ public struct CombinationsSequence<Base: Collection> {
|
||||
}
|
||||
}
|
||||
|
||||
return k.map {
|
||||
binomial(n: n, k: $0)
|
||||
}.reduce(0, +)
|
||||
return k.map { binomial(n: n, k: $0) }.reduce(0, +)
|
||||
}
|
||||
|
||||
/// The total number of combinations.
|
||||
@inlinable
|
||||
public var underestimatedCount: Int { count }
|
||||
}
|
||||
|
||||
extension CombinationsSequence: Sequence {
|
||||
/// The iterator for a `CombinationsSequence` instance.
|
||||
extension Combinations: Sequence {
|
||||
/// The iterator for a `Combinations` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
@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>
|
||||
@usableFromInline internal var kRange: Range<Int>
|
||||
|
||||
/// Whether or not iteration is finished (`kRange` is empty).
|
||||
@inlinable
|
||||
internal var isFinished: Bool {
|
||||
kRange.isEmpty
|
||||
}
|
||||
/// Whether or not iteration is finished (`kRange` is empty)
|
||||
@inlinable internal var isFinished: Bool { return kRange.isEmpty }
|
||||
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
@usableFromInline internal var indexes: [Base.Index]
|
||||
|
||||
@inlinable
|
||||
internal init(_ combinations: CombinationsSequence) {
|
||||
@inlinable internal init(_ combinations: Combinations) {
|
||||
self.base = combinations.base
|
||||
self.kRange = combinations.kRange ?? 0..<0
|
||||
self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound))
|
||||
@@ -134,8 +100,7 @@ extension CombinationsSequence: Sequence {
|
||||
/// [2, 3, 4] *
|
||||
/// // Can't advance without needing to go past `base.endIndex`,
|
||||
/// // so the iteration is finished.
|
||||
@inlinable
|
||||
internal mutating func advance() {
|
||||
@inlinable internal mutating func advance() {
|
||||
/// Advances `kRange` by incrementing its `lowerBound` until the range is
|
||||
/// empty, when iteration is finished.
|
||||
func advanceKRange() {
|
||||
@@ -171,29 +136,22 @@ extension CombinationsSequence: Sequence {
|
||||
base.formIndex(after: &indexes[j])
|
||||
for k in indexes.indices[(j + 1)...] {
|
||||
indexes[k] = base.index(after: indexes[k - 1])
|
||||
if indexes[k] == base.endIndex {
|
||||
break
|
||||
}
|
||||
if indexes[k] == base.endIndex { break }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> [Base.Element]? {
|
||||
@inlinable public mutating func next() -> [Base.Element]? {
|
||||
guard !isFinished else { return nil }
|
||||
defer { advance() }
|
||||
return indexes.map { i in base[i] }
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(self)
|
||||
}
|
||||
public func makeIterator() -> Iterator { Iterator(self) }
|
||||
}
|
||||
|
||||
extension CombinationsSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// combinations(ofCount:)
|
||||
@@ -256,19 +214,13 @@ extension Collection {
|
||||
/// limited range is empty, the resulting sequence has no elements.
|
||||
///
|
||||
/// - Parameter kRange: The range of numbers of elements to include in each
|
||||
/// combination.
|
||||
/// - Returns: A sequence of the combinations of this collection's
|
||||
/// elements, for all sizes in `kRange`, from smallest to largest.
|
||||
/// combination.
|
||||
///
|
||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||
/// is the number of elements in the base collection, since
|
||||
/// `CombinationsSequence` accesses the `count` of the base collection.
|
||||
@inlinable
|
||||
public func combinations<R: RangeExpression>(
|
||||
ofCount kRange: R
|
||||
) -> CombinationsSequence<Self> where R.Bound == Int {
|
||||
CombinationsSequence(self, kRange: kRange)
|
||||
}
|
||||
/// is the number of elements in the base collection, since `Combinations`
|
||||
/// accesses the `count` of the base collection.
|
||||
@inlinable public func combinations<R: RangeExpression>(ofCount kRange: R) -> 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.
|
||||
@@ -295,17 +247,12 @@ extension Collection {
|
||||
/// the resulting sequence has no elements.
|
||||
///
|
||||
/// - Parameter k: The number of elements to include in each combination.
|
||||
/// - Returns: A sequence of the combinations of this collection's
|
||||
/// elements.
|
||||
///
|
||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||
/// is the number of elements in the base collection, since
|
||||
/// `CombinationsSequence` accesses the `count` of the base collection.
|
||||
@inlinable
|
||||
public func combinations(ofCount k: Int) -> CombinationsSequence<Self> {
|
||||
precondition(
|
||||
k >= 0,
|
||||
"Can't have combinations with a negative number of elements.")
|
||||
return CombinationsSequence(self, k: k)
|
||||
/// is the number of elements in the base collection, since `Combinations`
|
||||
/// accesses the `count` of the base collection.
|
||||
@inlinable public func combinations(ofCount k: Int) -> Combinations<Self> {
|
||||
precondition(k >= 0, "Can't have combinations with a negative number of elements.")
|
||||
return Combinations(self, k: k)
|
||||
}
|
||||
}
|
||||
@@ -9,30 +9,19 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A `Sequence` that iterates over every non-nil element from the original
|
||||
/// `Sequence`.
|
||||
public struct CompactedSequence<Base: Sequence, Element>: Sequence
|
||||
where Base.Element == Element? {
|
||||
/// 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
|
||||
@usableFromInline let base: Base
|
||||
|
||||
@inlinable
|
||||
init(base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
@inlinable init(base: Base) { self.base = base }
|
||||
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
var base: Base.Iterator
|
||||
@usableFromInline var base: Base.Iterator
|
||||
|
||||
@inlinable
|
||||
init(base: Base.Iterator) {
|
||||
self.base = base
|
||||
}
|
||||
@inlinable init(base: Base.Iterator) { self.base = base }
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Element? {
|
||||
@inlinable public mutating func next() -> Element? {
|
||||
while let wrapped = base.next() {
|
||||
guard let some = wrapped else { continue }
|
||||
return some
|
||||
@@ -41,17 +30,13 @@ where Base.Element == Element? {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(base: base.makeIterator())
|
||||
}
|
||||
@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`.
|
||||
///
|
||||
/// Produces the same result as `c.compactMap { $0 }`.
|
||||
/// 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() {
|
||||
@@ -66,95 +51,67 @@ extension Sequence {
|
||||
/// `Sequence`.
|
||||
///
|
||||
/// Complexity: O(1)
|
||||
@inlinable
|
||||
public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
|
||||
where Element == Unwrapped? {
|
||||
CompactedSequence(base: self)
|
||||
}
|
||||
@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`.
|
||||
/// 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
|
||||
@usableFromInline let base: Base
|
||||
|
||||
@inlinable
|
||||
init(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
|
||||
@usableFromInline let base: Base.Index
|
||||
|
||||
@inlinable
|
||||
init(base: Base.Index) {
|
||||
self.base = base
|
||||
}
|
||||
@inlinable init(base: Base.Index) { self.base = base }
|
||||
}
|
||||
|
||||
public var startIndex: Index
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index { Index(base: base.endIndex) }
|
||||
@inlinable public var endIndex: Index { Index(base: base.endIndex) }
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Element {
|
||||
// swift-format-ignore: NeverForceUnwrap
|
||||
// All indices are only for non-`nil` elements.
|
||||
base[position.base]!
|
||||
}
|
||||
@inlinable public subscript(position: Index) -> Element { base[position.base]! }
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
@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 }
|
||||
guard let idx = base[baseIdx...].firstIndex(where: { $0 != nil }) else { return endIndex }
|
||||
return Index(base: idx)
|
||||
}
|
||||
}
|
||||
|
||||
extension CompactedCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection {
|
||||
extension CompactedCollection: BidirectionalCollection where Base: BidirectionalCollection {
|
||||
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
@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") }
|
||||
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
|
||||
}
|
||||
@inlinable public static func < (lhs: CompactedCollection.Index, rhs: CompactedCollection.Index)
|
||||
-> Bool
|
||||
{ lhs.base < rhs.base }
|
||||
}
|
||||
|
||||
extension CompactedCollection.Index: Hashable
|
||||
where Base.Index: Hashable {}
|
||||
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`.
|
||||
///
|
||||
/// Produces the same result as `c.compactMap { $0 }`.
|
||||
/// 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() {
|
||||
@@ -168,21 +125,17 @@ extension Collection {
|
||||
/// element and iterates over every non-nil element from the original
|
||||
/// `Collection`.
|
||||
///
|
||||
/// Complexity: O(*n*) where *n* is the number of elements in the
|
||||
/// Complexity: O(*n*) where *n* is the number of elements in the
|
||||
/// original `Collection`.
|
||||
@inlinable
|
||||
public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
|
||||
where Element == Unwrapped? {
|
||||
CompactedCollection(base: self)
|
||||
}
|
||||
@inlinable public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
|
||||
where Element == Unwrapped? { CompactedCollection(base: self) }
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Protocol Conformances
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension CompactedSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension CompactedSequence: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
extension CompactedCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension CompactedCollection: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension CompactedCollection: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
||||
@@ -10,159 +10,113 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection wrapper that repeats the elements of a base collection.
|
||||
public struct CycledSequence<Base: Collection> {
|
||||
public struct Cycle<Base: Collection> {
|
||||
/// The collection to repeat.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
@inlinable internal init(base: Base) { self.base = base }
|
||||
}
|
||||
|
||||
extension CycledSequence: Sequence {
|
||||
/// The iterator for a `CycledSequence` instance.
|
||||
extension Cycle: Sequence {
|
||||
/// The iterator for a `Cycle` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal var current: Base.Index
|
||||
@usableFromInline internal var current: Base.Index
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
@inlinable internal init(base: Base) {
|
||||
self.base = base
|
||||
self.current = base.startIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element? {
|
||||
@inlinable public mutating func next() -> Base.Element? {
|
||||
guard !base.isEmpty else { return nil }
|
||||
|
||||
if current == base.endIndex {
|
||||
current = base.startIndex
|
||||
}
|
||||
if current == base.endIndex { current = base.startIndex }
|
||||
|
||||
defer { base.formIndex(after: ¤t) }
|
||||
return base[current]
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(base: base)
|
||||
}
|
||||
@inlinable public func makeIterator() -> Iterator { Iterator(base: base) }
|
||||
}
|
||||
|
||||
extension CycledSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
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 CycledTimesCollection<Base: Collection> {
|
||||
/// A `Product2Sequence` instance for iterating the base collection.
|
||||
@usableFromInline
|
||||
internal let product: Product2Sequence<Range<Int>, Base>
|
||||
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 = Product2Sequence(0..<times, base)
|
||||
}
|
||||
@inlinable internal init(base: Base, times: Int) { self.product = Product2(0..<times, base) }
|
||||
}
|
||||
|
||||
extension CycledTimesCollection: Collection {
|
||||
extension FiniteCycle: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
|
||||
extension FiniteCycle: Collection {
|
||||
|
||||
public typealias Element = Base.Element
|
||||
|
||||
public struct Index: Comparable {
|
||||
/// The index corresponding to the `Product2Sequence` index at this
|
||||
/// position.
|
||||
@usableFromInline
|
||||
internal let productIndex: Product2Sequence<Range<Int>, Base>.Index
|
||||
/// The index corresponding to the Product2 index at this position.
|
||||
@usableFromInline internal let productIndex: Product2<Range<Int>, Base>.Index
|
||||
|
||||
@inlinable
|
||||
internal init(_ productIndex: Product2Sequence<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 {
|
||||
@inlinable public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.productIndex == rhs.productIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.productIndex < rhs.productIndex
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(product.startIndex)
|
||||
}
|
||||
@inlinable public var startIndex: Index { Index(product.startIndex) }
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(product.endIndex)
|
||||
}
|
||||
@inlinable public var endIndex: Index { Index(product.endIndex) }
|
||||
|
||||
@inlinable
|
||||
public subscript(_ index: Index) -> Element {
|
||||
product[index.productIndex].1
|
||||
}
|
||||
@inlinable public subscript(_ index: Index) -> Element { product[index.productIndex].1 }
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
@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 {
|
||||
@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 {
|
||||
@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? {
|
||||
@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)
|
||||
i.productIndex, offsetBy: distance, limitedBy: limit.productIndex)
|
||||
else { return nil }
|
||||
return Index(productIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
product.count
|
||||
}
|
||||
@inlinable public var count: Int { product.count }
|
||||
}
|
||||
|
||||
extension CycledTimesCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
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 CycledTimesCollection: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
extension CycledTimesCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension FiniteCycle: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// cycled()
|
||||
@@ -194,10 +148,7 @@ extension Collection {
|
||||
/// forever.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func cycled() -> CycledSequence<Self> {
|
||||
CycledSequence(base: self)
|
||||
}
|
||||
@inlinable public func cycled() -> Cycle<Self> { Cycle(base: self) }
|
||||
|
||||
/// Returns a sequence that repeats the elements of this collection the
|
||||
/// specified number of times.
|
||||
@@ -216,8 +167,7 @@ extension Collection {
|
||||
/// times.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func cycled(times: Int) -> CycledTimesCollection<Self> {
|
||||
CycledTimesCollection(base: self, times: times)
|
||||
@inlinable public func cycled(times: Int) -> FiniteCycle<Self> {
|
||||
FiniteCycle(base: self, times: times)
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
# ``Algorithms``
|
||||
|
||||
**Swift Algorithms** is an open-source package of sequence and collection algorithms,
|
||||
along with their related types.
|
||||
|
||||
## Overview
|
||||
|
||||
The Algorithms package provides a variety of sequence and collection operations, letting you cycle over a collection's elements, find combinations and permutations, create a random sample, and more.
|
||||
|
||||
For example, the package includes a group of "chunking" methods, each of which breaks a collection into consecutive subsequences. One version tests adjacent elements to find the breaking point between chunks — you can use it to quickly separate an array into ascending runs:
|
||||
|
||||
```swift
|
||||
let numbers = [10, 20, 30, 10, 40, 40, 10, 20]
|
||||
let chunks = numbers.chunked(by: { $0 <= $1 })
|
||||
// [[10, 20, 30], [10, 40, 40], [10, 20]]
|
||||
```
|
||||
|
||||
Another version looks for a change in the transformation of each successive value. You can use that to separate a list of names into groups by the first character:
|
||||
|
||||
```swift
|
||||
let names = ["Cassie", "Chloe", "Jasmine", "Jordan", "Taylor"]
|
||||
let chunks = names.chunked(on: \.first)
|
||||
// [["Cassie", "Chloe"], ["Jasmine", "Jordan"], ["Taylor"]]
|
||||
```
|
||||
|
||||
Explore more chunking methods and the remainder of the Algorithms package, grouped in the following topics.
|
||||
|
||||
## Topics
|
||||
|
||||
- <doc:CombinationsPermutations>
|
||||
- <doc:SlicingSplitting>
|
||||
- <doc:Chunking>
|
||||
- <doc:Joining>
|
||||
- <doc:Extending>
|
||||
- <doc:Trimming>
|
||||
- <doc:Keying>
|
||||
- <doc:Sampling>
|
||||
- <doc:MinAndMax>
|
||||
- <doc:Selecting>
|
||||
- <doc:Filtering>
|
||||
- <doc:Reductions>
|
||||
- <doc:Partitioning>
|
||||
@@ -1,40 +0,0 @@
|
||||
# Chunking
|
||||
|
||||
Break collections into consecutive chunks by length, count, or based on closure-based logic.
|
||||
|
||||
## Overview
|
||||
|
||||
_Chunking_ is the process of breaking a collection into consecutive subsequences, without dropping or duplicating any of the collection's elements. After chunking a collection, joining the resulting subsequences produces the original collection of elements, unlike _splitting_, which consumes the separator element(s).
|
||||
|
||||
```swift
|
||||
let names = ["Ji-sun", "Jin-su", "Min-jae", "Young-ho"]
|
||||
let evenlyChunked = names.chunks(ofCount: 2)
|
||||
// ~ [["Ji-sun", "Jin-su"], ["Min-jae", "Young-ho"]]
|
||||
|
||||
let chunkedByFirstLetter = names.chunked(on: \.first)
|
||||
// equivalent to [("J", ["Ji-sun", "Jin-su"]), ("M", ["Min-jae"]), ("Y", ["Young-ho"])]
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Chunking a Collection by Count
|
||||
|
||||
- ``Swift/Collection/chunks(ofCount:)``
|
||||
- ``Swift/Collection/evenlyChunked(in:)``
|
||||
|
||||
### Chunking a Collection by Predicate
|
||||
|
||||
- ``Swift/Collection/chunked(by:)``
|
||||
- ``Swift/LazySequenceProtocol/chunked(by:)``
|
||||
|
||||
### Chunking a Collection by Subject
|
||||
|
||||
- ``Swift/Collection/chunked(on:)``
|
||||
- ``Swift/LazySequenceProtocol/chunked(on:)``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``ChunkedByCollection``
|
||||
- ``ChunkedOnCollection``
|
||||
- ``ChunksOfCountCollection``
|
||||
- ``EvenlyChunkedCollection``
|
||||
@@ -1,32 +0,0 @@
|
||||
# Combinations and Permutations
|
||||
|
||||
Find the combinations and permutations of any collection's elements,
|
||||
or the product of two different collections.
|
||||
|
||||
## Topics
|
||||
|
||||
### Combinations
|
||||
|
||||
- ``Swift/Collection/combinations(ofCount:)-26o4x``
|
||||
- ``Swift/Collection/combinations(ofCount:)-53jql``
|
||||
|
||||
### Permutations
|
||||
|
||||
- ``Swift/Collection/permutations(ofCount:)-7rc99``
|
||||
- ``Swift/Collection/permutations(ofCount:)-5zvhn``
|
||||
|
||||
### Unique Permutations
|
||||
|
||||
- ``Swift/Collection/uniquePermutations(ofCount:)-2extq``
|
||||
- ``Swift/Collection/uniquePermutations(ofCount:)-48r1k``
|
||||
|
||||
### Product
|
||||
|
||||
- ``product(_:_:)``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``CombinationsSequence``
|
||||
- ``PermutationsSequence``
|
||||
- ``UniquePermutationsSequence``
|
||||
- ``Product2Sequence``
|
||||
@@ -1,14 +0,0 @@
|
||||
# DeprecatedScan
|
||||
|
||||
These methods are deprecated; use the `reductions` family of methods instead.
|
||||
|
||||
See: <doc:Reductions>
|
||||
|
||||
## Topics
|
||||
|
||||
- ``Swift/Sequence/scan(_:)``
|
||||
- ``Swift/Sequence/scan(_:_:)``
|
||||
- ``Swift/Sequence/scan(into:_:)``
|
||||
- ``Swift/LazySequenceProtocol/scan(_:)``
|
||||
- ``Swift/LazySequenceProtocol/scan(_:_:)``
|
||||
- ``Swift/LazySequenceProtocol/scan(into:_:)``
|
||||
@@ -1,42 +0,0 @@
|
||||
# Extending
|
||||
|
||||
Chain two collections end-to-end,
|
||||
or repeat a collection forever or a specific number of times.
|
||||
|
||||
## Overview
|
||||
|
||||
_Chaining_ two collections
|
||||
|
||||
```swift
|
||||
let letters = chain("abcd", "EFGH")
|
||||
// String(letters) == "abcdEFGH"
|
||||
|
||||
for (num, letter) in zip((1...3).cycled(), letters) {
|
||||
print(num, letter)
|
||||
}
|
||||
// 1 a
|
||||
// 2 b
|
||||
// 3 c
|
||||
// 1 d
|
||||
// 2 E
|
||||
// 3 F
|
||||
// 1 G
|
||||
// 2 H
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Chaining Two Collections
|
||||
|
||||
- ``chain(_:_:)``
|
||||
|
||||
### Cycling a Collection
|
||||
|
||||
- ``Swift/Collection/cycled()``
|
||||
- ``Swift/Collection/cycled(times:)``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``Chain2Sequence``
|
||||
- ``CycledSequence``
|
||||
- ``CycledTimesCollection``
|
||||
@@ -1,41 +0,0 @@
|
||||
# Filtering
|
||||
|
||||
Remove duplicated elements or strip the `nil` values from a sequence or collection.
|
||||
|
||||
## Overview
|
||||
|
||||
Use the _uniquing_ methods to remove duplicates from a sequence or collection, or to remove elements that have a duplicated property.
|
||||
|
||||
```swift
|
||||
let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1]
|
||||
|
||||
let unique = numbers.uniqued()
|
||||
// Array(unique) == [1, 2, 3]
|
||||
```
|
||||
|
||||
The `compacted()` method removes all `nil` values from a sequence or collection of optionals:
|
||||
|
||||
```swift
|
||||
let array: [Int?] = [10, nil, 30, nil, 2, 3, nil, 5]
|
||||
let withNoNils = array.compacted()
|
||||
// Array(withNoNils) == [10, 30, 2, 3, 5]
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Uniquing Elements
|
||||
|
||||
- ``Swift/Sequence/uniqued()``
|
||||
- ``Swift/Sequence/uniqued(on:)``
|
||||
- ``Swift/LazySequenceProtocol/uniqued(on:)``
|
||||
|
||||
### Filtering out `nil` Elements
|
||||
|
||||
- ``Swift/Collection/compacted()``
|
||||
- ``Swift/Sequence/compacted()``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``UniquedSequence``
|
||||
- ``CompactedSequence``
|
||||
- ``CompactedCollection``
|
||||
@@ -1,35 +0,0 @@
|
||||
# Joining
|
||||
|
||||
Join the parts of a collection of collections,
|
||||
providing a connecting element or collection,
|
||||
or a closure that produces the connector.
|
||||
|
||||
## Topics
|
||||
|
||||
### Joining by an Element
|
||||
|
||||
- ``Swift/Sequence/joined(by:)-6mrf9``
|
||||
- ``Swift/Sequence/joined(by:)-9hyaf``
|
||||
- ``Swift/Collection/joined(by:)-430ue``
|
||||
- ``Swift/LazySequenceProtocol/joined(by:)-3yjw0``
|
||||
- ``Swift/LazySequenceProtocol/joined(by:)-47xvy``
|
||||
|
||||
### Joining by a Collection
|
||||
|
||||
- ``Swift/Sequence/joined(by:)-62j1h``
|
||||
- ``Swift/Sequence/joined(by:)-9b108``
|
||||
- ``Swift/Collection/joined(by:)-28n3b``
|
||||
- ``Swift/LazySequenceProtocol/joined(by:)-4neii``
|
||||
- ``Swift/LazySequenceProtocol/joined(by:)-49xws``
|
||||
|
||||
### Interspersing Elements
|
||||
|
||||
- ``Swift/Sequence/interspersed(with:)``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``JoinedBySequence``
|
||||
- ``JoinedByCollection``
|
||||
- ``JoinedByClosureSequence``
|
||||
- ``JoinedByClosureCollection``
|
||||
- ``InterspersedSequence``
|
||||
@@ -1,14 +0,0 @@
|
||||
# Keying and Grouping
|
||||
|
||||
Convert a sequence to a dictionary, providing keys to individual elements or to use as grouping values.
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating a Keyed Dictionary
|
||||
|
||||
- ``Swift/Sequence/keyed(by:)``
|
||||
- ``Swift/Sequence/keyed(by:resolvingConflictsWith:)``
|
||||
|
||||
### Grouping Elements by Key
|
||||
|
||||
- ``Swift/Sequence/grouped(by:)``
|
||||
@@ -1,23 +0,0 @@
|
||||
# Finding the Minimum and Maximum
|
||||
|
||||
Find the minimum and maximum elements simultaneously,
|
||||
or a specific number of elements at the minimum and maximum.
|
||||
|
||||
## Topics
|
||||
|
||||
### Finding Minimum or Maximum Elements
|
||||
|
||||
- ``Swift/Sequence/min(count:)``
|
||||
- ``Swift/Collection/min(count:)``
|
||||
- ``Swift/Sequence/min(count:sortedBy:)``
|
||||
- ``Swift/Collection/min(count:sortedBy:)``
|
||||
- ``Swift/Sequence/max(count:)``
|
||||
- ``Swift/Collection/max(count:)``
|
||||
- ``Swift/Sequence/max(count:sortedBy:)``
|
||||
- ``Swift/Collection/max(count:sortedBy:)``
|
||||
|
||||
### Finding the Minimum and Maximum Elements Simultaneously
|
||||
|
||||
- ``Swift/Sequence/minAndMax()``
|
||||
- ``Swift/Sequence/minAndMax(by:)``
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
# Partitioning and Rotating
|
||||
|
||||
Partition a collection according to a unary predicate,
|
||||
rotate a collection around a particular index,
|
||||
or find the index where a collection is already partitioned.
|
||||
|
||||
## Overview
|
||||
|
||||
A _stable partition_ maintains the relative order of elements within both partitions.
|
||||
|
||||
```swift
|
||||
// partition(by:) - unstable ordering
|
||||
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
let p1 = numbers.partition(by: { $0.isMultiple(of: 20) })
|
||||
// p1 == 4
|
||||
// numbers == [10, 70, 30, 50, 40, 60, 20, 80]
|
||||
// ^ start of second partition
|
||||
|
||||
// stablePartition(by:) - maintains relative ordering
|
||||
numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
let p2 = numbers.stablePartition(by: { $0.isMultiple(of: 20) })
|
||||
// p2 == 4
|
||||
// numbers == [10, 30, 50, 70, 20, 40, 60, 80]
|
||||
// ^ start of second partition
|
||||
```
|
||||
|
||||
Use the `rotate` method to shift the elements of a collection to start at a new position, moving the displaced elements to the end:
|
||||
|
||||
```swift
|
||||
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
let p = numbers.rotate(toStartAt: 2)
|
||||
// numbers == [30, 40, 50, 60, 70, 80, 10, 20]
|
||||
// p == 6 -- numbers[p] == 10
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Stable Partition
|
||||
|
||||
- ``Swift/MutableCollection/stablePartition(by:)``
|
||||
- ``Swift/MutableCollection/stablePartition(subrange:by:)``
|
||||
- ``Swift/Sequence/partitioned(by:)``
|
||||
- ``Swift/Collection/partitioned(by:)``
|
||||
|
||||
### Partition of Subranges
|
||||
|
||||
- ``Swift/MutableCollection/partition(subrange:by:)-5vdh7``
|
||||
- ``Swift/MutableCollection/partition(subrange:by:)-4gpqz``
|
||||
|
||||
### Finding a Partition Index
|
||||
|
||||
- ``Swift/Collection/partitioningIndex(where:)``
|
||||
|
||||
### Rotation
|
||||
|
||||
- ``Swift/MutableCollection/rotate(toStartAt:)-9fp48``
|
||||
- ``Swift/MutableCollection/rotate(toStartAt:)-2r55j``
|
||||
- ``Swift/MutableCollection/rotate(subrange:toStartAt:)-ov6a``
|
||||
- ``Swift/MutableCollection/rotate(subrange:toStartAt:)-5teoq``
|
||||
|
||||
### Reversing
|
||||
|
||||
- ``Swift/MutableCollection/reverse(subrange:)``
|
||||
@@ -1,35 +0,0 @@
|
||||
# Reductions
|
||||
|
||||
Find the incremental values of a sequence "reduce" operation.
|
||||
|
||||
## Overview
|
||||
|
||||
Call one of the `reductions` methods when you want the result of a `reduce` operation along with all of its intermediate values:
|
||||
|
||||
```swift
|
||||
let exclusiveRunningTotal = (1...5).reductions(0, +)
|
||||
print(exclusiveRunningTotal)
|
||||
// prints [0, 1, 3, 6, 10, 15]
|
||||
|
||||
let inclusiveRunningTotal = (1...5).reductions(+)
|
||||
print(inclusiveRunningTotal)
|
||||
// prints [1, 3, 6, 10, 15]
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
- ``Swift/Sequence/reductions(_:)``
|
||||
- ``Swift/Sequence/reductions(_:_:)``
|
||||
- ``Swift/Sequence/reductions(into:_:)``
|
||||
- ``Swift/LazySequenceProtocol/reductions(_:)``
|
||||
- ``Swift/LazySequenceProtocol/reductions(_:_:)``
|
||||
- ``Swift/LazySequenceProtocol/reductions(into:_:)``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``InclusiveReductionsSequence``
|
||||
- ``ExclusiveReductionsSequence``
|
||||
|
||||
### Deprecated Methods
|
||||
|
||||
- <doc:DeprecatedScan>
|
||||
@@ -1,17 +0,0 @@
|
||||
# Random Sampling
|
||||
|
||||
Choose a specified number of random elements from a sequence or collection.
|
||||
|
||||
## Topics
|
||||
|
||||
### Random Sampling
|
||||
|
||||
- ``Swift/Sequence/randomSample(count:)``
|
||||
- ``Swift/Collection/randomSample(count:)``
|
||||
- ``Swift/Collection/randomStableSample(count:)``
|
||||
|
||||
### Random Sampling with a Generator
|
||||
|
||||
- ``Swift/Sequence/randomSample(count:using:)``
|
||||
- ``Swift/Collection/randomSample(count:using:)``
|
||||
- ``Swift/Collection/randomStableSample(count:using:)``
|
||||
@@ -1,25 +0,0 @@
|
||||
# Selecting Elements
|
||||
|
||||
Select elements at a particular interval, the first mapped value,
|
||||
or iterate of elements with their indices.
|
||||
|
||||
## Topics
|
||||
|
||||
### Selecting Elements at an Interval
|
||||
|
||||
- ``Swift/Sequence/striding(by:)``
|
||||
- ``Swift/Collection/striding(by:)``
|
||||
|
||||
### Conditionally Finding the First Mapped Value
|
||||
|
||||
- ``Swift/Sequence/firstNonNil(_:)``
|
||||
|
||||
### Iterating Over Elements with Their Indices
|
||||
|
||||
- ``Swift/Collection/indexed()``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``IndexedCollection``
|
||||
- ``StridingSequence``
|
||||
- ``StridingCollection``
|
||||
@@ -1,29 +0,0 @@
|
||||
# Slicing and Splitting
|
||||
|
||||
Iterate over tuple pairs of adjacent elements, overlapping windows of a specified size, or lazily-calculated splits.
|
||||
|
||||
## Topics
|
||||
|
||||
### Adjacent Pairs
|
||||
|
||||
- ``Swift/Sequence/adjacentPairs()``
|
||||
- ``Swift/Collection/adjacentPairs()``
|
||||
|
||||
### Windows
|
||||
|
||||
- ``Swift/Collection/windows(ofCount:)``
|
||||
|
||||
### Lazily Splitting a Collection
|
||||
|
||||
- ``Swift/LazySequenceProtocol/split(separator:maxSplits:omittingEmptySubsequences:)-4q4x8``
|
||||
- ``Swift/LazySequenceProtocol/split(maxSplits:omittingEmptySubsequences:whereSeparator:)-68oqf``
|
||||
- ``Swift/LazySequenceProtocol/split(separator:maxSplits:omittingEmptySubsequences:)-a46s``
|
||||
- ``Swift/LazySequenceProtocol/split(maxSplits:omittingEmptySubsequences:whereSeparator:)-3rwee``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``AdjacentPairsSequence``
|
||||
- ``AdjacentPairsCollection``
|
||||
- ``WindowsOfCountCollection``
|
||||
- ``SplitSequence``
|
||||
- ``SplitCollection``
|
||||
@@ -1,32 +0,0 @@
|
||||
# Trimming
|
||||
|
||||
Remove unwanted elements from the start, the end, or both ends of a collection.
|
||||
|
||||
## Topics
|
||||
|
||||
### Trimming Both Ends of a Collection
|
||||
|
||||
- ``Swift/BidirectionalCollection/trimming(while:)``
|
||||
- ``Swift/BidirectionalCollection/trim(while:)-781az``
|
||||
- ``Swift/BidirectionalCollection/trim(while:)-6cbz3``
|
||||
|
||||
### Trimming from the Start
|
||||
|
||||
- ``Swift/Collection/trimmingPrefix(while:)``
|
||||
- ``Swift/Collection/trimPrefix(while:)-2r8n8``
|
||||
- ``Swift/Collection/trimPrefix(while:)-93obt``
|
||||
|
||||
### Trimming from the End
|
||||
|
||||
- ``Swift/BidirectionalCollection/trimmingSuffix(while:)``
|
||||
- ``Swift/BidirectionalCollection/trimSuffix(while:)-33ubj``
|
||||
- ``Swift/BidirectionalCollection/trimSuffix(while:)-3o6x9``
|
||||
|
||||
### Finding the Suffix of a Collection
|
||||
|
||||
- ``Swift/BidirectionalCollection/suffix(while:)``
|
||||
|
||||
### Finding Boundaries within a Collection
|
||||
|
||||
- ``Swift/Collection/endOfPrefix(while:)``
|
||||
- ``Swift/BidirectionalCollection/startOfSuffix(while:)``
|
||||
@@ -1,197 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Either
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A general-purpose sum type.
|
||||
@usableFromInline
|
||||
internal enum Either<Left, Right> {
|
||||
case left(Left)
|
||||
case right(Right)
|
||||
}
|
||||
|
||||
extension Either: Equatable where Left: Equatable, Right: Equatable {
|
||||
@usableFromInline
|
||||
internal static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.left(let lhs), .left(let rhs)):
|
||||
return lhs == rhs
|
||||
case (.right(let lhs), .right(let rhs)):
|
||||
return lhs == rhs
|
||||
case (.left, .right), (.right, .left):
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Either: Comparable where Left: Comparable, Right: Comparable {
|
||||
@usableFromInline
|
||||
internal static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.left(let lhs), .left(let rhs)):
|
||||
return lhs < rhs
|
||||
case (.right(let lhs), .right(let rhs)):
|
||||
return lhs < rhs
|
||||
case (.left, .right):
|
||||
return true
|
||||
case (.right, .left):
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// EitherSequence
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence that has one of the two specified types.
|
||||
@usableFromInline
|
||||
internal enum EitherSequence<Left: Sequence, Right: Sequence>
|
||||
where Left.Element == Right.Element {
|
||||
case left(Left)
|
||||
case right(Right)
|
||||
}
|
||||
|
||||
extension EitherSequence: Sequence {
|
||||
@usableFromInline
|
||||
internal struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var left: Left.Iterator?
|
||||
|
||||
@usableFromInline
|
||||
internal var right: Right.Iterator?
|
||||
|
||||
@inlinable
|
||||
internal mutating func next() -> Left.Element? {
|
||||
left?.next() ?? right?.next()
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func makeIterator() -> Iterator {
|
||||
switch self {
|
||||
case .left(let left):
|
||||
return Iterator(left: left.makeIterator(), right: nil)
|
||||
case .right(let right):
|
||||
return Iterator(left: nil, right: right.makeIterator())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension EitherSequence: Collection
|
||||
where Left: Collection, Right: Collection, Left.Element == Right.Element {
|
||||
@usableFromInline
|
||||
internal typealias Index = Either<Left.Index, Right.Index>
|
||||
|
||||
@inlinable
|
||||
internal var startIndex: Index {
|
||||
switch self {
|
||||
case .left(let s):
|
||||
return .left(s.startIndex)
|
||||
case .right(let s):
|
||||
return .right(s.startIndex)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var endIndex: Index {
|
||||
switch self {
|
||||
case .left(let s):
|
||||
return .left(s.endIndex)
|
||||
case .right(let s):
|
||||
return .right(s.endIndex)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal subscript(position: Index) -> Element {
|
||||
switch (self, position) {
|
||||
case (.left(let s), .left(let i)):
|
||||
return s[i]
|
||||
case (.right(let s), .right(let i)):
|
||||
return s[i]
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(after i: Index) -> Index {
|
||||
switch (self, i) {
|
||||
case (.left(let s), .left(let i)):
|
||||
return .left(s.index(after: i))
|
||||
case (.right(let s), .right(let i)):
|
||||
return .right(s.index(after: i))
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(
|
||||
_ i: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
switch (self, i, limit) {
|
||||
case (.left(let s), .left(let i), .left(let limit)):
|
||||
return s.index(i, offsetBy: distance, limitedBy: limit).map { .left($0) }
|
||||
case (.right(let s), .right(let i), .right(let limit)):
|
||||
return s.index(i, offsetBy: distance, limitedBy: limit).map { .right($0) }
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
switch (self, i) {
|
||||
case (.left(let s), .left(let i)):
|
||||
return .left(s.index(i, offsetBy: distance))
|
||||
case (.right(let s), .right(let i)):
|
||||
return .right(s.index(i, offsetBy: distance))
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (self, start, end) {
|
||||
case (.left(let s), .left(let i), .left(let j)):
|
||||
return s.distance(from: i, to: j)
|
||||
case (.right(let s), .right(let i), .right(let j)):
|
||||
return s.distance(from: i, to: j)
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension EitherSequence: BidirectionalCollection
|
||||
where Left: BidirectionalCollection, Right: BidirectionalCollection {
|
||||
@inlinable
|
||||
internal func index(before i: Index) -> Index {
|
||||
switch (self, i) {
|
||||
case (.left(let s), .left(let i)):
|
||||
return .left(s.index(before: i))
|
||||
case (.right(let s), .right(let i)):
|
||||
return .right(s.index(before: i))
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension EitherSequence: RandomAccessCollection
|
||||
where Left: RandomAccessCollection, Right: RandomAccessCollection {}
|
||||
@@ -1,83 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// EndsWith
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension BidirectionalCollection where Element: Equatable {
|
||||
/// Returns a Boolean value indicating whether the final elements of the
|
||||
/// collection are the same as the elements in another collection.
|
||||
///
|
||||
/// This example tests whether one countable range ends with the elements
|
||||
/// of another countable range.
|
||||
///
|
||||
/// let a = 8...10
|
||||
/// let b = 1...10
|
||||
///
|
||||
/// print(b.ends(with: a))
|
||||
/// // Prints "true"
|
||||
///
|
||||
/// Passing a collection with no elements or an empty collection as
|
||||
/// `possibleSuffix` always results in `true`.
|
||||
///
|
||||
/// print(b.ends(with: []))
|
||||
/// // Prints "true"
|
||||
///
|
||||
/// - Parameter possibleSuffix: A collection to compare to this collection.
|
||||
/// - Returns: `true` if the initial elements of the collection are the same as
|
||||
/// the elements of `possibleSuffix`; otherwise, `false`. If
|
||||
/// `possibleSuffix` has no elements, the return value is `true`.
|
||||
///
|
||||
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
|
||||
/// collection and the length of `possibleSuffix`.
|
||||
@inlinable
|
||||
public func ends<PossibleSuffix: BidirectionalCollection>(
|
||||
with possibleSuffix: PossibleSuffix
|
||||
) -> Bool where PossibleSuffix.Element == Element {
|
||||
self.ends(with: possibleSuffix, by: ==)
|
||||
}
|
||||
}
|
||||
|
||||
extension BidirectionalCollection {
|
||||
/// Returns a Boolean value indicating whether the final elements of the
|
||||
/// collection are equivalent to the elements in another collection, using
|
||||
/// the given predicate as the equivalence test.
|
||||
///
|
||||
/// The predicate must be an *equivalence relation* over the elements. That
|
||||
/// is, for any elements `a`, `b`, and `c`, the following conditions must
|
||||
/// hold:
|
||||
///
|
||||
/// - `areEquivalent(a, a)` is always `true`. (Reflexivity)
|
||||
/// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
|
||||
/// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then
|
||||
/// `areEquivalent(a, c)` is also `true`. (Transitivity)
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - possibleSuffix: A collection to compare to this collection.
|
||||
/// - areEquivalent: A predicate that returns `true` if its two arguments
|
||||
/// are equivalent; otherwise, `false`.
|
||||
/// - Returns: `true` if the initial elements of the collection are equivalent
|
||||
/// to the elements of `possibleSuffix`; otherwise, `false`. If
|
||||
/// `possibleSuffix` has no elements, the return value is `true`.
|
||||
///
|
||||
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
|
||||
/// collection and the length of `possibleSuffix`.
|
||||
@inlinable
|
||||
public func ends<PossibleSuffix: BidirectionalCollection>(
|
||||
with possibleSuffix: PossibleSuffix,
|
||||
by areEquivalent: (Element, PossibleSuffix.Element) throws -> Bool
|
||||
) rethrows -> Bool {
|
||||
try self
|
||||
.reversed()
|
||||
.starts(with: possibleSuffix.reversed(), by: areEquivalent)
|
||||
}
|
||||
}
|
||||
@@ -30,15 +30,8 @@ extension Sequence {
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the number of elements at the start of
|
||||
/// the sequence that result in `nil` when applying the transformation.
|
||||
@inlinable
|
||||
public func firstNonNil<Result>(
|
||||
_ transform: (Element) throws -> Result?
|
||||
) rethrows -> Result? {
|
||||
for value in self {
|
||||
if let value = try transform(value) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
public func firstNonNil<Result>(_ transform: (Element) throws -> Result?) rethrows -> Result? {
|
||||
for value in self { if let value = try transform(value) { return value } }
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1,332 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection consisting of all the elements contained in a collection of
|
||||
/// collections.
|
||||
@usableFromInline
|
||||
internal struct FlattenCollection<Base: Collection>
|
||||
where Base.Element: Collection {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let indexOfFirstNonEmptyElement: Base.Index
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
self.indexOfFirstNonEmptyElement = base.endOfPrefix(while: { $0.isEmpty })
|
||||
}
|
||||
}
|
||||
|
||||
extension FlattenCollection: Collection {
|
||||
@usableFromInline
|
||||
internal struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let outer: Base.Index
|
||||
|
||||
@usableFromInline
|
||||
internal let inner: Base.Element.Index?
|
||||
|
||||
@inlinable
|
||||
init(outer: Base.Index, inner: Base.Element.Index?) {
|
||||
self.outer = outer
|
||||
self.inner = inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
guard lhs.outer == rhs.outer else { return lhs.outer < rhs.outer }
|
||||
// swift-format-ignore: NeverForceUnwrap
|
||||
// `inner` is nil iff `outer` is `base.endIndex`, and the
|
||||
// previous line established that the two outer indices are equal.
|
||||
// Thus, either both inner indices are nil or neither are.
|
||||
return lhs.inner == nil ? false : lhs.inner! < rhs.inner!
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var startIndex: Index {
|
||||
let outer = indexOfFirstNonEmptyElement
|
||||
let inner = outer == base.endIndex ? nil : base[outer].startIndex
|
||||
return Index(outer: outer, inner: inner)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var endIndex: Index {
|
||||
Index(outer: base.endIndex, inner: nil)
|
||||
}
|
||||
|
||||
/// Forms an index from a pair of base indices, normalizing
|
||||
/// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if
|
||||
/// necessary.
|
||||
@inlinable
|
||||
internal func normalizeIndex(
|
||||
outer: Base.Index,
|
||||
inner: Base.Element.Index
|
||||
) -> Index {
|
||||
guard inner == base[outer].endIndex else {
|
||||
return Index(outer: outer, inner: inner)
|
||||
}
|
||||
let outer = base[base.index(after: outer)...]
|
||||
.endOfPrefix(while: { $0.isEmpty })
|
||||
let inner = outer == base.endIndex ? nil : base[outer].startIndex
|
||||
return Index(outer: outer, inner: inner)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(after index: Index) -> Index {
|
||||
let element = base[index.outer]
|
||||
// swift-format-ignore: NeverForceUnwrap
|
||||
// This unwrap, like the unchecked subscript above, enforces the
|
||||
// precondition that you can't advance past `endIndex`.
|
||||
let nextInner = element.index(after: index.inner!)
|
||||
return normalizeIndex(outer: index.outer, inner: nextInner)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal subscript(position: Index) -> Base.Element.Element {
|
||||
// swift-format-ignore: NeverForceUnwrap
|
||||
// This unwrap, along with the unchecked subscript, enforces the
|
||||
// precondition that you can't subscript at `endIndex`.
|
||||
base[position.outer][position.inner!]
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func distance(from start: Index, to end: Index) -> Int {
|
||||
guard start.outer <= end.outer
|
||||
else { return -distance(from: end, to: start) }
|
||||
guard let startInner = start.inner
|
||||
else { return 0 }
|
||||
guard start.outer != end.outer
|
||||
else {
|
||||
// swift-format-ignore: NeverForceUnwrap
|
||||
// Established via guards that outer indices are equal and `start.inner`
|
||||
// is non-nil, so `end.inner` must also be non-`nil`.
|
||||
return base[start.outer].distance(from: startInner, to: end.inner!)
|
||||
}
|
||||
|
||||
let firstPart = base[start.outer][startInner...].count
|
||||
let middlePart = base[start.outer..<end.outer].dropFirst()
|
||||
.reduce(0, { $0 + $1.count })
|
||||
let lastPart = end.inner.map { base[end.outer][..<$0].count } ?? 0
|
||||
|
||||
return firstPart + middlePart + lastPart
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(_ index: Index, offsetBy distance: Int) -> Index {
|
||||
guard distance != 0 else { return index }
|
||||
|
||||
return distance > 0
|
||||
? offsetForward(index, by: distance)
|
||||
: offsetBackward(index, by: -distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(
|
||||
_ index: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
guard distance != 0 else { return index }
|
||||
|
||||
if distance > 0 {
|
||||
return limit >= index
|
||||
? offsetForward(index, by: distance, limitedBy: limit)
|
||||
: offsetForward(index, by: distance)
|
||||
} else {
|
||||
return limit <= index
|
||||
? offsetBackward(index, by: -distance, limitedBy: limit)
|
||||
: offsetBackward(index, by: -distance)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ index: Index,
|
||||
by distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit >= index)
|
||||
|
||||
if index.outer == limit.outer {
|
||||
guard let indexInner = index.inner, let limitInner = limit.inner else {
|
||||
// `index` and `limit` are both `endIndex`
|
||||
return nil
|
||||
}
|
||||
return base[index.outer]
|
||||
.index(indexInner, offsetBy: distance, limitedBy: limitInner)
|
||||
.map { inner in Index(outer: index.outer, inner: inner) }
|
||||
}
|
||||
|
||||
// swift-format-ignore: NeverForceUnwrap
|
||||
// `index <= limit` and `index.outer != limit.outer`, so `index != endIndex`
|
||||
let indexInner = index.inner!
|
||||
let element = base[index.outer]
|
||||
|
||||
if let inner = element.index(
|
||||
indexInner,
|
||||
offsetBy: distance,
|
||||
limitedBy: element.endIndex
|
||||
) {
|
||||
return normalizeIndex(outer: index.outer, inner: inner)
|
||||
}
|
||||
|
||||
var remainder = distance - element[indexInner...].count
|
||||
var outer = base.index(after: index.outer)
|
||||
|
||||
while outer != limit.outer {
|
||||
let element = base[outer]
|
||||
|
||||
if let inner = element.index(
|
||||
element.startIndex,
|
||||
offsetBy: remainder,
|
||||
limitedBy: element.endIndex
|
||||
) {
|
||||
return normalizeIndex(outer: outer, inner: inner)
|
||||
}
|
||||
|
||||
remainder -= element.count
|
||||
base.formIndex(after: &outer)
|
||||
}
|
||||
|
||||
if let limitInner = limit.inner {
|
||||
let element = base[outer]
|
||||
return element.index(
|
||||
element.startIndex,
|
||||
offsetBy: remainder,
|
||||
limitedBy: limitInner
|
||||
)
|
||||
.map { inner in Index(outer: outer, inner: inner) }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ index: Index,
|
||||
by distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit <= index)
|
||||
|
||||
if index.outer == limit.outer {
|
||||
guard let indexInner = index.inner, let limitInner = limit.inner else {
|
||||
// `index` and `limit` are both `endIndex`
|
||||
return nil
|
||||
}
|
||||
return base[index.outer]
|
||||
.index(indexInner, offsetBy: -distance, limitedBy: limitInner)
|
||||
.map { inner in Index(outer: index.outer, inner: inner) }
|
||||
}
|
||||
|
||||
var remainder = distance
|
||||
|
||||
if let indexInner = index.inner {
|
||||
let element = base[index.outer]
|
||||
|
||||
if let inner = element.index(
|
||||
indexInner,
|
||||
offsetBy: -remainder,
|
||||
limitedBy: element.startIndex
|
||||
) {
|
||||
return Index(outer: index.outer, inner: inner)
|
||||
}
|
||||
|
||||
remainder -= element[..<indexInner].count
|
||||
}
|
||||
|
||||
var outer = base.index(index.outer, offsetBy: -1)
|
||||
|
||||
while outer != limit.outer {
|
||||
let element = base[outer]
|
||||
|
||||
if let inner = element.index(
|
||||
element.endIndex,
|
||||
offsetBy: -remainder,
|
||||
limitedBy: element.startIndex
|
||||
) {
|
||||
return Index(outer: outer, inner: inner)
|
||||
}
|
||||
|
||||
remainder -= element.count
|
||||
base.formIndex(&outer, offsetBy: -1)
|
||||
}
|
||||
|
||||
let element = base[outer]
|
||||
// swift-format-ignore: NeverForceUnwrap
|
||||
// At start of function, `limit <= index`, and checked for
|
||||
// `limit == endIndex`.
|
||||
return element.index(
|
||||
element.endIndex,
|
||||
offsetBy: -remainder,
|
||||
limitedBy: limit.inner!
|
||||
).map { inner in Index(outer: outer, inner: inner) }
|
||||
}
|
||||
}
|
||||
|
||||
extension FlattenCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection, Base.Element: BidirectionalCollection {
|
||||
@inlinable
|
||||
internal func index(before index: Index) -> Index {
|
||||
if let inner = index.inner {
|
||||
let element = base[index.outer]
|
||||
|
||||
if inner != element.startIndex {
|
||||
let previousInner = element.index(before: inner)
|
||||
return Index(outer: index.outer, inner: previousInner)
|
||||
}
|
||||
}
|
||||
|
||||
guard
|
||||
let previousOuter = base[..<index.outer]
|
||||
.lastIndex(where: { !$0.isEmpty })
|
||||
else {
|
||||
fatalError("Can't move before startIndex.")
|
||||
}
|
||||
let element = base[previousOuter]
|
||||
let previousInner = element.index(before: element.endIndex)
|
||||
return Index(outer: previousOuter, inner: previousInner)
|
||||
}
|
||||
}
|
||||
|
||||
extension FlattenCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol, Base.Element: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// joined()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection where Element: Collection {
|
||||
/// Returns the concatenation of the elements in this collection of
|
||||
/// collections.
|
||||
@inlinable
|
||||
internal func joined() -> FlattenCollection<Self> {
|
||||
FlattenCollection(base: self)
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Groups elements of this sequence into a new dictionary,
|
||||
/// whose values are arrays of grouped elements,
|
||||
/// each keyed by the key returned by the given closure.
|
||||
///
|
||||
/// - Parameter keyForValue: A closure that returns a key for each element
|
||||
/// in the sequence.
|
||||
/// - Returns: A dictionary containing grouped elements of self, keyed by
|
||||
/// the keys derived by the `keyForValue` closure.
|
||||
@inlinable
|
||||
public func grouped<GroupKey>(
|
||||
by keyForValue: (Element) throws -> GroupKey
|
||||
) rethrows -> [GroupKey: [Element]] {
|
||||
try Dictionary(grouping: self, by: keyForValue)
|
||||
}
|
||||
}
|
||||
@@ -11,79 +11,47 @@
|
||||
|
||||
/// A collection wrapper that iterates over the indices and elements of a
|
||||
/// collection together.
|
||||
public struct IndexedCollection<Base: Collection> {
|
||||
/// The base collection.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
}
|
||||
|
||||
extension IndexedCollection: Collection {
|
||||
/// The element type for an `IndexedCollection` collection.
|
||||
public struct Indexed<Base: Collection> {
|
||||
/// The element type for an `Indexed` collection.
|
||||
public typealias Element = (index: Base.Index, element: Base.Element)
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Base.Index {
|
||||
base.startIndex
|
||||
}
|
||||
/// The base collection.
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Base.Index {
|
||||
base.endIndex
|
||||
}
|
||||
@inlinable internal init(base: Base) { self.base = base }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Base.Index) -> Element {
|
||||
extension Indexed: Collection {
|
||||
@inlinable public var startIndex: Base.Index { base.startIndex }
|
||||
|
||||
@inlinable public var endIndex: Base.Index { base.endIndex }
|
||||
|
||||
@inlinable public subscript(position: Base.Index) -> Element {
|
||||
(index: position, element: base[position])
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Base.Index) -> Base.Index {
|
||||
base.index(after: i)
|
||||
}
|
||||
@inlinable public func index(after i: Base.Index) -> Base.Index { base.index(after: i) }
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index {
|
||||
@inlinable public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index {
|
||||
base.index(i, offsetBy: distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Base.Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Base.Index
|
||||
) -> Base.Index? {
|
||||
base.index(i, offsetBy: distance, limitedBy: limit)
|
||||
}
|
||||
@inlinable public func 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 {
|
||||
@inlinable public func distance(from start: Base.Index, to end: Base.Index) -> Int {
|
||||
base.distance(from: start, to: end)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var indices: Base.Indices {
|
||||
base.indices
|
||||
}
|
||||
}
|
||||
|
||||
extension IndexedCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before i: Base.Index) -> Base.Index {
|
||||
base.index(before: i)
|
||||
}
|
||||
extension Indexed: BidirectionalCollection where Base: BidirectionalCollection {
|
||||
@inlinable public func index(before i: Base.Index) -> Base.Index { base.index(before: i) }
|
||||
}
|
||||
|
||||
extension IndexedCollection: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
extension IndexedCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
extension Indexed: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension Indexed: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// indexed()
|
||||
@@ -93,10 +61,6 @@ extension Collection {
|
||||
/// Returns a collection of pairs *(i, x)*, where *i* represents an index of
|
||||
/// the collection, and *x* represents an element.
|
||||
///
|
||||
/// The `indexed()` method is similar to the standard library's `enumerated()`
|
||||
/// method, but provides the index with each element instead of a zero-based
|
||||
/// counter.
|
||||
///
|
||||
/// This example iterates over the indices and elements of a set, building an
|
||||
/// array consisting of indices of names with five or fewer letters.
|
||||
///
|
||||
@@ -108,9 +72,6 @@ extension Collection {
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// - Returns: A collection of paired indices and elements of this collection.
|
||||
@inlinable
|
||||
public func indexed() -> IndexedCollection<Self> {
|
||||
IndexedCollection(base: self)
|
||||
}
|
||||
/// Returns: A collection of paired indices and elements of this collection.
|
||||
@inlinable public func indexed() -> Indexed<Self> { Indexed(base: self) }
|
||||
}
|
||||
@@ -9,53 +9,40 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Intersperse
|
||||
//===----------------------------------------------------------------------===//
|
||||
/// A sequence that presents the elements of a base sequence of elements
|
||||
/// with a separator between each of those elements.
|
||||
public struct Intersperse<Base: Sequence> {
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
/// A sequence that presents the elements of a base sequence of elements with a
|
||||
/// separator between each of those elements.
|
||||
public struct InterspersedSequence<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
@usableFromInline internal let separator: Base.Element
|
||||
|
||||
@usableFromInline
|
||||
internal let separator: Base.Element
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, separator: Base.Element) {
|
||||
@inlinable internal init(base: Base, separator: Base.Element) {
|
||||
self.base = base
|
||||
self.separator = separator
|
||||
}
|
||||
}
|
||||
|
||||
extension InterspersedSequence: Sequence {
|
||||
/// The iterator for an `InterspersedSequence` sequence.
|
||||
extension Intersperse: Sequence {
|
||||
/// The iterator for an `Intersperse` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal enum State {
|
||||
@usableFromInline internal var iterator: Base.Iterator
|
||||
|
||||
@usableFromInline internal let separator: Base.Element
|
||||
|
||||
@usableFromInline internal var state = State.start
|
||||
|
||||
@inlinable internal init(iterator: Base.Iterator, separator: Base.Element) {
|
||||
self.iterator = iterator
|
||||
self.separator = separator
|
||||
}
|
||||
|
||||
@usableFromInline enum State {
|
||||
case start
|
||||
case element(Base.Element)
|
||||
case separator
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal let separator: Base.Element
|
||||
|
||||
@usableFromInline
|
||||
internal var state = State.start
|
||||
|
||||
@inlinable
|
||||
internal init(iterator: Base.Iterator, separator: Base.Element) {
|
||||
self.iterator = iterator
|
||||
self.separator = separator
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element? {
|
||||
@inlinable public mutating func next() -> Base.Element? {
|
||||
// After the start, the state flips between element and separator. Before
|
||||
// returning a separator, a check is made for the next element as a
|
||||
// separator is only returned between two elements. The next element is
|
||||
@@ -75,548 +62,105 @@ extension InterspersedSequence: Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> InterspersedSequence<Base>.Iterator {
|
||||
@inlinable public func makeIterator() -> Intersperse<Base>.Iterator {
|
||||
Iterator(iterator: base.makeIterator(), separator: separator)
|
||||
}
|
||||
}
|
||||
|
||||
extension InterspersedSequence: Collection where Base: Collection {
|
||||
/// A position in an `InterspersedSequence` instance.
|
||||
extension Intersperse: Collection where Base: Collection {
|
||||
/// A position in an `Intersperse` collection.
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal enum Representation: Equatable {
|
||||
@usableFromInline enum Representation: Equatable {
|
||||
case element(Base.Index)
|
||||
case separator(next: Base.Index)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal let representation: Representation
|
||||
@usableFromInline internal let representation: Representation
|
||||
|
||||
@inlinable
|
||||
internal init(representation: Representation) {
|
||||
self.representation = representation
|
||||
}
|
||||
@inlinable init(representation: Representation) { self.representation = representation }
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
switch (lhs.representation, rhs.representation) {
|
||||
case (.element(let li), .element(let ri)),
|
||||
(.separator(next: let li), .separator(next: let ri)),
|
||||
(.element(let li), .separator(next: let ri)):
|
||||
case let (.element(li), .element(ri)), let (.separator(next: li), .separator(next: ri)),
|
||||
let (.element(li), .separator(next: ri)):
|
||||
return li < ri
|
||||
case (.separator(next: let li), .element(let ri)):
|
||||
return li <= ri
|
||||
case let (.separator(next: li), .element(ri)): return li <= ri
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func element(_ index: Base.Index) -> Self {
|
||||
@inlinable static func element(_ index: Base.Index) -> Self {
|
||||
Self(representation: .element(index))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func separator(next: Base.Index) -> Self {
|
||||
@inlinable static func separator(next: Base.Index) -> Self {
|
||||
Self(representation: .separator(next: next))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
@inlinable public var startIndex: Index {
|
||||
base.startIndex == base.endIndex ? endIndex : .element(base.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
.separator(next: base.endIndex)
|
||||
}
|
||||
@inlinable public var endIndex: Index { .separator(next: base.endIndex) }
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
@inlinable public func index(after i: Index) -> Index {
|
||||
precondition(i != endIndex, "Can't advance past endIndex")
|
||||
switch i.representation {
|
||||
case .element(let index):
|
||||
return .separator(next: base.index(after: index))
|
||||
case .separator(let next):
|
||||
return .element(next)
|
||||
case let .element(index): return .separator(next: base.index(after: index))
|
||||
case let .separator(next): return .element(next)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Element {
|
||||
@inlinable public subscript(position: Index) -> Element {
|
||||
switch position.representation {
|
||||
case .element(let index): return base[index]
|
||||
case .separator: return separator
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
@inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
switch (i.representation, distance.isMultiple(of: 2)) {
|
||||
case (let .element(index), true): return .element(base.index(index, offsetBy: distance / 2))
|
||||
case (let .element(index), false):
|
||||
return .separator(next: base.index(index, offsetBy: (distance + 1) / 2))
|
||||
case (let .separator(next: index), true):
|
||||
return .separator(next: base.index(index, offsetBy: distance / 2))
|
||||
case (let .separator(next: index), false):
|
||||
return .element(base.index(index, offsetBy: (distance - 1) / 2))
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Implement index(_:offsetBy:limitedBy:)
|
||||
@inlinable public func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (start.representation, end.representation) {
|
||||
case (.element(let element), .separator(next: let separator)):
|
||||
case let (.element(element), .separator(next: separator)):
|
||||
return 2 * base.distance(from: element, to: separator) - 1
|
||||
case (.separator(next: let separator), .element(let element)):
|
||||
case let (.separator(next: separator), .element(element)):
|
||||
return 2 * base.distance(from: separator, to: element) + 1
|
||||
case (.element(let start), .element(let end)),
|
||||
(.separator(let start), .separator(let end)):
|
||||
case let (.element(start), .element(end)), let (.separator(start), .separator(end)):
|
||||
return 2 * base.distance(from: start, to: end)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ index: Index, offsetBy distance: Int) -> Index {
|
||||
distance >= 0
|
||||
? offsetForward(index, by: distance)
|
||||
: offsetBackward(index, by: -distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ index: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
if distance >= 0 {
|
||||
return limit >= index
|
||||
? offsetForward(index, by: distance, limitedBy: limit)
|
||||
: offsetForward(index, by: distance)
|
||||
} else {
|
||||
return limit <= index
|
||||
? offsetBackward(index, by: -distance, limitedBy: limit)
|
||||
: offsetBackward(index, by: -distance)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ index: Index,
|
||||
by distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance >= 0)
|
||||
assert(limit >= index)
|
||||
|
||||
switch (
|
||||
index.representation, limit.representation, distance.isMultiple(of: 2)
|
||||
) {
|
||||
case (.element(let index), .element(let limit), true),
|
||||
(.separator(next: let index), .element(let limit), false):
|
||||
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
|
||||
.map { .element($0) }
|
||||
|
||||
case (.element(let index), .element(let limit), false),
|
||||
(.element(let index), .separator(next: let limit), false),
|
||||
(.separator(next: let index), .element(let limit), true),
|
||||
(.separator(next: let index), .separator(next: let limit), true):
|
||||
return base.index(index, offsetBy: (distance + 1) / 2, limitedBy: limit)
|
||||
.map { .separator(next: $0) }
|
||||
|
||||
case (.element(let index), .separator(next: let limit), true),
|
||||
(.separator(next: let index), .separator(next: let limit), false):
|
||||
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
|
||||
.flatMap { $0 == limit ? nil : .element($0) }
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ index: Index,
|
||||
by distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance >= 0)
|
||||
assert(limit <= index)
|
||||
|
||||
switch (
|
||||
index.representation, limit.representation, distance.isMultiple(of: 2)
|
||||
) {
|
||||
case (.element(let index), .element(let limit), true),
|
||||
(.element(let index), .separator(next: let limit), true),
|
||||
(.separator(next: let index), .element(let limit), false),
|
||||
(.separator(next: let index), .separator(next: let limit), false):
|
||||
return base.index(
|
||||
index, offsetBy: -((distance + 1) / 2), limitedBy: limit
|
||||
)
|
||||
.map { .element($0) }
|
||||
|
||||
case (.element(let index), .separator(next: let limit), false),
|
||||
(.separator(next: let index), .separator(next: let limit), true):
|
||||
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
|
||||
.map { .separator(next: $0) }
|
||||
|
||||
case (.element(let index), .element(let limit), false),
|
||||
(.separator(next: let index), .element(let limit), true):
|
||||
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
|
||||
.flatMap { $0 == limit ? nil : .separator(next: $0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension InterspersedSequence: BidirectionalCollection
|
||||
where Base: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
extension Intersperse: BidirectionalCollection where Base: BidirectionalCollection {
|
||||
@inlinable public func index(before i: Index) -> Index {
|
||||
precondition(i != startIndex, "Can't move before startIndex")
|
||||
switch i.representation {
|
||||
case .element(let index):
|
||||
return .separator(next: index)
|
||||
case .separator(let next):
|
||||
return .element(base.index(before: next))
|
||||
case let .element(index): return .separator(next: index)
|
||||
case let .separator(next): return .element(base.index(before: next))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension InterspersedSequence: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
extension Intersperse: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
|
||||
extension InterspersedSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension Intersperse: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
extension InterspersedSequence: LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol & Collection {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// InterspersedMap
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence over the results of applying a closure to the sequence's
|
||||
/// elements, with a separator that separates each pair of adjacent transformed
|
||||
/// values.
|
||||
@usableFromInline
|
||||
internal struct InterspersedMapSequence<Base: Sequence, Result> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (Base.Element) -> Result
|
||||
|
||||
@usableFromInline
|
||||
internal let separator: (Base.Element, Base.Element) -> Result
|
||||
}
|
||||
|
||||
extension InterspersedMapSequence: Sequence {
|
||||
@usableFromInline
|
||||
internal struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal enum State {
|
||||
case start
|
||||
case element(Base.Element)
|
||||
case separator(previous: Base.Element)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal var base: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (Base.Element) -> Result
|
||||
|
||||
@usableFromInline
|
||||
internal let separator: (Base.Element, Base.Element) -> Result
|
||||
|
||||
@usableFromInline
|
||||
internal var state = State.start
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base.Iterator,
|
||||
transform: @escaping (Base.Element) -> Result,
|
||||
separator: @escaping (Base.Element, Base.Element) -> Result
|
||||
) {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
self.separator = separator
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func next() -> Result? {
|
||||
switch state {
|
||||
case .start:
|
||||
guard let first = base.next() else { return nil }
|
||||
state = .separator(previous: first)
|
||||
return transform(first)
|
||||
case .separator(let previous):
|
||||
guard let next = base.next() else { return nil }
|
||||
state = .element(next)
|
||||
return separator(previous, next)
|
||||
case .element(let element):
|
||||
state = .separator(previous: element)
|
||||
return transform(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func makeIterator() -> Iterator {
|
||||
Iterator(
|
||||
base: base.makeIterator(),
|
||||
transform: transform,
|
||||
separator: separator)
|
||||
}
|
||||
}
|
||||
|
||||
extension InterspersedMapSequence: Collection where Base: Collection {
|
||||
@usableFromInline
|
||||
internal struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal enum Representation {
|
||||
case element(Base.Index)
|
||||
case separator(previous: Base.Index, next: Base.Index)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal let base: Representation
|
||||
|
||||
@inlinable
|
||||
internal init(representation: Representation) {
|
||||
self.base = representation
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func element(_ index: Base.Index) -> Self {
|
||||
Self(representation: .element(index))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func separator(
|
||||
previous: Base.Index,
|
||||
next: Base.Index
|
||||
) -> Self {
|
||||
Self(representation: .separator(previous: previous, next: next))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs.base, rhs.base) {
|
||||
case (.element(let lhs), .element(let rhs)),
|
||||
(.separator(_, next: let lhs), .separator(_, next: let rhs)):
|
||||
return lhs == rhs
|
||||
case (.element, .separator), (.separator, .element):
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs.base, rhs.base) {
|
||||
case (.element(let lhs), .element(let rhs)),
|
||||
(.separator(_, next: let lhs), .separator(_, next: let rhs)),
|
||||
(.element(let lhs), .separator(_, next: let rhs)),
|
||||
(.separator(previous: let lhs, _), .element(let rhs)):
|
||||
return lhs < rhs
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var startIndex: Index {
|
||||
base.isEmpty ? endIndex : .element(base.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var endIndex: Index {
|
||||
.separator(previous: base.endIndex, next: base.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(after index: Index) -> Index {
|
||||
switch index.base {
|
||||
case .element(let index):
|
||||
let next = base.index(after: index)
|
||||
return .separator(previous: index, next: next)
|
||||
case .separator(_, let next):
|
||||
return .element(next)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal subscript(position: Index) -> Result {
|
||||
switch position.base {
|
||||
case .element(let index):
|
||||
return transform(base[index])
|
||||
case .separator(let previous, let next):
|
||||
return separator(base[previous], base[next])
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (start.base, end.base) {
|
||||
case (.element(let lhs), .element(let rhs)),
|
||||
(.separator(_, next: let lhs), .separator(_, next: let rhs)):
|
||||
return 2 * base.distance(from: lhs, to: rhs)
|
||||
case (.element(let lhs), .separator(_, next: let rhs)):
|
||||
return 2 * base.distance(from: lhs, to: rhs) - 1
|
||||
case (.separator(_, next: let lhs), .element(let rhs)):
|
||||
return 2 * base.distance(from: lhs, to: rhs) + 1
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(_ index: Index, offsetBy distance: Int) -> Index {
|
||||
guard distance != 0 else { return index }
|
||||
|
||||
return distance > 0
|
||||
? offsetForward(index, by: distance)
|
||||
: offsetBackward(index, by: -distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(
|
||||
_ index: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
guard distance != 0 else { return index }
|
||||
|
||||
if distance > 0 {
|
||||
return limit >= index
|
||||
? offsetForward(index, by: distance, limitedBy: limit)
|
||||
: offsetForward(index, by: distance)
|
||||
} else {
|
||||
return limit <= index
|
||||
? offsetBackward(index, by: -distance, limitedBy: limit)
|
||||
: offsetBackward(index, by: -distance)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ index: Index,
|
||||
by distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit >= index)
|
||||
|
||||
switch (index.base, limit.base, distance.isMultiple(of: 2)) {
|
||||
case (.element(let index), .element(let limit), true),
|
||||
(.separator(_, next: let index), .element(let limit), false):
|
||||
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
|
||||
.map { .element($0) }
|
||||
|
||||
case (.element(let index), .element(let limit), false),
|
||||
(.element(let index), .separator(_, next: let limit), false),
|
||||
(.separator(_, next: let index), .element(let limit), true),
|
||||
(.separator(_, next: let index), .separator(_, next: let limit), true):
|
||||
return base.index(index, offsetBy: (distance - 1) / 2, limitedBy: limit)
|
||||
.flatMap {
|
||||
guard $0 != limit else { return nil }
|
||||
let next = base.index(after: $0)
|
||||
return next == base.endIndex
|
||||
? endIndex
|
||||
: .separator(previous: $0, next: next)
|
||||
}
|
||||
|
||||
case (.element(let index), .separator(_, next: let limit), true),
|
||||
(.separator(_, next: let index), .separator(_, next: let limit), false):
|
||||
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
|
||||
.flatMap { $0 == limit ? nil : .element($0) }
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ index: Index,
|
||||
by distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit <= index)
|
||||
|
||||
switch (index.base, limit.base, distance.isMultiple(of: 2)) {
|
||||
case (.element(let index), .element(let limit), true),
|
||||
(.element(let index), .separator(_, next: let limit), true),
|
||||
(.separator(_, next: let index), .element(let limit), false),
|
||||
(.separator(_, next: let index), .separator(_, next: let limit), false):
|
||||
return
|
||||
base
|
||||
.index(index, offsetBy: -((distance + 1) / 2), limitedBy: limit)
|
||||
.map { .element($0) }
|
||||
|
||||
case (.element(let index), .separator(_, next: let limit), false),
|
||||
(.separator(_, next: let index), .separator(_, next: let limit), true):
|
||||
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
|
||||
.map { .separator(previous: base.index($0, offsetBy: -1), next: $0) }
|
||||
|
||||
case (.element(let index), .element(let limit), false),
|
||||
(.separator(_, next: let index), .element(let limit), true):
|
||||
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
|
||||
.flatMap {
|
||||
$0 == limit
|
||||
? nil
|
||||
: .separator(previous: base.index($0, offsetBy: -1), next: $0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension InterspersedMapSequence: BidirectionalCollection
|
||||
where Base: BidirectionalCollection {
|
||||
@inlinable
|
||||
internal func index(before index: Index) -> Index {
|
||||
switch index.base {
|
||||
case .element(let index):
|
||||
let previous = base.index(before: index)
|
||||
return .separator(previous: previous, next: index)
|
||||
case .separator(let previous, let next):
|
||||
let index = next == base.endIndex ? base.index(before: next) : previous
|
||||
return .element(index)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension InterspersedMapSequence.Index: Hashable
|
||||
where Base.Index: Hashable {
|
||||
@inlinable
|
||||
internal func hash(into hasher: inout Hasher) {
|
||||
switch base {
|
||||
case .element(let base):
|
||||
hasher.combine(false)
|
||||
hasher.combine(base)
|
||||
case .separator(_, let next):
|
||||
hasher.combine(true)
|
||||
hasher.combine(next)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension InterspersedMapSequence: LazySequenceProtocol {}
|
||||
extension InterspersedMapSequence: LazyCollectionProtocol
|
||||
where Base: Collection {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// interspersed(with:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
extension Intersperse: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns a sequence containing elements of this sequence with the given
|
||||
/// separator inserted in between each element.
|
||||
///
|
||||
@@ -645,40 +189,7 @@ extension Sequence {
|
||||
/// - Returns: The interspersed sequence of elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func interspersed(
|
||||
with separator: Element
|
||||
) -> InterspersedSequence<Self> {
|
||||
InterspersedSequence(base: self, separator: separator)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// lazy.interspersedMap(_:with:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
/// Returns a sequence over the results of applying a closure to the
|
||||
/// sequence's elements, with a separator that separates each pair of adjacent
|
||||
/// transformed values.
|
||||
///
|
||||
/// The transformation closure lets you intersperse a sequence using a
|
||||
/// separator of a different type than the original's sequence's elements.
|
||||
/// Each separator is produced by a closure that is given access to the
|
||||
/// two elements in the original sequence right before and after it.
|
||||
///
|
||||
/// let strings = [1, 2, 2].interspersedMap(String.init,
|
||||
/// with: { $0 == $1 ? " == " : " != " })
|
||||
/// print(strings.joined()) // "1 != 2 == 2"
|
||||
///
|
||||
@usableFromInline
|
||||
internal func interspersedMap<Result>(
|
||||
_ transform: @escaping (Element) -> Result,
|
||||
with separator: @escaping (Element, Element) -> Result
|
||||
) -> InterspersedMapSequence<Elements, Result> {
|
||||
InterspersedMapSequence(
|
||||
base: elements,
|
||||
transform: transform,
|
||||
separator: separator)
|
||||
@inlinable public func interspersed(with separator: Element) -> Intersperse<Self> {
|
||||
Intersperse(base: self, separator: separator)
|
||||
}
|
||||
}
|
||||
@@ -1,499 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// JoinedBySequence
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence that presents the elements of a base sequence of sequences
|
||||
/// concatenated using a given separator.
|
||||
public struct JoinedBySequence<Base: Sequence, Separator: Sequence>
|
||||
where Base.Element: Sequence, Base.Element.Element == Separator.Element {
|
||||
@usableFromInline
|
||||
internal typealias Inner = FlattenSequence<
|
||||
InterspersedSequence<
|
||||
LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>
|
||||
>
|
||||
>
|
||||
|
||||
@usableFromInline
|
||||
internal let inner: Inner
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, separator: Separator) {
|
||||
self.inner = base.lazy
|
||||
.map(EitherSequence.left)
|
||||
.interspersed(with: .right(separator))
|
||||
.joined()
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedBySequence: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var inner: Inner.Iterator
|
||||
|
||||
@inlinable
|
||||
internal init(inner: Inner.Iterator) {
|
||||
self.inner = inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element.Element? {
|
||||
inner.next()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(inner: inner.makeIterator())
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedBySequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// JoinedByClosureSequence
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence that presents the elements of a base sequence of sequences
|
||||
/// concatenated using a given separator that depends on the sequences right
|
||||
/// before and after it.
|
||||
public struct JoinedByClosureSequence<Base: Sequence, Separator: Sequence>
|
||||
where Base.Element: Sequence, Base.Element.Element == Separator.Element {
|
||||
@usableFromInline
|
||||
internal typealias Inner = FlattenSequence<
|
||||
InterspersedMapSequence<
|
||||
Base, EitherSequence<Base.Element, Separator>
|
||||
>
|
||||
>
|
||||
|
||||
@usableFromInline
|
||||
internal let inner: Inner
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
separator: @escaping (Base.Element, Base.Element) -> Separator
|
||||
) {
|
||||
self.inner = base.lazy
|
||||
.interspersedMap(
|
||||
EitherSequence.left,
|
||||
with: { EitherSequence.right(separator($0, $1)) }
|
||||
)
|
||||
.joined()
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByClosureSequence: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var inner: Inner.Iterator
|
||||
|
||||
@inlinable
|
||||
internal init(inner: Inner.Iterator) {
|
||||
self.inner = inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element.Element? {
|
||||
inner.next()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(inner: inner.makeIterator())
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByClosureSequence: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// JoinedByCollection
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection that presents the elements of a base collection of collections
|
||||
/// concatenated using a given separator.
|
||||
public struct JoinedByCollection<Base: Collection, Separator: Collection>
|
||||
where Base.Element: Collection, Base.Element.Element == Separator.Element {
|
||||
@usableFromInline
|
||||
internal typealias Inner = FlattenCollection<
|
||||
InterspersedSequence<
|
||||
LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>
|
||||
>
|
||||
>
|
||||
|
||||
@usableFromInline
|
||||
internal let inner: Inner
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, separator: Separator) {
|
||||
self.inner = base.lazy
|
||||
.map(EitherSequence.left)
|
||||
.interspersed(with: .right(separator))
|
||||
.joined()
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByCollection: Collection {
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let inner: Inner.Index
|
||||
|
||||
@inlinable
|
||||
internal init(_ inner: Inner.Index) {
|
||||
self.inner = inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.inner == rhs.inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.inner < rhs.inner
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(inner.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(inner.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after index: Index) -> Index {
|
||||
Index(inner.index(after: index.inner))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Base.Element.Element {
|
||||
inner[position.inner]
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ index: Index, offsetBy distance: Int) -> Index {
|
||||
Index(inner.index(index.inner, offsetBy: distance))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ index: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
inner.index(index.inner, offsetBy: distance, limitedBy: limit.inner)
|
||||
.map(Index.init)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
inner.distance(from: start.inner, to: end.inner)
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByCollection: BidirectionalCollection
|
||||
where
|
||||
Base: BidirectionalCollection,
|
||||
Base.Element: BidirectionalCollection,
|
||||
Separator: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
public func index(before index: Index) -> Index {
|
||||
Index(inner.index(before: index.inner))
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// JoinedByClosureCollection
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection that presents the elements of a base collection of collections
|
||||
/// concatenated using a given separator that depends on the collections right
|
||||
/// before and after it.
|
||||
public struct JoinedByClosureCollection<Base: Collection, Separator: Collection>
|
||||
where Base.Element: Collection, Base.Element.Element == Separator.Element {
|
||||
@usableFromInline
|
||||
internal typealias Inner = FlattenCollection<
|
||||
InterspersedMapSequence<
|
||||
Base, EitherSequence<Base.Element, Separator>
|
||||
>
|
||||
>
|
||||
|
||||
@usableFromInline
|
||||
internal let inner: Inner
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
separator: @escaping (Base.Element, Base.Element) -> Separator
|
||||
) {
|
||||
self.inner = base.lazy
|
||||
.interspersedMap(
|
||||
EitherSequence.left,
|
||||
with: { EitherSequence.right(separator($0, $1)) }
|
||||
)
|
||||
.joined()
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByClosureCollection: Collection {
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let inner: Inner.Index
|
||||
|
||||
@inlinable
|
||||
internal init(_ inner: Inner.Index) {
|
||||
self.inner = inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.inner == rhs.inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.inner < rhs.inner
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(inner.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(inner.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after index: Index) -> Index {
|
||||
Index(inner.index(after: index.inner))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Base.Element.Element {
|
||||
inner[position.inner]
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ index: Index, offsetBy distance: Int) -> Index {
|
||||
Index(inner.index(index.inner, offsetBy: distance))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ index: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
inner.index(index.inner, offsetBy: distance, limitedBy: limit.inner)
|
||||
.map(Index.init)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
inner.distance(from: start.inner, to: end.inner)
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByClosureCollection: BidirectionalCollection
|
||||
where
|
||||
Base: BidirectionalCollection,
|
||||
Base.Element: BidirectionalCollection,
|
||||
Separator: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
public func index(before index: Index) -> Index {
|
||||
Index(inner.index(before: index.inner))
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByClosureCollection: LazyCollectionProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Sequence.joined(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence where Element: Sequence {
|
||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
||||
/// inserting the given separator between each sequence.
|
||||
///
|
||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: 100) {
|
||||
/// print(x)
|
||||
/// }
|
||||
/// // 1, 2, 100, 3, 4, 100, 5, 6
|
||||
@inlinable
|
||||
public func joined(by separator: Element.Element)
|
||||
-> JoinedBySequence<Self, CollectionOfOne<Element.Element>>
|
||||
{
|
||||
joined(by: CollectionOfOne(separator))
|
||||
}
|
||||
|
||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
||||
/// inserting the given separator between each sequence.
|
||||
///
|
||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: [100, 200]) {
|
||||
/// print(x)
|
||||
/// }
|
||||
/// // 1, 2, 100, 200, 3, 4, 100, 200, 5, 6
|
||||
@inlinable
|
||||
public func joined<Separator>(
|
||||
by separator: Separator
|
||||
) -> JoinedBySequence<Self, Separator>
|
||||
where Separator: Collection, Separator.Element == Element.Element {
|
||||
JoinedBySequence(base: self, separator: separator)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _joined(
|
||||
by update: (inout [Element.Element], Element, Element) throws -> Void
|
||||
) rethrows -> [Element.Element] {
|
||||
var iterator = makeIterator()
|
||||
guard let first = iterator.next() else { return [] }
|
||||
|
||||
var result = Array(first)
|
||||
var previous = first
|
||||
|
||||
while let next = iterator.next() {
|
||||
try update(&result, previous, next)
|
||||
result.append(contentsOf: next)
|
||||
previous = next
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
||||
/// inserting the separator produced by the closure between each sequence.
|
||||
///
|
||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: { $0.last! * $1.first! }) {
|
||||
/// print(x)
|
||||
/// }
|
||||
/// // 1, 2, 6, 3, 4, 20, 5, 6
|
||||
@inlinable
|
||||
public func joined(
|
||||
by separator: (Element, Element) throws -> Element.Element
|
||||
) rethrows -> [Element.Element] {
|
||||
try _joined(by: { $0.append(try separator($1, $2)) })
|
||||
}
|
||||
|
||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
||||
/// inserting the separator produced by the closure between each sequence.
|
||||
///
|
||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: { [100 * $0.last!, 100 * $1.first!] }) {
|
||||
/// print(x)
|
||||
/// }
|
||||
/// // 1, 2, 200, 300, 3, 4, 400, 500, 5, 6
|
||||
@inlinable
|
||||
public func joined<Separator>(
|
||||
by separator: (Element, Element) throws -> Separator
|
||||
) rethrows -> [Element.Element]
|
||||
where Separator: Sequence, Separator.Element == Element.Element {
|
||||
try _joined(by: { $0.append(contentsOf: try separator($1, $2)) })
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// LazySequenceProtocol.joined(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension LazySequenceProtocol where Element: Sequence {
|
||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
||||
/// inserting the separator produced by the closure between each sequence.
|
||||
@inlinable
|
||||
public func joined(
|
||||
by separator: @escaping (Element, Element) -> Element.Element
|
||||
) -> JoinedByClosureSequence<Elements, CollectionOfOne<Element.Element>> {
|
||||
joined(by: { CollectionOfOne(separator($0, $1)) })
|
||||
}
|
||||
|
||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
||||
/// inserting the separator produced by the closure between each sequence.
|
||||
@inlinable
|
||||
public func joined<Separator>(
|
||||
by separator: @escaping (Element, Element) -> Separator
|
||||
) -> JoinedByClosureSequence<Elements, Separator> {
|
||||
JoinedByClosureSequence(base: elements, separator: separator)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Collection.joined(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection where Element: Collection {
|
||||
/// Returns the concatenation of the elements in this collection of
|
||||
/// collections, inserting the given separator between each collection.
|
||||
///
|
||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: 100) {
|
||||
/// print(x)
|
||||
/// }
|
||||
/// // 1, 2, 100, 3, 4, 100, 5, 6
|
||||
@inlinable
|
||||
public func joined(by separator: Element.Element)
|
||||
-> JoinedByCollection<Self, CollectionOfOne<Element.Element>>
|
||||
{
|
||||
joined(by: CollectionOfOne(separator))
|
||||
}
|
||||
|
||||
/// Returns the concatenation of the elements in this collection of
|
||||
/// collections, inserting the given separator between each collection.
|
||||
///
|
||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: [100, 200]) {
|
||||
/// print(x)
|
||||
/// }
|
||||
/// // 1, 2, 100, 200, 3, 4, 100, 200, 5, 6
|
||||
@inlinable
|
||||
public func joined<Separator>(by separator: Separator)
|
||||
-> JoinedByCollection<Self, Separator>
|
||||
{
|
||||
JoinedByCollection(base: self, separator: separator)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// LazySequenceProtocol.joined(by:) where Self: Collection
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension LazySequenceProtocol where Elements: Collection, Element: Collection {
|
||||
/// Returns the concatenation of the elements in this collection of
|
||||
/// collections, inserting the separator produced by the closure between each
|
||||
/// sequence.
|
||||
@inlinable
|
||||
public func joined(
|
||||
by separator: @escaping (Element, Element) -> Element.Element
|
||||
) -> JoinedByClosureCollection<Elements, CollectionOfOne<Element.Element>> {
|
||||
joined(by: { CollectionOfOne(separator($0, $1)) })
|
||||
}
|
||||
|
||||
/// Returns the concatenation of the elements in this collection of
|
||||
/// collections, inserting the separator produced by the closure between each
|
||||
/// sequence.
|
||||
@inlinable
|
||||
public func joined<Separator>(
|
||||
by separator: @escaping (Element, Element) -> Separator
|
||||
) -> JoinedByClosureCollection<Elements, Separator> {
|
||||
JoinedByClosureCollection(base: elements, separator: separator)
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Creates a new dictionary keyed by the result of the given closure, using
|
||||
/// the latest element for any duplicate keys.
|
||||
///
|
||||
/// If the key derived for a new element collides with an existing key from a
|
||||
/// previous element, the latest value will be kept.
|
||||
///
|
||||
/// - Parameter keyForValue: A closure that returns a key for each element in
|
||||
/// `self`.
|
||||
/// - Returns: A dictionary with key-value pairs generated by calling
|
||||
/// `keyForValue` for each element in this sequence. If `keyForValue`
|
||||
/// returns the same key for two or more elements, the returned dictionary
|
||||
/// uses the last value for that key.
|
||||
@inlinable
|
||||
public func keyed<Key>(
|
||||
by keyForValue: (Element) throws -> Key
|
||||
) rethrows -> [Key: Element] {
|
||||
try self.reduce(into: [:]) { result, element in
|
||||
try result[keyForValue(element)] = element
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new dictionary keyed by the result of the first closure, using
|
||||
/// the second closure to resolve the ambiguity for any duplicate keys.
|
||||
///
|
||||
/// As the dictionary is built, the initializer calls the `resolve` closure
|
||||
/// with the current and new values for any duplicate keys. Pass a closure as
|
||||
/// `resolve` that returns the value to use for that key in the resulting
|
||||
/// dictionary. The closure can choose between the two values, combine them to
|
||||
/// produce a new value, or even throw an error.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - keyForValue: A closure that returns a key for each element in `self`.
|
||||
/// - resolve: A closure that is called with the values for any duplicate
|
||||
/// keys that are encountered. The closure returns the desired value for
|
||||
/// the final dictionary.
|
||||
/// - Returns: A dictionary with key-value pairs generated by calling
|
||||
/// `keyForValue` for each element in this sequence. If `keyForValue`
|
||||
/// returns the same key for two or more elements, the result of the
|
||||
/// `resolve` closure is used as the value for that key.
|
||||
@inlinable
|
||||
public func keyed<Key>(
|
||||
by keyForValue: (Element) throws -> Key,
|
||||
resolvingConflictsWith resolve: (Key, Element, Element) throws -> Element
|
||||
) rethrows -> [Key: Element] {
|
||||
var result: [Key: Element] = [:]
|
||||
|
||||
for element in self {
|
||||
let key = try keyForValue(element)
|
||||
|
||||
if let oldValue = result.updateValue(element, forKey: key) {
|
||||
let valueToKeep = try resolve(key, oldValue, element)
|
||||
|
||||
// This causes a second look-up for the same key. The standard library can avoid that
|
||||
// by calling `mutatingFind` to get access to the bucket where the value will end up,
|
||||
// and updating in place.
|
||||
// Swift Algorithms doesn't have access to that API, so we make do.
|
||||
// When this gets merged into the standard library, we should optimize this.
|
||||
result[key] = valueToKeep
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,8 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// SplitSequence
|
||||
// LazySplitSequence
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence that lazily splits a base sequence into subsequences separated by
|
||||
/// elements that satisfy the given `whereSeparator` predicate.
|
||||
///
|
||||
@@ -22,24 +21,17 @@
|
||||
/// x.split(separator:maxSplits:omittingEmptySubsequences)
|
||||
///
|
||||
/// where `x` conforms to `LazySequenceProtocol`.
|
||||
public struct SplitSequence<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
public struct LazySplitSequence<Base: Sequence> {
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let isSeparator: (Base.Element) -> Bool
|
||||
@usableFromInline internal let isSeparator: (Base.Element) -> Bool
|
||||
|
||||
@usableFromInline
|
||||
internal let maxSplits: Int
|
||||
@usableFromInline internal let maxSplits: Int
|
||||
|
||||
@usableFromInline
|
||||
internal let omittingEmptySubsequences: Bool
|
||||
@usableFromInline internal let omittingEmptySubsequences: Bool
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
isSeparator: @escaping (Base.Element) -> Bool,
|
||||
maxSplits: Int,
|
||||
@inlinable internal init(
|
||||
base: Base, isSeparator: @escaping (Base.Element) -> Bool, maxSplits: Int,
|
||||
omittingEmptySubsequences: Bool
|
||||
) {
|
||||
self.base = base
|
||||
@@ -49,35 +41,26 @@ public struct SplitSequence<Base: Sequence> {
|
||||
}
|
||||
}
|
||||
|
||||
extension SplitSequence: Sequence {
|
||||
extension LazySplitSequence {
|
||||
public struct Iterator {
|
||||
public typealias Element = [Base.Element]
|
||||
|
||||
@usableFromInline
|
||||
internal var base: Base.Iterator
|
||||
@usableFromInline internal var base: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal let isSeparator: (Base.Element) -> Bool
|
||||
@usableFromInline internal let isSeparator: (Base.Element) -> Bool
|
||||
|
||||
@usableFromInline
|
||||
internal let maxSplits: Int
|
||||
@usableFromInline internal let maxSplits: Int
|
||||
|
||||
@usableFromInline
|
||||
internal let omittingEmptySubsequences: Bool
|
||||
@usableFromInline internal let omittingEmptySubsequences: Bool
|
||||
|
||||
/// The number of splits performed.
|
||||
@usableFromInline
|
||||
internal var splitCount = 0
|
||||
@usableFromInline internal var splitCount = 0
|
||||
|
||||
/// The number of subsequences returned.
|
||||
@usableFromInline
|
||||
internal var sequenceLength = 0
|
||||
@usableFromInline internal var sequenceLength = 0
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base.Iterator,
|
||||
whereSeparator: @escaping (Base.Element) -> Bool,
|
||||
maxSplits: Int,
|
||||
@inlinable internal init(
|
||||
base: Base.Iterator, whereSeparator: @escaping (Base.Element) -> Bool, maxSplits: Int,
|
||||
omittingEmptySubsequences: Bool
|
||||
) {
|
||||
self.base = base
|
||||
@@ -86,40 +69,29 @@ extension SplitSequence: Sequence {
|
||||
self.omittingEmptySubsequences = omittingEmptySubsequences
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(
|
||||
base: base.makeIterator(),
|
||||
whereSeparator: self.isSeparator,
|
||||
maxSplits: self.maxSplits,
|
||||
omittingEmptySubsequences: self.omittingEmptySubsequences
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension SplitSequence.Iterator: IteratorProtocol {
|
||||
@inlinable
|
||||
public mutating func next() -> Element? {
|
||||
var nextElement = base.next()
|
||||
extension LazySplitSequence.Iterator: IteratorProtocol {
|
||||
@inlinable public mutating func next() -> Element? {
|
||||
var currentElement = base.next()
|
||||
var subsequence: Element = []
|
||||
|
||||
// Add the next elements of the base sequence to this subsequence, until we
|
||||
// reach a separator, unless we've already split the maximum number of
|
||||
// times. In all cases, stop at the end of the base sequence.
|
||||
while let currentElement = nextElement {
|
||||
if splitCount < maxSplits && isSeparator(currentElement) {
|
||||
while currentElement != nil {
|
||||
if splitCount < maxSplits && isSeparator(currentElement!) {
|
||||
if omittingEmptySubsequences && subsequence.isEmpty {
|
||||
// Keep going if we don't want to return an empty subsequence.
|
||||
nextElement = base.next()
|
||||
currentElement = base.next()
|
||||
continue
|
||||
} else {
|
||||
splitCount += 1
|
||||
break
|
||||
}
|
||||
} else {
|
||||
subsequence.append(currentElement)
|
||||
nextElement = base.next()
|
||||
subsequence.append(currentElement!)
|
||||
currentElement = base.next()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,9 +99,8 @@ extension SplitSequence.Iterator: IteratorProtocol {
|
||||
// and we've either returned the maximum number of subsequences (one more
|
||||
// than the number of separators), or the only subsequence left to return is
|
||||
// empty and we're omitting those.
|
||||
if nextElement == nil
|
||||
&& (sequenceLength == splitCount + 1
|
||||
|| omittingEmptySubsequences && subsequence.isEmpty)
|
||||
if currentElement == nil
|
||||
&& (sequenceLength == splitCount + 1 || omittingEmptySubsequences && subsequence.isEmpty)
|
||||
{
|
||||
return nil
|
||||
} else {
|
||||
@@ -139,7 +110,13 @@ extension SplitSequence.Iterator: IteratorProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
extension SplitSequence: LazySequenceProtocol {}
|
||||
extension LazySplitSequence: LazySequenceProtocol {
|
||||
@inlinable public func makeIterator() -> Iterator {
|
||||
return Iterator(
|
||||
base: base.makeIterator(), whereSeparator: self.isSeparator, maxSplits: self.maxSplits,
|
||||
omittingEmptySubsequences: self.omittingEmptySubsequences)
|
||||
}
|
||||
}
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
/// Lazily returns the longest possible subsequences of the sequence, in
|
||||
@@ -219,27 +196,22 @@ extension LazySequenceProtocol {
|
||||
/// satisfying the `isSeparator` predicate and for each element at the
|
||||
/// start or end of the sequence satisfying the `isSeparator`
|
||||
/// predicate. The default value is `true`.
|
||||
/// - isSeparator: A closure that takes an element as an argument and
|
||||
/// - whereSeparator: A closure that takes an element as an argument and
|
||||
/// returns a Boolean value indicating whether the sequence should be
|
||||
/// split at that element.
|
||||
/// - Returns: A lazy sequence of subsequences, split from this sequence's
|
||||
/// elements.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func split(
|
||||
maxSplits: Int = Int.max,
|
||||
omittingEmptySubsequences: Bool = true,
|
||||
@inlinable public func split(
|
||||
maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true,
|
||||
whereSeparator isSeparator: @escaping (Element) -> Bool
|
||||
) -> SplitSequence<Elements> {
|
||||
) -> LazySplitSequence<Elements> {
|
||||
precondition(maxSplits >= 0, "Must take zero or more splits")
|
||||
|
||||
return SplitSequence(
|
||||
base: elements,
|
||||
isSeparator: isSeparator,
|
||||
maxSplits: maxSplits,
|
||||
omittingEmptySubsequences: omittingEmptySubsequences
|
||||
)
|
||||
return LazySplitSequence(
|
||||
base: elements, isSeparator: isSeparator, maxSplits: maxSplits,
|
||||
omittingEmptySubsequences: omittingEmptySubsequences)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -316,27 +288,20 @@ extension LazySequenceProtocol where Element: Equatable {
|
||||
/// elements.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func split(
|
||||
separator: Element,
|
||||
maxSplits: Int = Int.max,
|
||||
omittingEmptySubsequences: Bool = true
|
||||
) -> SplitSequence<Elements> {
|
||||
@inlinable public func split(
|
||||
separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true
|
||||
) -> LazySplitSequence<Elements> {
|
||||
precondition(maxSplits >= 0, "Must take zero or more splits")
|
||||
|
||||
return SplitSequence(
|
||||
base: elements,
|
||||
isSeparator: { $0 == separator },
|
||||
maxSplits: maxSplits,
|
||||
omittingEmptySubsequences: omittingEmptySubsequences
|
||||
)
|
||||
return LazySplitSequence(
|
||||
base: elements, isSeparator: { $0 == separator }, maxSplits: maxSplits,
|
||||
omittingEmptySubsequences: omittingEmptySubsequences)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// SplitCollection
|
||||
// LazySplitCollection
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection that lazily splits a base collection into subsequences
|
||||
/// separated by elements that satisfy the given `whereSeparator` predicate.
|
||||
///
|
||||
@@ -345,28 +310,20 @@ extension LazySequenceProtocol where Element: Equatable {
|
||||
/// x.split(maxSplits:omittingEmptySubsequences:whereSeparator)
|
||||
/// x.split(separator:maxSplits:omittingEmptySubsequences)
|
||||
///
|
||||
/// where `x` conforms to `LazySequenceProtocol` and `Collection`.
|
||||
public struct SplitCollection<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
/// where `x` conforms to `LazyCollectionProtocol`.
|
||||
public struct LazySplitCollection<Base: Collection> {
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let isSeparator: (Base.Element) -> Bool
|
||||
@usableFromInline internal let isSeparator: (Base.Element) -> Bool
|
||||
|
||||
@usableFromInline
|
||||
internal let maxSplits: Int
|
||||
@usableFromInline internal let maxSplits: Int
|
||||
|
||||
@usableFromInline
|
||||
internal let omittingEmptySubsequences: Bool
|
||||
@usableFromInline internal let omittingEmptySubsequences: Bool
|
||||
|
||||
@usableFromInline
|
||||
internal var _startIndex: Index
|
||||
@usableFromInline internal var _startIndex: Index
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
isSeparator: @escaping (Base.Element) -> Bool,
|
||||
maxSplits: Int,
|
||||
@inlinable internal init(
|
||||
base: Base, isSeparator: @escaping (Base.Element) -> Bool, maxSplits: Int,
|
||||
omittingEmptySubsequences: Bool
|
||||
) {
|
||||
self.base = base
|
||||
@@ -378,10 +335,7 @@ public struct SplitCollection<Base: Collection> {
|
||||
// 1. `base` is empty and we're _not_ omitting empty subsequences, in which
|
||||
// case the following index describes the sole element of this collection;
|
||||
self._startIndex = Index(
|
||||
baseRange: base.startIndex..<base.startIndex,
|
||||
sequenceLength: 1,
|
||||
splitCount: 0
|
||||
)
|
||||
baseRange: base.startIndex..<base.startIndex, sequenceLength: 1, splitCount: 0)
|
||||
if base.isEmpty {
|
||||
if omittingEmptySubsequences {
|
||||
// 2. `base` is empty and we _are_ omitting empty subsequences, so this
|
||||
@@ -392,62 +346,46 @@ public struct SplitCollection<Base: Collection> {
|
||||
// 3. `base` isn't empty, so we must iterate it to determine the start
|
||||
// index.
|
||||
_startIndex = indexForSubsequence(
|
||||
atOrAfter: base.startIndex,
|
||||
sequenceLength: 0,
|
||||
splitCount: 0
|
||||
)
|
||||
atOrAfter: base.startIndex, sequenceLength: 0, splitCount: 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SplitCollection: Collection {
|
||||
extension LazySplitCollection: LazyCollectionProtocol {
|
||||
/// Position of a subsequence in a split collection.
|
||||
public struct Index: Comparable {
|
||||
/// The range corresponding to the subsequence at this position.
|
||||
@usableFromInline
|
||||
internal let baseRange: Range<Base.Index>
|
||||
@usableFromInline internal let baseRange: Range<Base.Index>
|
||||
|
||||
/// The number of subsequences up to and including this position in the
|
||||
/// collection.
|
||||
@usableFromInline
|
||||
internal let sequenceLength: Int
|
||||
@usableFromInline internal let sequenceLength: Int
|
||||
|
||||
/// The number splits performed up to and including this position in the
|
||||
/// collection.
|
||||
@usableFromInline
|
||||
internal let splitCount: Int
|
||||
@usableFromInline internal let splitCount: Int
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
baseRange: Range<Base.Index>,
|
||||
sequenceLength: Int,
|
||||
splitCount: Int
|
||||
) {
|
||||
@inlinable internal init(baseRange: Range<Base.Index>, sequenceLength: Int, splitCount: Int) {
|
||||
self.baseRange = baseRange
|
||||
self.sequenceLength = sequenceLength
|
||||
self.splitCount = splitCount
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||
@inlinable public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||
// `sequenceLength` is equivalent to the index's 1-based position in the
|
||||
// collection of indices.
|
||||
lhs.sequenceLength == rhs.sequenceLength
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.sequenceLength < rhs.sequenceLength
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the index of the subsequence starting at or after the given base
|
||||
/// collection index.
|
||||
@inlinable
|
||||
internal func indexForSubsequence(
|
||||
atOrAfter lowerBound: Base.Index,
|
||||
sequenceLength: Int,
|
||||
splitCount: Int
|
||||
@inlinable internal func indexForSubsequence(
|
||||
atOrAfter lowerBound: Base.Index, sequenceLength: Int, splitCount: Int
|
||||
) -> Index {
|
||||
var start = lowerBound
|
||||
// If we don't have any more splits to do (which we'll determine shortly),
|
||||
@@ -457,16 +395,12 @@ extension SplitCollection: Collection {
|
||||
if splitCount < maxSplits {
|
||||
// The non-inclusive end of this subsequence is marked by the next
|
||||
// separator, or the end of the base collection.
|
||||
end =
|
||||
base[start...].firstIndex(where: isSeparator)
|
||||
?? base.endIndex
|
||||
end = base[start...].firstIndex(where: isSeparator) ?? base.endIndex
|
||||
|
||||
if base[start..<end].isEmpty {
|
||||
if omittingEmptySubsequences {
|
||||
// Find the next subsequence of non-separators.
|
||||
start =
|
||||
base[end...].firstIndex(where: { !isSeparator($0) })
|
||||
?? base.endIndex
|
||||
start = base[end...].firstIndex(where: { !isSeparator($0) }) ?? base.endIndex
|
||||
if start == base.endIndex {
|
||||
// No non-separators left in the base collection. We're done.
|
||||
return endIndex
|
||||
@@ -477,7 +411,7 @@ extension SplitCollection: Collection {
|
||||
}
|
||||
|
||||
var updatedSplitCount = splitCount
|
||||
if end != base.endIndex {
|
||||
if end < base.endIndex {
|
||||
// This subsequence ends on a separator (and perhaps includes other
|
||||
// separators, if we're omitting empty subsequences), so we've performed
|
||||
// another split.
|
||||
@@ -485,80 +419,55 @@ extension SplitCollection: Collection {
|
||||
}
|
||||
|
||||
return Index(
|
||||
baseRange: start..<end,
|
||||
sequenceLength: sequenceLength + 1,
|
||||
splitCount: updatedSplitCount
|
||||
)
|
||||
baseRange: start..<end, sequenceLength: sequenceLength + 1, splitCount: updatedSplitCount)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
_startIndex
|
||||
@inlinable public var startIndex: Index { _startIndex }
|
||||
|
||||
@inlinable public var endIndex: Index {
|
||||
Index(baseRange: base.endIndex..<base.endIndex, sequenceLength: Int.max, splitCount: Int.max)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(
|
||||
baseRange: base.endIndex..<base.endIndex,
|
||||
sequenceLength: Int.max,
|
||||
splitCount: Int.max
|
||||
)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
@inlinable public func index(after i: Index) -> Index {
|
||||
precondition(i != endIndex, "Can't advance past endIndex")
|
||||
|
||||
var subsequenceStart = i.baseRange.upperBound
|
||||
if subsequenceStart < base.endIndex {
|
||||
// If we're not already at the end of the base collection, the previous
|
||||
// subsequence ended with a separator. Start searching for the next
|
||||
// susequence ended with a separator. Start searching for the next
|
||||
// subsequence at the following element.
|
||||
subsequenceStart = base.index(after: i.baseRange.upperBound)
|
||||
}
|
||||
|
||||
guard subsequenceStart != base.endIndex else {
|
||||
if !omittingEmptySubsequences
|
||||
&& i.sequenceLength < i.splitCount + 1
|
||||
{
|
||||
if !omittingEmptySubsequences && i.sequenceLength < i.splitCount + 1 {
|
||||
// The base collection ended with a separator, so we need to emit one
|
||||
// more empty subsequence. This one differs from `endIndex` in its
|
||||
// `sequenceLength` (except in an extreme edge case!), which is the
|
||||
// sole property tested for equality and comparison.
|
||||
return Index(
|
||||
baseRange: base.endIndex..<base.endIndex,
|
||||
sequenceLength: i.sequenceLength + 1,
|
||||
splitCount: i.splitCount
|
||||
)
|
||||
baseRange: base.endIndex..<base.endIndex, sequenceLength: i.sequenceLength + 1,
|
||||
splitCount: i.splitCount)
|
||||
} else {
|
||||
return endIndex
|
||||
}
|
||||
}
|
||||
|
||||
return indexForSubsequence(
|
||||
atOrAfter: subsequenceStart,
|
||||
sequenceLength: i.sequenceLength,
|
||||
splitCount: i.splitCount
|
||||
)
|
||||
atOrAfter: subsequenceStart, sequenceLength: i.sequenceLength, splitCount: i.splitCount)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Base.SubSequence {
|
||||
@inlinable public subscript(position: Index) -> Base.SubSequence {
|
||||
precondition(position != endIndex, "Can't subscript using endIndex")
|
||||
return base[position.baseRange]
|
||||
}
|
||||
}
|
||||
|
||||
extension SplitCollection.Index: Hashable {
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(sequenceLength)
|
||||
}
|
||||
extension LazySplitCollection.Index: Hashable {
|
||||
public func hash(into hasher: inout Hasher) { hasher.combine(sequenceLength) }
|
||||
}
|
||||
|
||||
extension SplitCollection: LazyCollectionProtocol {}
|
||||
|
||||
extension LazySequenceProtocol where Self: Collection, Elements: Collection {
|
||||
extension LazyCollectionProtocol {
|
||||
/// Lazily returns the longest possible subsequences of the collection, in
|
||||
/// order, that don't contain elements satisfying the given predicate.
|
||||
///
|
||||
@@ -634,32 +543,26 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
|
||||
/// satisfying the `isSeparator` predicate and for each element at the
|
||||
/// start or end of the collection satisfying the `isSeparator`
|
||||
/// predicate. The default value is `true`.
|
||||
/// - isSeparator: A closure that takes an element as an argument and
|
||||
/// - whereSeparator: A closure that takes an element as an argument and
|
||||
/// returns a Boolean value indicating whether the collection should be
|
||||
/// split at that element.
|
||||
/// - Returns: A lazy collection of subsequences, split from this collection's
|
||||
/// elements.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func split(
|
||||
maxSplits: Int = Int.max,
|
||||
omittingEmptySubsequences: Bool = true,
|
||||
@inlinable public func split(
|
||||
maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true,
|
||||
whereSeparator isSeparator: @escaping (Element) -> Bool
|
||||
) -> SplitCollection<Elements> {
|
||||
) -> LazySplitCollection<Elements> {
|
||||
precondition(maxSplits >= 0, "Must take zero or more splits")
|
||||
|
||||
return SplitCollection(
|
||||
base: elements,
|
||||
isSeparator: isSeparator,
|
||||
maxSplits: maxSplits,
|
||||
omittingEmptySubsequences: omittingEmptySubsequences
|
||||
)
|
||||
return LazySplitCollection(
|
||||
base: elements, isSeparator: isSeparator, maxSplits: maxSplits,
|
||||
omittingEmptySubsequences: omittingEmptySubsequences)
|
||||
}
|
||||
}
|
||||
|
||||
extension LazySequenceProtocol
|
||||
where Self: Collection, Elements: Collection, Element: Equatable {
|
||||
extension LazyCollectionProtocol where Element: Equatable {
|
||||
/// Lazily returns the longest possible subsequences of the collection, in
|
||||
/// order, around elements equal to the given element.
|
||||
///
|
||||
@@ -737,19 +640,13 @@ where Self: Collection, Elements: Collection, Element: Equatable {
|
||||
/// elements.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func split(
|
||||
separator: Element,
|
||||
maxSplits: Int = Int.max,
|
||||
omittingEmptySubsequences: Bool = true
|
||||
) -> SplitCollection<Elements> {
|
||||
@inlinable public func split(
|
||||
separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true
|
||||
) -> LazySplitCollection<Elements> {
|
||||
precondition(maxSplits >= 0, "Must take zero or more splits")
|
||||
|
||||
return SplitCollection(
|
||||
base: elements,
|
||||
isSeparator: { $0 == separator },
|
||||
maxSplits: maxSplits,
|
||||
omittingEmptySubsequences: omittingEmptySubsequences
|
||||
)
|
||||
return LazySplitCollection(
|
||||
base: elements, isSeparator: { $0 == separator }, maxSplits: maxSplits,
|
||||
omittingEmptySubsequences: omittingEmptySubsequences)
|
||||
}
|
||||
}
|
||||
+43
-182
@@ -10,53 +10,45 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
// Implementation for min(count:areInIncreasingOrder:)
|
||||
@inlinable
|
||||
internal func _minImplementation(
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
/// Implementation for min(count:areInIncreasingOrder:)
|
||||
@inlinable internal func _minImplementation(
|
||||
count: Int, 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)
|
||||
}
|
||||
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[count - 1]`.
|
||||
guard try areInIncreasingOrder(e, result[count - 1]) else { continue }
|
||||
// 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()
|
||||
let insertionIndex =
|
||||
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
|
||||
result.insert(e, at: insertionIndex)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Implementation for max(count:areInIncreasingOrder:)
|
||||
@inlinable
|
||||
internal func _maxImplementation(
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
/// Implementation for max(count:areInIncreasingOrder:)
|
||||
@inlinable internal func _maxImplementation(
|
||||
count: Int, 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)
|
||||
}
|
||||
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[0]`.
|
||||
guard try !areInIncreasingOrder(e, result[0]) else { continue }
|
||||
let insertionIndex =
|
||||
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
|
||||
// To be part of `result`, `e` must be greater/equal to `result.first`.
|
||||
guard try !areInIncreasingOrder(e, result.first!) else { continue }
|
||||
let insertionIndex = try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
|
||||
|
||||
assert(insertionIndex > 0)
|
||||
// Inserting `e` and then removing the first element (or vice versa)
|
||||
@@ -100,22 +92,17 @@ extension Sequence {
|
||||
///
|
||||
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
|
||||
/// sequence and *k* is `count`.
|
||||
@inlinable
|
||||
public func min(
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
@inlinable public func min(
|
||||
count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
precondition(
|
||||
count >= 0,
|
||||
"""
|
||||
Cannot find a minimum with a negative count of elements!
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
// Do nothing if we're prefixing nothing.
|
||||
guard count > 0 else {
|
||||
return []
|
||||
}
|
||||
guard count > 0 else { return [] }
|
||||
|
||||
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
|
||||
}
|
||||
@@ -127,7 +114,7 @@ extension Sequence {
|
||||
/// largest values:
|
||||
///
|
||||
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
/// let largestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// let smallestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// // [7, 8, 9]
|
||||
///
|
||||
/// If you need to sort a sequence but only need to access its largest
|
||||
@@ -147,22 +134,17 @@ extension Sequence {
|
||||
///
|
||||
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
|
||||
/// sequence and *k* is `count`.
|
||||
@inlinable
|
||||
public func max(
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
@inlinable public func max(
|
||||
count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
precondition(
|
||||
count >= 0,
|
||||
"""
|
||||
Cannot find a maximum with a negative count of elements!
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
// Do nothing if we're suffixing nothing.
|
||||
guard count > 0 else {
|
||||
return []
|
||||
}
|
||||
guard count > 0 else { return [] }
|
||||
|
||||
return try _maxImplementation(count: count, sortedBy: areInIncreasingOrder)
|
||||
}
|
||||
@@ -190,10 +172,7 @@ extension Sequence where Element: Comparable {
|
||||
///
|
||||
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
|
||||
/// sequence and *k* is `count`.
|
||||
@inlinable
|
||||
public func min(count: Int) -> [Element] {
|
||||
min(count: count, sortedBy: <)
|
||||
}
|
||||
@inlinable public func min(count: Int) -> [Element] { return min(count: count, sortedBy: <) }
|
||||
|
||||
/// Returns the largest elements of this sequence.
|
||||
///
|
||||
@@ -201,7 +180,7 @@ extension Sequence where Element: Comparable {
|
||||
/// largest values:
|
||||
///
|
||||
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
/// let largestThree = numbers.max(count: 3)
|
||||
/// let smallestThree = numbers.max(count: 3)
|
||||
/// // [7, 8, 9]
|
||||
///
|
||||
/// If you need to sort a sequence but only need to access its largest
|
||||
@@ -216,10 +195,7 @@ extension Sequence where Element: Comparable {
|
||||
///
|
||||
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
|
||||
/// sequence and *k* is `count`.
|
||||
@inlinable
|
||||
public func max(count: Int) -> [Element] {
|
||||
max(count: count, sortedBy: <)
|
||||
}
|
||||
@inlinable public func max(count: Int) -> [Element] { return max(count: count, sortedBy: <) }
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
@@ -250,26 +226,21 @@ extension Collection {
|
||||
///
|
||||
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
|
||||
/// collection and *k* is `count`.
|
||||
@inlinable
|
||||
public func min(
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
@inlinable public func min(
|
||||
count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
precondition(
|
||||
count >= 0,
|
||||
"""
|
||||
Cannot find a minimum with a negative count of elements!
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
// Do nothing if we're prefixing nothing.
|
||||
guard count > 0 else { return [] }
|
||||
|
||||
// Make sure we are within bounds.
|
||||
let prefixCount = Swift.min(count, self.count)
|
||||
|
||||
// Do nothing if we're prefixing nothing.
|
||||
guard prefixCount > 0 else {
|
||||
return []
|
||||
}
|
||||
|
||||
// If we're attempting to prefix more than 10% of the collection, it's
|
||||
// faster to sort everything.
|
||||
guard prefixCount < (self.count / 10) else {
|
||||
@@ -286,7 +257,7 @@ extension Collection {
|
||||
/// largest values:
|
||||
///
|
||||
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
/// let largestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// let smallestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// // [7, 8, 9]
|
||||
///
|
||||
/// If you need to sort a collection but only need to access its largest
|
||||
@@ -306,26 +277,21 @@ extension Collection {
|
||||
///
|
||||
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
|
||||
/// collection and *k* is `count`.
|
||||
@inlinable
|
||||
public func max(
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
@inlinable public func max(
|
||||
count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
precondition(
|
||||
count >= 0,
|
||||
"""
|
||||
Cannot find a maximum with a negative count of elements!
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
// Do nothing if we're suffixing nothing.
|
||||
guard count > 0 else { return [] }
|
||||
|
||||
// Make sure we are within bounds.
|
||||
let suffixCount = Swift.min(count, self.count)
|
||||
|
||||
// Do nothing if we're suffixing nothing.
|
||||
guard suffixCount > 0 else {
|
||||
return []
|
||||
}
|
||||
|
||||
// If we're attempting to prefix more than 10% of the collection, it's
|
||||
// faster to sort everything.
|
||||
guard suffixCount < (self.count / 10) else {
|
||||
@@ -358,10 +324,7 @@ extension Collection where Element: Comparable {
|
||||
///
|
||||
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
|
||||
/// collection and *k* is `count`.
|
||||
@inlinable
|
||||
public func min(count: Int) -> [Element] {
|
||||
min(count: count, sortedBy: <)
|
||||
}
|
||||
@inlinable public func min(count: Int) -> [Element] { return min(count: count, sortedBy: <) }
|
||||
|
||||
/// Returns the largest elements of this collection.
|
||||
///
|
||||
@@ -384,107 +347,5 @@ extension Collection where Element: Comparable {
|
||||
///
|
||||
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
|
||||
/// collection and *k* is `count`.
|
||||
@inlinable
|
||||
public func max(count: Int) -> [Element] {
|
||||
max(count: count, sortedBy: <)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Simultaneous minimum and maximum evaluation
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Returns both the minimum and maximum elements in the sequence, using the
|
||||
/// given predicate as the comparison between elements.
|
||||
///
|
||||
/// The predicate must be a *strict weak ordering* over the elements. That is,
|
||||
/// for any elements `a`, `b`, and `c`, the following conditions must hold:
|
||||
///
|
||||
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
|
||||
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
|
||||
/// both `true`, then `areInIncreasingOrder(a, c)` is also
|
||||
/// `true`. (Transitive comparability)
|
||||
/// - Two elements are *incomparable* if neither is ordered before the other
|
||||
/// according to the predicate. If `a` and `b` are incomparable, and `b`
|
||||
/// and `c` are incomparable, then `a` and `c` are also incomparable.
|
||||
/// (Transitive incomparability)
|
||||
///
|
||||
/// This example shows how to use the `minAndMax(by:)` method on a dictionary
|
||||
/// to find the key-value pair with the lowest value and the pair with the
|
||||
/// highest value.
|
||||
///
|
||||
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
|
||||
/// if let extremeHues = hues.minAndMax(by: {$0.value < $1.value}) {
|
||||
/// print(extremeHues.min, extremeHues.max)
|
||||
/// } else {
|
||||
/// print("There are no hues")
|
||||
/// }
|
||||
/// // Prints: "(key: "Coral", value: 16) (key: "Heliotrope", value: 296)"
|
||||
///
|
||||
/// - Precondition: The sequence is finite.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
|
||||
/// first argument should be ordered before its second argument; otherwise,
|
||||
/// `false`.
|
||||
/// - Returns: A tuple with the sequence's minimum element, followed by its
|
||||
/// maximum element. If the sequence provides multiple qualifying minimum
|
||||
/// elements, the first equivalent element is returned; of multiple maximum
|
||||
/// elements, the last is returned. If the sequence has no elements, the
|
||||
/// method returns `nil`.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func minAndMax(
|
||||
by areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> (min: Element, max: Element)? {
|
||||
// Check short sequences.
|
||||
var iterator = makeIterator()
|
||||
guard var lowest = iterator.next() else { return nil }
|
||||
guard var highest = iterator.next() else { return (lowest, lowest) }
|
||||
|
||||
// Confirm the initial bounds.
|
||||
if try areInIncreasingOrder(highest, lowest) { swap(&lowest, &highest) }
|
||||
|
||||
// Read the elements in pairwise. Structuring the comparisons around this
|
||||
// is actually faster than loops based on extracting and testing elements
|
||||
// one-at-a-time.
|
||||
while var low = iterator.next() {
|
||||
var high = iterator.next() ?? low
|
||||
if try areInIncreasingOrder(high, low) { swap(&low, &high) }
|
||||
if try areInIncreasingOrder(low, lowest) { lowest = low }
|
||||
if try !areInIncreasingOrder(high, highest) { highest = high }
|
||||
}
|
||||
|
||||
return (lowest, highest)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Element: Comparable {
|
||||
/// Returns both the minimum and maximum elements in the sequence.
|
||||
///
|
||||
/// This example finds the smallest and largest values in an array of height
|
||||
/// measurements.
|
||||
///
|
||||
/// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
|
||||
/// if let (lowestHeight, greatestHeight) = heights.minAndMax() {
|
||||
/// print(lowestHeight, greatestHeight)
|
||||
/// } else {
|
||||
/// print("The list of heights is empty")
|
||||
/// }
|
||||
/// // Prints: "58.5 67.5"
|
||||
///
|
||||
/// - Precondition: The sequence is finite.
|
||||
///
|
||||
/// - Returns: A tuple with the sequence's minimum element, followed by its
|
||||
/// maximum element. If the sequence provides multiple qualifying minimum
|
||||
/// elements, the first equivalent element is returned; of multiple maximum
|
||||
/// elements, the last is returned. If the sequence has no elements, the
|
||||
/// method returns `nil`.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func minAndMax() -> (min: Element, max: Element)? {
|
||||
minAndMax(by: <)
|
||||
}
|
||||
@inlinable public func max(count: Int) -> [Element] { return max(count: count, sortedBy: <) }
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -14,36 +14,28 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension MutableCollection {
|
||||
/// Moves all elements satisfying `belongsInSecondPartition` into a suffix of
|
||||
/// the collection, preserving their relative order, and returns the start of
|
||||
/// the resulting suffix.
|
||||
/// Moves all elements satisfying `belongsInSecondPartition` into a suffix
|
||||
/// of the collection, preserving their relative order, and returns the
|
||||
/// start of the resulting suffix.
|
||||
///
|
||||
/// - Complexity: O(*n* log *n*), where *n* is the number of elements.
|
||||
/// - Precondition:
|
||||
/// `n == distance(from: range.lowerBound, to: range.upperBound)`
|
||||
@inlinable
|
||||
internal mutating func stablePartition(
|
||||
count n: Int,
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
@inlinable internal mutating func stablePartition(
|
||||
count n: Int, subrange: Range<Index>, by belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
if n == 0 { return subrange.lowerBound }
|
||||
if n == 1 {
|
||||
return try belongsInSecondPartition(self[subrange.lowerBound])
|
||||
? subrange.lowerBound
|
||||
: subrange.upperBound
|
||||
? subrange.lowerBound : subrange.upperBound
|
||||
}
|
||||
|
||||
let h = n / 2
|
||||
let i = index(subrange.lowerBound, offsetBy: h)
|
||||
let j = try stablePartition(
|
||||
count: h,
|
||||
subrange: subrange.lowerBound..<i,
|
||||
by: belongsInSecondPartition)
|
||||
count: h, subrange: subrange.lowerBound..<i, by: belongsInSecondPartition)
|
||||
let k = try stablePartition(
|
||||
count: n - h,
|
||||
subrange: i..<subrange.upperBound,
|
||||
by: belongsInSecondPartition)
|
||||
count: n - h, subrange: i..<subrange.upperBound, by: belongsInSecondPartition)
|
||||
return rotate(subrange: j..<k, toStartAt: i)
|
||||
}
|
||||
|
||||
@@ -56,20 +48,13 @@ extension MutableCollection {
|
||||
/// - belongsInSecondPartition: A predicate used to partition the
|
||||
/// collection. All elements satisfying this predicate are ordered after
|
||||
/// all elements not satisfying it.
|
||||
/// - Returns: The pivot index `p`, which is the index of the first element
|
||||
/// in the reordered collection that matches `belongsInSecondPartition`.
|
||||
/// If no elements in the collection match `belongsInSecondPartition`, the
|
||||
/// returned index is equal to the collection's `endIndex`.
|
||||
///
|
||||
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public mutating func stablePartition(
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
@inlinable public mutating func stablePartition(
|
||||
subrange: Range<Index>, by belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
try stablePartition(
|
||||
count: distance(from: subrange.lowerBound, to: subrange.upperBound),
|
||||
subrange: subrange,
|
||||
count: distance(from: subrange.lowerBound, to: subrange.upperBound), subrange: subrange,
|
||||
by: belongsInSecondPartition)
|
||||
}
|
||||
|
||||
@@ -80,19 +65,12 @@ extension MutableCollection {
|
||||
/// - Parameter belongsInSecondPartition: A predicate used to partition the
|
||||
/// collection. All elements satisfying this predicate are ordered after
|
||||
/// all elements not satisfying it.
|
||||
/// - Returns: The pivot index `p`, which is the index of the first element
|
||||
/// in the reordered collection that matches `belongsInSecondPartition`.
|
||||
/// If no elements in the collection match `belongsInSecondPartition`, the
|
||||
/// returned index is equal to the collection's `endIndex`.
|
||||
///
|
||||
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public mutating func stablePartition(
|
||||
@inlinable public mutating func stablePartition(
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
try stablePartition(
|
||||
subrange: startIndex..<endIndex,
|
||||
by: belongsInSecondPartition)
|
||||
try stablePartition(subrange: startIndex..<endIndex, by: belongsInSecondPartition)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,35 +79,18 @@ extension MutableCollection {
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension MutableCollection {
|
||||
/// Moves all elements satisfying the given closure into a suffix of the
|
||||
/// Moves all elements satisfying `isSuffixElement` into a suffix of the
|
||||
/// collection, returning the start position of the resulting suffix.
|
||||
///
|
||||
/// After partitioning a collection, there is a pivot index `p` where no
|
||||
/// element before `p` satisfies the `belongsInSecondPartition` predicate and
|
||||
/// every element at or after `p` satisfies `belongsInSecondPartition`. This
|
||||
/// operation isn't guaranteed to be stable, so the relative ordering of
|
||||
/// elements within the partitions might change.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - subrange: The range of elements within this collection to partition.
|
||||
/// - belongsInSecondPartition: A predicate used to partition the
|
||||
/// collection. All elements satisfying this predicate are ordered after
|
||||
/// all elements not satisfying it.
|
||||
/// - Returns: The pivot index `p`, which is the index of the first element
|
||||
/// in the reordered collection that matches `belongsInSecondPartition`.
|
||||
/// If no elements in the collection match `belongsInSecondPartition`, the
|
||||
/// returned index is equal to the collection's `endIndex`.
|
||||
///
|
||||
/// - Complexity: O(*n*) where n is the length of the collection.
|
||||
@inlinable
|
||||
public mutating func partition(
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
@inlinable public mutating func partition(
|
||||
subrange: Range<Index>, by belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
// 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 }
|
||||
guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition) else {
|
||||
return subrange.upperBound
|
||||
}
|
||||
|
||||
var j = index(after: i)
|
||||
while j != subrange.upperBound {
|
||||
@@ -145,30 +106,12 @@ extension MutableCollection {
|
||||
}
|
||||
|
||||
extension MutableCollection where Self: BidirectionalCollection {
|
||||
/// Moves all elements satisfying the given closure into a suffix of the
|
||||
/// Moves all elements satisfying `isSuffixElement` into a suffix of the
|
||||
/// collection, returning the start position of the resulting suffix.
|
||||
///
|
||||
/// After partitioning a collection, there is a pivot index `p` where no
|
||||
/// element before `p` satisfies the `belongsInSecondPartition` predicate and
|
||||
/// every element at or after `p` satisfies `belongsInSecondPartition`. This
|
||||
/// operation isn't guaranteed to be stable, so the relative ordering of
|
||||
/// elements within the partitions might change.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - subrange: The range of elements within this collection to partition.
|
||||
/// - belongsInSecondPartition: A predicate used to partition the
|
||||
/// collection. All elements satisfying this predicate are ordered after
|
||||
/// all elements not satisfying it.
|
||||
/// - Returns: The pivot index `p`, which is the index of the first element
|
||||
/// in the reordered collection that matches `belongsInSecondPartition`.
|
||||
/// If no elements in the collection match `belongsInSecondPartition`, the
|
||||
/// returned index is equal to the collection's `endIndex`.
|
||||
///
|
||||
/// - Complexity: O(*n*) where n is the length of the collection.
|
||||
@inlinable
|
||||
public mutating func partition(
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
@inlinable public mutating func partition(
|
||||
subrange: Range<Index>, by belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
var lo = subrange.lowerBound
|
||||
var hi = subrange.upperBound
|
||||
@@ -179,22 +122,22 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
// * predicate(self[i]) == true, for i in hi ..< endIndex
|
||||
|
||||
Loop: while true {
|
||||
FindLo: do {
|
||||
FindLo: repeat {
|
||||
while lo < hi {
|
||||
if try belongsInSecondPartition(self[lo]) { break FindLo }
|
||||
formIndex(after: &lo)
|
||||
}
|
||||
break Loop
|
||||
}
|
||||
} while false
|
||||
|
||||
FindHi: do {
|
||||
FindHi: repeat {
|
||||
formIndex(before: &hi)
|
||||
while lo < hi {
|
||||
if try !belongsInSecondPartition(self[hi]) { break FindHi }
|
||||
formIndex(before: &hi)
|
||||
}
|
||||
break Loop
|
||||
}
|
||||
} while false
|
||||
|
||||
swapAt(lo, hi)
|
||||
formIndex(after: &lo)
|
||||
@@ -209,26 +152,24 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection {
|
||||
/// Returns the start index of the partition of a collection that matches
|
||||
/// the given predicate.
|
||||
/// Returns the index of the first element in the collection that matches
|
||||
/// the predicate.
|
||||
///
|
||||
/// The collection must already be partitioned according to the predicate.
|
||||
/// That is, there should be an index `i` where for every element in
|
||||
/// `collection[..<i]` the predicate is `false`, and for every element in
|
||||
/// `collection[i...]` the predicate is `true`.
|
||||
/// `collection[..<i]` the predicate is `false`, and for every element
|
||||
/// in `collection[i...]` the predicate is `true`.
|
||||
///
|
||||
/// - Parameter belongsInSecondPartition: A predicate that partitions the
|
||||
/// collection.
|
||||
/// - Returns: The index of the first element in the collection for which
|
||||
/// `predicate` returns `true`, or `endIndex` if there are no elements
|
||||
/// for which `predicate` returns `true`.
|
||||
/// `predicate` returns `true`.
|
||||
///
|
||||
/// - Complexity: O(log *n*), where *n* is the length of this collection if
|
||||
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
|
||||
@inlinable
|
||||
public func partitioningIndex(
|
||||
where belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
@inlinable public func partitioningIndex(where belongsInSecondPartition: (Element) throws -> Bool)
|
||||
rethrows -> Index
|
||||
{
|
||||
var n = count
|
||||
var l = startIndex
|
||||
|
||||
@@ -245,145 +186,3 @@ extension Collection {
|
||||
return l
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// partitioned(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Returns two arrays containing the elements of the sequence that
|
||||
/// don’t and do satisfy the given predicate, respectively.
|
||||
///
|
||||
/// In this example, `partitioned(by:)` is used to separate the input based on
|
||||
/// whether a name is shorter than five characters:
|
||||
///
|
||||
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
||||
/// let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
||||
/// print(longNames)
|
||||
/// // Prints "["Vivien", "Marlon"]"
|
||||
/// print(shortNames)
|
||||
/// // Prints "["Kim", "Karl"]"
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the sequence as
|
||||
/// its argument and returns a Boolean value indicating whether the element
|
||||
/// should be included in the second returned array. Otherwise, the element
|
||||
/// will appear in the first returned array.
|
||||
/// - Returns: Two arrays with all of the elements of the receiver. The
|
||||
/// first array contains all the elements that `predicate` didn’t allow, and
|
||||
/// the second array contains all the elements that `predicate` allowed. The
|
||||
/// order of the elements in the arrays matches the order of the elements in
|
||||
/// the original sequence.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func partitioned(
|
||||
by predicate: (Element) throws -> Bool
|
||||
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
|
||||
var lhs: [Element] = []
|
||||
var rhs: [Element] = []
|
||||
|
||||
for element in self {
|
||||
if try predicate(element) {
|
||||
rhs.append(element)
|
||||
} else {
|
||||
lhs.append(element)
|
||||
}
|
||||
}
|
||||
|
||||
return (lhs, rhs)
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
/// Returns two arrays containing the elements of the collection that
|
||||
/// don’t and do satisfy the given predicate, respectively.
|
||||
///
|
||||
/// In this example, `partitioned(by:)` is used to separate the input based on
|
||||
/// whether a name is shorter than five characters.
|
||||
///
|
||||
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
||||
/// let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
||||
/// print(longNames)
|
||||
/// // Prints "["Vivien", "Marlon"]"
|
||||
/// print(shortNames)
|
||||
/// // Prints "["Kim", "Karl"]"
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the collection
|
||||
/// as its argument and returns a Boolean value indicating whether the
|
||||
/// element should be included in the second returned array. Otherwise, the
|
||||
/// element will appear in the first returned array.
|
||||
/// - Returns: Two arrays with all of the elements of the receiver. The
|
||||
/// first array contains all the elements that `predicate` didn’t allow, and
|
||||
/// the second array contains all the elements that `predicate` allowed. The
|
||||
/// order of the elements in the arrays matches the order of the elements in
|
||||
/// the original collection.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func partitioned(
|
||||
by predicate: (Element) throws -> Bool
|
||||
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
|
||||
guard !self.isEmpty else {
|
||||
return ([], [])
|
||||
}
|
||||
|
||||
// Since collections have known sizes, we can allocate one array of size
|
||||
// `self.count`, then insert items at the beginning or end of that contiguous
|
||||
// block. This way, we don’t have to do any dynamic array resizing. Since we
|
||||
// insert the right elements on the right side in reverse order, we need to
|
||||
// reverse them back to the original order at the end.
|
||||
|
||||
let count = self.count
|
||||
|
||||
// Inside of the `initializer` closure, we set what the actual mid-point is.
|
||||
// We will use this to partition the single array into two.
|
||||
var midPoint: Int = 0
|
||||
|
||||
let elements = try [Element](
|
||||
unsafeUninitializedCapacity: count,
|
||||
initializingWith: { buffer, initializedCount in
|
||||
// swift-format-ignore: NeverForceUnwrap
|
||||
// Non-empty check above.
|
||||
let bufferStart = buffer.baseAddress!
|
||||
var lhs = bufferStart
|
||||
var rhs = lhs + buffer.count
|
||||
do {
|
||||
for element in self {
|
||||
if try predicate(element) {
|
||||
rhs -= 1
|
||||
rhs.initialize(to: element)
|
||||
} else {
|
||||
lhs.initialize(to: element)
|
||||
lhs += 1
|
||||
}
|
||||
}
|
||||
|
||||
precondition(
|
||||
lhs == rhs,
|
||||
"""
|
||||
Collection's `count` differed from the number of elements iterated.
|
||||
"""
|
||||
)
|
||||
|
||||
let rhsIndex = rhs - bufferStart
|
||||
buffer[rhsIndex...].reverse()
|
||||
initializedCount = buffer.count
|
||||
|
||||
midPoint = rhsIndex
|
||||
} catch {
|
||||
let lhsCount = lhs - bufferStart
|
||||
let rhsCount = (bufferStart + buffer.count) - rhs
|
||||
bufferStart.deinitialize(count: lhsCount)
|
||||
rhs.deinitialize(count: rhsCount)
|
||||
throw error
|
||||
}
|
||||
})
|
||||
|
||||
let lhs = elements[..<midPoint]
|
||||
let rhs = elements[midPoint...]
|
||||
return (
|
||||
Array(lhs),
|
||||
Array(rhs)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -13,13 +13,12 @@
|
||||
// nextPermutation()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension MutableCollection
|
||||
where Self: BidirectionalCollection, Element: Comparable {
|
||||
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
|
||||
/// 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
|
||||
@@ -27,8 +26,7 @@ where Self: BidirectionalCollection, Element: Comparable {
|
||||
/// 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 {
|
||||
@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)
|
||||
@@ -43,7 +41,6 @@ where Self: BidirectionalCollection, Element: Comparable {
|
||||
// Find the last ascending pair (ie. ..., a, b, ... where a < b)
|
||||
if self[i] < self[ip1] {
|
||||
// Find the last element greater than self[i]
|
||||
// swift-format-ignore: NeverForceUnwrap
|
||||
// This is _always_ at most `ip1` due to if statement above
|
||||
let j = lastIndex(where: { self[i] < $0 })!
|
||||
|
||||
@@ -76,96 +73,69 @@ where Self: BidirectionalCollection, Element: Comparable {
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence of all the permutations of a collection's elements.
|
||||
public struct PermutationsSequence<Base: Collection> {
|
||||
public struct Permutations<Base: Collection> {
|
||||
/// The base collection to iterate over for permutations.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let baseCount: Int
|
||||
@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>
|
||||
@usableFromInline internal let kRange: Range<Int>
|
||||
|
||||
/// Initializes a `PermutationsSequence` for all permutations of `base` of
|
||||
/// size `k`.
|
||||
///
|
||||
/// 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.
|
||||
@inlinable
|
||||
internal init(_ base: Base, k: Int? = nil) {
|
||||
@inlinable internal init(_ base: Base, k: Int? = nil) {
|
||||
let kRange: ClosedRange<Int>?
|
||||
if let countToChoose = k {
|
||||
kRange = countToChoose...countToChoose
|
||||
} else {
|
||||
kRange = nil
|
||||
}
|
||||
if let countToChoose = k { kRange = countToChoose...countToChoose } else { kRange = nil }
|
||||
self.init(base, kRange: kRange)
|
||||
}
|
||||
|
||||
/// Initializes a `PermutationsSequence` for all combinations of `base` of
|
||||
/// sizes within a given range.
|
||||
///
|
||||
/// 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.
|
||||
@inlinable
|
||||
internal init<R: RangeExpression>(
|
||||
_ base: Base,
|
||||
kRange: R?
|
||||
) where R.Bound == Int {
|
||||
@inlinable internal init<R: RangeExpression>(_ base: Base, kRange: R?) where R.Bound == Int {
|
||||
self.base = base
|
||||
let baseCount = base.count
|
||||
self.baseCount = baseCount
|
||||
let upperBound = baseCount + 1
|
||||
self.kRange =
|
||||
kRange?.relative(to: 0 ..< .max)
|
||||
.clamped(to: 0..<upperBound) ?? baseCount..<upperBound
|
||||
kRange?.relative(to: 0 ..< .max).clamped(to: 0..<upperBound) ?? baseCount..<upperBound
|
||||
}
|
||||
|
||||
/// The total number of permutations.
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
kRange.map {
|
||||
stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *)
|
||||
}.reduce(0, +)
|
||||
@inlinable public var count: Int {
|
||||
return kRange.map { stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *) }.reduce(
|
||||
0, +)
|
||||
}
|
||||
}
|
||||
|
||||
extension PermutationsSequence: Sequence {
|
||||
/// The iterator for a `PermutationsSequence` instance.
|
||||
extension Permutations: Sequence {
|
||||
/// The iterator for a `Permutations` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let baseCount: Int
|
||||
@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>
|
||||
@usableFromInline internal var kRange: Range<Int>
|
||||
|
||||
/// Whether or not iteration is finished (`kRange` is empty).
|
||||
@inlinable
|
||||
internal var isFinished: Bool {
|
||||
kRange.isEmpty
|
||||
}
|
||||
/// Whether or not iteration is finished (`kRange` is empty)
|
||||
@inlinable internal var isFinished: Bool { return kRange.isEmpty }
|
||||
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
@usableFromInline internal var indexes: [Base.Index]
|
||||
|
||||
@inlinable
|
||||
internal init(_ permutations: PermutationsSequence) {
|
||||
@inlinable internal init(_ permutations: Permutations) {
|
||||
self.base = permutations.base
|
||||
self.baseCount = permutations.baseCount
|
||||
self.kRange = permutations.kRange
|
||||
@@ -183,15 +153,12 @@ extension PermutationsSequence: Sequence {
|
||||
/// is in ascending order.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
internal mutating func nextState() -> Bool {
|
||||
@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 })
|
||||
{
|
||||
if let i = indexes[countToChoose...].firstIndex(where: { indexes[edge] < $0 }) {
|
||||
indexes.swapAt(edge, i)
|
||||
} else {
|
||||
indexes.reverse(subrange: countToChoose..<indexes.endIndex)
|
||||
@@ -199,18 +166,11 @@ extension PermutationsSequence: Sequence {
|
||||
// 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]
|
||||
{
|
||||
lastAscent -= 1
|
||||
}
|
||||
if lastAscent < 0 {
|
||||
return false
|
||||
}
|
||||
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 })
|
||||
{
|
||||
if let i = indexes[lastAscent...].lastIndex(where: { indexes[lastAscent] < $0 }) {
|
||||
indexes.swapAt(lastAscent, i)
|
||||
}
|
||||
indexes.reverse(subrange: (lastAscent + 1)..<indexes.endIndex)
|
||||
@@ -219,8 +179,7 @@ extension PermutationsSequence: Sequence {
|
||||
return true
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> [Base.Element]? {
|
||||
@inlinable public mutating func next() -> [Base.Element]? {
|
||||
guard !isFinished else { return nil }
|
||||
|
||||
/// Advances `kRange` by incrementing its `lowerBound` until the range is
|
||||
@@ -232,9 +191,7 @@ extension PermutationsSequence: Sequence {
|
||||
|
||||
let countToChoose = self.kRange.lowerBound
|
||||
if countToChoose == 0 {
|
||||
defer {
|
||||
advanceKRange()
|
||||
}
|
||||
defer { advanceKRange() }
|
||||
return []
|
||||
}
|
||||
|
||||
@@ -244,9 +201,7 @@ extension PermutationsSequence: Sequence {
|
||||
// call to `nextPermutation` on `indexes`.
|
||||
defer {
|
||||
let hasMorePermutations = indexes.nextPermutation()
|
||||
if !hasMorePermutations {
|
||||
advanceKRange()
|
||||
}
|
||||
if !hasMorePermutations { advanceKRange() }
|
||||
}
|
||||
return indexes.map { base[$0] }
|
||||
} else {
|
||||
@@ -254,23 +209,17 @@ extension PermutationsSequence: Sequence {
|
||||
// advance the state.
|
||||
defer {
|
||||
let hasMorePermutations = nextState()
|
||||
if !hasMorePermutations {
|
||||
advanceKRange()
|
||||
}
|
||||
if !hasMorePermutations { advanceKRange() }
|
||||
}
|
||||
return indexes.prefix(countToChoose).map { base[$0] }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(self)
|
||||
}
|
||||
@inlinable public func makeIterator() -> Iterator { Iterator(self) }
|
||||
}
|
||||
|
||||
extension PermutationsSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension Permutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// permutations(ofCount:)
|
||||
@@ -329,18 +278,12 @@ extension Collection {
|
||||
/// 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.
|
||||
/// - Returns: A sequence of the permutations of this collection's elements,
|
||||
/// for all sizes in `kRange`, from smallest to largest.
|
||||
///
|
||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||
/// is the number of elements in the base collection, since
|
||||
/// `PermutationsSequence` accesses the `count` of the base collection.
|
||||
@inlinable
|
||||
public func permutations<R: RangeExpression>(
|
||||
ofCount kRange: R
|
||||
) -> PermutationsSequence<Self> where R.Bound == Int {
|
||||
PermutationsSequence(self, kRange: kRange)
|
||||
}
|
||||
/// 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.
|
||||
@@ -387,19 +330,13 @@ extension Collection {
|
||||
/// 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.
|
||||
/// - Returns: A sequence of the permutations of this collection's elements.
|
||||
///
|
||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||
/// is the number of elements in the base collection, since
|
||||
/// `PermutationsSequence` accesses the `count` of the base collection.
|
||||
@inlinable
|
||||
public func permutations(
|
||||
ofCount k: Int? = nil
|
||||
) -> PermutationsSequence<Self> {
|
||||
precondition(
|
||||
k ?? 0 >= 0,
|
||||
"Can't have permutations with a negative number of elements.")
|
||||
return PermutationsSequence(self, k: k)
|
||||
/// 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(k ?? 0 >= 0, "Can't have permutations with a negative number of elements.")
|
||||
return Permutations(self, k: k)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -410,82 +347,63 @@ extension Collection {
|
||||
/// A sequence of the unique permutations of the elements of a sequence or
|
||||
/// collection.
|
||||
///
|
||||
/// To create a `UniquePermutationsSequence` instance, call one of the
|
||||
/// To create a `UniquePermutations` instance, call one of the
|
||||
/// `uniquePermutations` methods on your collection.
|
||||
public struct UniquePermutationsSequence<Base: Collection> {
|
||||
public struct UniquePermutations<Base: Collection> {
|
||||
/// The base collection to iterate over for permutations.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
@usableFromInline internal var indexes: [Base.Index]
|
||||
|
||||
@usableFromInline
|
||||
internal let kRange: Range<Int>
|
||||
@usableFromInline internal let kRange: Range<Int>
|
||||
}
|
||||
|
||||
extension UniquePermutationsSequence where Base.Element: Hashable {
|
||||
@inlinable
|
||||
internal static func _indexes(_ base: Base) -> [Base.Index] {
|
||||
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)
|
||||
})
|
||||
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) }
|
||||
return firstIndexesAndCountsByElement.values.sorted(by: { $0.0 < $1.0 }).flatMap {
|
||||
index, count in repeatElement(index, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal init(_ elements: Base) {
|
||||
@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 {
|
||||
@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)
|
||||
self.kRange = range.relative(to: 0 ..< .max).clamped(to: 0..<upperBound)
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquePermutationsSequence: Sequence {
|
||||
/// The iterator for a `UniquePermutationsSequence` instance.
|
||||
extension UniquePermutations: Sequence {
|
||||
/// The iterator for a `UniquePermutations` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
@usableFromInline internal var indexes: [Base.Index]
|
||||
|
||||
@usableFromInline
|
||||
internal var lengths: Range<Int>
|
||||
@usableFromInline internal var lengths: Range<Int>
|
||||
|
||||
@usableFromInline
|
||||
internal var initial = true
|
||||
@usableFromInline internal var initial = true
|
||||
|
||||
@inlinable
|
||||
internal init(_ elements: Base, indexes: [Base.Index], lengths: Range<Int>)
|
||||
{
|
||||
@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]? {
|
||||
@inlinable public mutating func next() -> [Base.Element]? {
|
||||
// In the end case, `lengths` is an empty range.
|
||||
if lengths.isEmpty {
|
||||
return nil
|
||||
}
|
||||
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
|
||||
@@ -499,23 +417,19 @@ extension UniquePermutationsSequence: Sequence {
|
||||
if !indexes.nextPermutation(upperBound: lengths.lowerBound) {
|
||||
lengths.removeFirst()
|
||||
|
||||
if lengths.isEmpty {
|
||||
return nil
|
||||
}
|
||||
if lengths.isEmpty { return nil }
|
||||
}
|
||||
|
||||
return indexes[..<lengths.lowerBound].map { base[$0] }
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
@inlinable public func makeIterator() -> Iterator {
|
||||
Iterator(base, indexes: indexes, lengths: kRange)
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquePermutationsSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension UniquePermutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
extension Collection where Element: Hashable {
|
||||
/// Returns a sequence of the unique permutations of this sequence of the
|
||||
@@ -553,19 +467,15 @@ extension Collection where Element: Hashable {
|
||||
/// 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.
|
||||
/// - Returns: A sequence of the unique permutations of this collection's
|
||||
/// elements.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the number of elements in this
|
||||
/// collection.
|
||||
@inlinable
|
||||
public func uniquePermutations(ofCount k: Int? = nil)
|
||||
-> UniquePermutationsSequence<Self>
|
||||
{
|
||||
guard let k = k else {
|
||||
return UniquePermutationsSequence(self)
|
||||
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self> {
|
||||
if let k = k {
|
||||
return UniquePermutations(self, k..<(k + 1))
|
||||
} else {
|
||||
return UniquePermutations(self)
|
||||
}
|
||||
return UniquePermutationsSequence(self, k..<(k + 1))
|
||||
}
|
||||
|
||||
/// Returns a collection of the unique permutations of this sequence with
|
||||
@@ -594,15 +504,9 @@ extension Collection where Element: Hashable {
|
||||
/// 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.
|
||||
/// - Returns: A sequence of the unique permutations of this collection's
|
||||
/// elements, for all sizes in `kRange`, from smallest to largest.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the number of elements in this
|
||||
/// collection.
|
||||
@inlinable
|
||||
public func uniquePermutations<R: RangeExpression>(
|
||||
ofCount kRange: R
|
||||
) -> UniquePermutationsSequence<Self> where R.Bound == Int {
|
||||
UniquePermutationsSequence(self, kRange)
|
||||
}
|
||||
public func uniquePermutations<R: RangeExpression>(ofCount kRange: R) -> UniquePermutations<Self>
|
||||
where R.Bound == Int { UniquePermutations(self, kRange) }
|
||||
}
|
||||
+100
-194
@@ -10,49 +10,37 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence that represents the product of two sequences' elements.
|
||||
public struct Product2Sequence<Base1: Sequence, Base2: Collection> {
|
||||
public struct Product2<Base1: Sequence, Base2: Collection> {
|
||||
/// The outer sequence in the product.
|
||||
@usableFromInline
|
||||
internal let base1: Base1
|
||||
@usableFromInline internal let base1: Base1
|
||||
|
||||
/// The inner sequence in the product.
|
||||
@usableFromInline
|
||||
internal let base2: Base2
|
||||
@usableFromInline internal let base2: Base2
|
||||
|
||||
@inlinable
|
||||
internal init(_ base1: Base1, _ base2: Base2) {
|
||||
@inlinable internal init(_ base1: Base1, _ base2: Base2) {
|
||||
self.base1 = base1
|
||||
self.base2 = base2
|
||||
}
|
||||
}
|
||||
|
||||
extension Product2Sequence: Sequence {
|
||||
extension Product2: Sequence {
|
||||
public typealias Element = (Base1.Element, Base2.Element)
|
||||
|
||||
/// The iterator for a `Product2Sequence` sequence.
|
||||
/// The iterator for a `Product2` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var i1: Base1.Iterator
|
||||
@usableFromInline
|
||||
internal var i2: Base2.Iterator
|
||||
@usableFromInline
|
||||
internal var element1: Base1.Element?
|
||||
@usableFromInline
|
||||
internal let base2: Base2
|
||||
@usableFromInline internal var i1: Base1.Iterator
|
||||
@usableFromInline internal var i2: Base2.Iterator
|
||||
@usableFromInline internal var element1: Base1.Element?
|
||||
@usableFromInline internal let base2: Base2
|
||||
|
||||
@inlinable
|
||||
internal init(_ c: Product2Sequence) {
|
||||
@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
|
||||
)? {
|
||||
@inlinable public mutating func next() -> (Base1.Element, Base2.Element)? {
|
||||
// This is the initial state, where i1.next() has never
|
||||
// been called, or the final state, where i1.next() has
|
||||
// already returned nil.
|
||||
@@ -64,103 +52,70 @@ extension Product2Sequence: Sequence {
|
||||
|
||||
// Get the next element from the second sequence, if not
|
||||
// at end.
|
||||
if let element2 = i2.next() {
|
||||
// swift-format-ignore: NeverForceUnwrap
|
||||
// `element1` has a nil check above.
|
||||
return (element1!, element2)
|
||||
}
|
||||
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 else {
|
||||
return nil
|
||||
}
|
||||
guard let element1 = element1 else { return nil }
|
||||
|
||||
i2 = base2.makeIterator()
|
||||
guard let element2 = i2.next() else {
|
||||
return nil
|
||||
}
|
||||
return (element1, element2)
|
||||
if let element2 = i2.next() { return (element1, element2) } else { return nil }
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(self)
|
||||
}
|
||||
public func makeIterator() -> Iterator { return Iterator(self) }
|
||||
}
|
||||
|
||||
extension Product2Sequence: Collection where Base1: Collection {
|
||||
/// The index type for a `Product2Sequence` collection.
|
||||
extension Product2: Collection where Base1: Collection {
|
||||
/// The index type for a `Product2` collection.
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal var i1: Base1.Index
|
||||
@usableFromInline
|
||||
internal var i2: Base2.Index
|
||||
@usableFromInline internal var i1: Base1.Index
|
||||
@usableFromInline internal var i2: Base2.Index
|
||||
|
||||
@inlinable
|
||||
internal init(i1: Base1.Index, i2: Base2.Index) {
|
||||
@inlinable internal init(i1: Base1.Index, i2: Base2.Index) {
|
||||
self.i1 = i1
|
||||
self.i2 = i2
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
@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 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 startIndex: Index {
|
||||
Index(
|
||||
i1: base2.isEmpty ? base1.endIndex : base1.startIndex,
|
||||
i2: base2.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
@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
|
||||
) {
|
||||
@inlinable 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.
|
||||
@inlinable
|
||||
internal func normalizeIndex(_ i1: Base1.Index, _ i2: Base2.Index) -> Index {
|
||||
@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)
|
||||
? Index(i1: base1.index(after: i1), i2: base2.startIndex) : Index(i1: i1, i2: i2)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
@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) }
|
||||
guard start.i1 != end.i1
|
||||
else { return base2.distance(from: start.i2, to: end.i2) }
|
||||
@inlinable public func distance(from start: Index, to end: Index) -> Int {
|
||||
guard start.i1 <= end.i1 else { return -distance(from: end, to: start) }
|
||||
guard start.i1 != end.i1 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.
|
||||
@@ -181,9 +136,7 @@ extension Product2Sequence: Collection where Base1: Collection {
|
||||
let center = base2[start.i2..<end.i2].count
|
||||
let right = base2[end.i2...].count
|
||||
|
||||
return center + right
|
||||
+ fullBase2Cycles * (left + center + right)
|
||||
+ left + center
|
||||
return center + right + fullBase2Cycles * (left + center + right) + left + center
|
||||
} else {
|
||||
// start.i2
|
||||
// v
|
||||
@@ -203,58 +156,44 @@ extension Product2Sequence: Collection where Base1: Collection {
|
||||
guard fullBase2Cycles > 0 else { return right + left }
|
||||
|
||||
let center = base2[end.i2..<start.i2].count
|
||||
return right
|
||||
+ fullBase2Cycles * (left + center + right)
|
||||
+ left
|
||||
return right + fullBase2Cycles * (left + center + right) + left
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
@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)
|
||||
return distance > 0 ? offsetForward(i, by: distance) : offsetBackward(i, by: -distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@inlinable public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index?
|
||||
{
|
||||
if distance >= 0 {
|
||||
return limit >= i
|
||||
? offsetForward(i, by: distance, limitedBy: limit)
|
||||
: offsetForward(i, by: distance)
|
||||
? offsetForward(i, by: distance, limitedBy: limit) : offsetForward(i, by: distance)
|
||||
} else {
|
||||
return limit <= i
|
||||
? offsetBackward(i, by: -distance, limitedBy: limit)
|
||||
: offsetBackward(i, by: -distance)
|
||||
? offsetBackward(i, by: -distance, limitedBy: limit) : offsetBackward(i, by: -distance)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
@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") }
|
||||
@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 distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@inlinable internal func offsetForward(_ i: Index, by distance: Int, limitedBy limit: Index)
|
||||
-> Index?
|
||||
{
|
||||
assert(distance >= 0)
|
||||
assert(limit >= i)
|
||||
|
||||
@@ -265,14 +204,12 @@ extension Product2Sequence: Collection where Base1: Collection {
|
||||
// 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) }
|
||||
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)
|
||||
{
|
||||
if let i2 = base2.index(i.i2, offsetBy: distance, limitedBy: base2.endIndex) {
|
||||
// `distance` does not overflow `base2[i.i2...]`.
|
||||
//
|
||||
// i.i2 i2
|
||||
@@ -297,16 +234,12 @@ extension Product2Sequence: Collection where Base1: Collection {
|
||||
// ^
|
||||
// limit.i2
|
||||
|
||||
return
|
||||
base2
|
||||
.index(base2.startIndex, offsetBy: remaining, limitedBy: limit.i2)
|
||||
.map { i2 in Index(i1: nextI1, i2: 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)
|
||||
{
|
||||
if let i2 = base2.index(base2.startIndex, offsetBy: remaining, limitedBy: i.i2) {
|
||||
// `remaining` does not overflow `base2[..<i.i2]`.
|
||||
//
|
||||
// i.i2
|
||||
@@ -325,26 +258,22 @@ extension Product2Sequence: Collection where Base1: Collection {
|
||||
let base2Count = prefixCount + suffixCount
|
||||
let base1Distance = remaining / base2Count
|
||||
|
||||
guard
|
||||
let i1 = base1.index(nextI1, offsetBy: base1Distance, limitedBy: limit.i1)
|
||||
else { return nil }
|
||||
guard let i1 = base1.index(nextI1, offsetBy: base1Distance, limitedBy: limit.i1) 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) }
|
||||
return base2.index(base2.startIndex, offsetBy: base2Distance, limitedBy: base2Limit).map { i2 in
|
||||
Index(i1: i1, i2: i2)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ i: Index,
|
||||
by distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@inlinable internal func offsetBackward(_ i: Index, by distance: Int, limitedBy limit: Index)
|
||||
-> Index?
|
||||
{
|
||||
assert(distance >= 0)
|
||||
assert(limit <= i)
|
||||
|
||||
@@ -355,14 +284,12 @@ extension Product2Sequence: Collection where Base1: Collection {
|
||||
// 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) }
|
||||
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)
|
||||
{
|
||||
if let i2 = base2.index(i.i2, offsetBy: -distance, limitedBy: base2.startIndex) {
|
||||
// `distance` does not underflow `base2[..<i.i2]`.
|
||||
//
|
||||
// i2 i.i2
|
||||
@@ -387,16 +314,12 @@ extension Product2Sequence: Collection where Base1: Collection {
|
||||
// ^
|
||||
// i.i2
|
||||
|
||||
return
|
||||
base2
|
||||
.index(base2.endIndex, offsetBy: -remaining, limitedBy: limit.i2)
|
||||
.map { i2 in Index(i1: previousI1, i2: 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)
|
||||
{
|
||||
if let i2 = base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: i.i2) {
|
||||
// `remaining` does not underflow `base2[i.i2...]`.
|
||||
//
|
||||
// i2
|
||||
@@ -431,53 +354,41 @@ extension Product2Sequence: Collection where Base1: Collection {
|
||||
// ^
|
||||
// i.i2
|
||||
|
||||
guard
|
||||
let i1 = base1.index(
|
||||
previousI1,
|
||||
offsetBy: -(base1Distance - 1),
|
||||
limitedBy: limit.i1)
|
||||
else {
|
||||
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
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
let index = Index(i1: i1, i2: base2.startIndex)
|
||||
return index < limit ? nil : index
|
||||
}
|
||||
|
||||
guard
|
||||
let i1 =
|
||||
base1
|
||||
.index(previousI1, offsetBy: -base1Distance, limitedBy: limit.i1)
|
||||
else { return nil }
|
||||
guard let i1 = base1.index(previousI1, offsetBy: -base1Distance, limitedBy: limit.i1) 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) }
|
||||
return base2.index(base2.endIndex, offsetBy: -base2Distance, limitedBy: base2Limit).map { i2 in
|
||||
Index(i1: i1, i2: i2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Product2Sequence: BidirectionalCollection
|
||||
extension Product2: BidirectionalCollection
|
||||
where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(
|
||||
i != startIndex,
|
||||
"Can't move before startIndex")
|
||||
guard i.i2 == base2.startIndex else {
|
||||
@inlinable public func index(before i: Index) -> Index {
|
||||
precondition(i != startIndex, "Can't move before startIndex")
|
||||
if i.i2 == base2.startIndex {
|
||||
return Index(i1: base1.index(before: i.i1), i2: base2.index(before: base2.endIndex))
|
||||
} else {
|
||||
return Index(i1: i.i1, i2: base2.index(before: i.i2))
|
||||
}
|
||||
return Index(
|
||||
i1: base1.index(before: i.i1),
|
||||
i2: base2.index(before: base2.endIndex))
|
||||
}
|
||||
}
|
||||
|
||||
extension Product2Sequence: RandomAccessCollection
|
||||
extension Product2: RandomAccessCollection
|
||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||
|
||||
extension Product2Sequence.Index: Hashable
|
||||
where Base1.Index: Hashable, Base2.Index: Hashable {}
|
||||
extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// product(_:_:)
|
||||
@@ -490,6 +401,7 @@ where Base1.Index: Hashable, Base2.Index: Hashable {}
|
||||
/// element of the tuple is from the first collection and the second element is
|
||||
/// from the second collection.
|
||||
///
|
||||
///
|
||||
/// let numbers = 1...3
|
||||
/// let colors = ["cerise", "puce", "heliotrope"]
|
||||
/// for (number, color) in product(numbers, colors) {
|
||||
@@ -513,14 +425,8 @@ where Base1.Index: Hashable, Base2.Index: Hashable {}
|
||||
/// - Parameters:
|
||||
/// - s1: The first sequence to iterate over.
|
||||
/// - s2: The second sequence to iterate over.
|
||||
/// - Returns: A sequence of tuples, with every combination of the elements
|
||||
/// of `s1` and `s2`, in order.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func product<Base1: Sequence, Base2: Collection>(
|
||||
_ s1: Base1,
|
||||
_ s2: Base2
|
||||
) -> Product2Sequence<Base1, Base2> {
|
||||
Product2Sequence(s1, s2)
|
||||
}
|
||||
@inlinable public func product<Base1: Sequence, Base2: Collection>(_ s1: Base1, _ s2: Base2)
|
||||
-> Product2<Base1, Base2>
|
||||
{ return Product2(s1, s2) }
|
||||
@@ -10,34 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// For log(_:) and root(_:_:)
|
||||
#if ALGORITHMS_DARWIN_ONLY
|
||||
internal import Darwin
|
||||
|
||||
extension Double {
|
||||
@_transparent
|
||||
internal static func root(_ x: Double, _ n: Int) -> Double {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
if n == 3 { return cbrt(x) }
|
||||
return Double(signOf: x, magnitudeOf: pow(x.magnitude, 1 / Double(n)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal static func log(_ x: Double) -> Double {
|
||||
Darwin.log(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal static func log(onePlus x: Double) -> Double {
|
||||
Darwin.log1p(x)
|
||||
}
|
||||
}
|
||||
#elseif swift(>=5.11)
|
||||
internal import RealModule
|
||||
#elseif swift(>=5.10)
|
||||
import RealModule
|
||||
#else
|
||||
@_implementationOnly import RealModule
|
||||
#endif
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// randomStableSample(count:)
|
||||
@@ -54,10 +27,8 @@ extension Collection {
|
||||
/// collection's count, then this method returns the full collection.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func randomStableSample<G: RandomNumberGenerator>(
|
||||
count k: Int,
|
||||
using rng: inout G
|
||||
@inlinable public func randomStableSample<G: RandomNumberGenerator>(
|
||||
count k: Int, using rng: inout G
|
||||
) -> [Element] {
|
||||
guard k > 0 else { return [] }
|
||||
|
||||
@@ -89,13 +60,13 @@ extension Collection {
|
||||
/// This method is equivalent to calling `randomStableSample(k:using:)`,
|
||||
/// passing in the system's default random generator.
|
||||
///
|
||||
/// - Parameter k: The number of elements to randomly select.
|
||||
/// - Parameters:
|
||||
/// - k: The number of elements to randomly select.
|
||||
/// - Returns: An array of `k` random elements. If `k` is greater than this
|
||||
/// collection's count, then this method returns the full collection.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func randomStableSample(count k: Int) -> [Element] {
|
||||
@inlinable public func randomStableSample(count k: Int) -> [Element] {
|
||||
var g = SystemRandomNumberGenerator()
|
||||
return randomStableSample(count: k, using: &g)
|
||||
}
|
||||
@@ -109,19 +80,13 @@ extension Collection {
|
||||
// Algorithms of Time Complexity O(n(1 + log(N/n)))":
|
||||
// https://dl.acm.org/doi/pdf/10.1145/198429.198435
|
||||
|
||||
@usableFromInline
|
||||
internal func nextW<G: RandomNumberGenerator>(
|
||||
k: Int,
|
||||
using rng: inout G
|
||||
) -> Double {
|
||||
Double.root(.random(in: 0..<1, using: &rng), k)
|
||||
}
|
||||
@usableFromInline internal func nextW<G: RandomNumberGenerator>(k: Int, using rng: inout G)
|
||||
-> Double
|
||||
{ Double.root(.random(in: 0..<1, using: &rng), k) }
|
||||
|
||||
@usableFromInline
|
||||
internal func nextOffset<G: RandomNumberGenerator>(
|
||||
w: Double,
|
||||
using rng: inout G
|
||||
) -> Int {
|
||||
@usableFromInline internal func nextOffset<G: RandomNumberGenerator>(w: Double, using rng: inout G)
|
||||
-> Int
|
||||
{
|
||||
let offset = Double.log(.random(in: 0..<1, using: &rng)) / .log(onePlus: -w)
|
||||
return offset < Double(Int.max) ? Int(offset) : Int.max
|
||||
}
|
||||
@@ -139,11 +104,9 @@ extension Collection {
|
||||
/// - Complexity: O(*k*), where *k* is the number of elements to select, if
|
||||
/// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),
|
||||
/// where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func randomSample<G: RandomNumberGenerator>(
|
||||
count k: Int,
|
||||
using rng: inout G
|
||||
) -> [Element] {
|
||||
@inlinable public func randomSample<G: RandomNumberGenerator>(count k: Int, using rng: inout G)
|
||||
-> [Element]
|
||||
{
|
||||
guard k > 0 else { return [] }
|
||||
|
||||
var w = 1.0
|
||||
@@ -152,12 +115,12 @@ extension Collection {
|
||||
|
||||
// Fill the reservoir with the first `k` elements.
|
||||
var i = startIndex
|
||||
while i != endIndex, result.count < k {
|
||||
while i < endIndex, result.count < k {
|
||||
result.append(self[i])
|
||||
formIndex(after: &i)
|
||||
}
|
||||
|
||||
while i != endIndex {
|
||||
while i < endIndex {
|
||||
// Calculate the next value of w.
|
||||
w *= nextW(k: k, using: &rng)
|
||||
|
||||
@@ -165,7 +128,7 @@ extension Collection {
|
||||
let offset = nextOffset(w: w, using: &rng)
|
||||
i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex
|
||||
|
||||
if i != endIndex {
|
||||
if i < endIndex {
|
||||
// Swap selected element with a randomly chosen one in the reservoir.
|
||||
let j = Int.random(in: 0..<result.count, using: &rng)
|
||||
result[j] = self[i]
|
||||
@@ -183,7 +146,8 @@ extension Collection {
|
||||
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
|
||||
/// the system's default random generator.
|
||||
///
|
||||
/// - Parameter k: The number of elements to randomly select.
|
||||
/// - Parameters:
|
||||
/// - k: The number of elements to randomly select.
|
||||
/// - Returns: An array of `k` random elements. The returned elements may be
|
||||
/// in any order. If `k` is greater than this collection's count, then this
|
||||
/// method returns the full collection.
|
||||
@@ -191,8 +155,7 @@ extension Collection {
|
||||
/// - Complexity: O(*k*), where *k* is the number of elements to select, if
|
||||
/// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),
|
||||
/// where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func randomSample(count k: Int) -> [Element] {
|
||||
@inlinable public func randomSample(count k: Int) -> [Element] {
|
||||
var g = SystemRandomNumberGenerator()
|
||||
return randomSample(count: k, using: &g)
|
||||
}
|
||||
@@ -209,11 +172,9 @@ extension Sequence {
|
||||
/// method returns the full sequence.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func randomSample<G: RandomNumberGenerator>(
|
||||
count k: Int,
|
||||
using rng: inout G
|
||||
) -> [Element] {
|
||||
@inlinable public func randomSample<G: RandomNumberGenerator>(count k: Int, using rng: inout G)
|
||||
-> [Element]
|
||||
{
|
||||
guard k > 0 else { return [] }
|
||||
|
||||
var w = 1.0
|
||||
@@ -222,9 +183,7 @@ extension Sequence {
|
||||
|
||||
// Fill the reservoir with the first `k` elements.
|
||||
var iterator = makeIterator()
|
||||
while result.count < k, let el = iterator.next() {
|
||||
result.append(el)
|
||||
}
|
||||
while result.count < k, let el = iterator.next() { result.append(el) }
|
||||
|
||||
while true {
|
||||
// Calculate the next value of w.
|
||||
@@ -234,9 +193,7 @@ extension Sequence {
|
||||
var offset = nextOffset(w: w, using: &rng)
|
||||
|
||||
// Skip over `offset` elements to find the selected element.
|
||||
while offset > 0, iterator.next() != nil {
|
||||
offset -= 1
|
||||
}
|
||||
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.
|
||||
@@ -254,14 +211,14 @@ extension Sequence {
|
||||
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
|
||||
/// the system's default random generator.
|
||||
///
|
||||
/// - Parameter k: The number of elements to randomly select.
|
||||
/// - Parameters:
|
||||
/// - k: The number of elements to randomly select.
|
||||
/// - Returns: An array of `k` random elements. The returned elements may be
|
||||
/// in any order. If `k` is greater than this sequence's count, then this
|
||||
/// method returns the full sequence.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func randomSample(count k: Int) -> [Element] {
|
||||
@inlinable public func randomSample(count k: Int) -> [Element] {
|
||||
var g = SystemRandomNumberGenerator()
|
||||
return randomSample(count: k, using: &g)
|
||||
}
|
||||
|
||||
+190
-282
@@ -12,6 +12,7 @@
|
||||
// MARK: - Exclusive Reductions
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
|
||||
/// Returns a sequence containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
@@ -28,19 +29,15 @@ extension LazySequenceProtocol {
|
||||
/// - 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.
|
||||
/// the next element in the receiving sequence.
|
||||
/// - Returns: A sequence of the initial value followed by the reduced
|
||||
/// elements.
|
||||
/// elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func reductions<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: @escaping (Result, Element) -> Result
|
||||
) -> ExclusiveReductionsSequence<Elements, Result> {
|
||||
reductions(into: initial) { result, element in
|
||||
result = transform(result, element)
|
||||
}
|
||||
@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
|
||||
@@ -59,24 +56,20 @@ extension LazySequenceProtocol {
|
||||
/// - 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.
|
||||
/// 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
|
||||
) -> ExclusiveReductionsSequence<Elements, Result> {
|
||||
ExclusiveReductionsSequence(
|
||||
base: elements,
|
||||
initial: initial,
|
||||
transform: transform)
|
||||
@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.
|
||||
///
|
||||
@@ -107,16 +100,14 @@ extension Sequence {
|
||||
/// - 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.
|
||||
/// 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
|
||||
@inlinable public func reductions<Result>(
|
||||
_ initial: Result, _ transform: (Result, Element) throws -> Result
|
||||
) rethrows -> [Result] {
|
||||
try reductions(into: initial) { result, element in
|
||||
return try reductions(into: initial) { result, element in
|
||||
result = try transform(result, element)
|
||||
}
|
||||
}
|
||||
@@ -151,17 +142,15 @@ extension Sequence {
|
||||
/// - 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.
|
||||
/// 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
|
||||
@inlinable public func reductions<Result>(
|
||||
into initial: Result, _ transform: (inout Result, Element) throws -> Void
|
||||
) rethrows -> [Result] {
|
||||
|
||||
var output: [Result] = []
|
||||
var output = [Result]()
|
||||
output.reserveCapacity(underestimatedCount + 1)
|
||||
output.append(initial)
|
||||
|
||||
@@ -177,21 +166,15 @@ extension Sequence {
|
||||
|
||||
/// A sequence of applying a transform to the element of a sequence and the
|
||||
/// previously transformed result.
|
||||
public struct ExclusiveReductionsSequence<Base: Sequence, Result> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
public struct ExclusiveReductions<Result, Base: Sequence> {
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let initial: Result
|
||||
@usableFromInline internal let initial: Result
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (inout Result, Base.Element) -> Void
|
||||
@usableFromInline internal let transform: (inout Result, Base.Element) -> Void
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
initial: Result,
|
||||
transform: @escaping (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
|
||||
@@ -199,21 +182,16 @@ public struct ExclusiveReductionsSequence<Base: Sequence, Result> {
|
||||
}
|
||||
}
|
||||
|
||||
extension ExclusiveReductionsSequence: Sequence {
|
||||
extension ExclusiveReductions: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
@usableFromInline internal var iterator: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal var current: Result?
|
||||
@usableFromInline internal var current: Result?
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (inout Result, Base.Element) -> Void
|
||||
@usableFromInline internal let transform: (inout Result, Base.Element) -> Void
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
iterator: Base.Iterator,
|
||||
current: Result? = nil,
|
||||
@inlinable internal init(
|
||||
iterator: Base.Iterator, current: Result? = nil,
|
||||
transform: @escaping (inout Result, Base.Element) -> Void
|
||||
) {
|
||||
self.iterator = iterator
|
||||
@@ -221,11 +199,9 @@ extension ExclusiveReductionsSequence: Sequence {
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Result? {
|
||||
@inlinable public mutating func next() -> Result? {
|
||||
guard let result = current else { return nil }
|
||||
current = iterator.next().map { element in
|
||||
var result = result
|
||||
current = iterator.next().map { element in var result = result
|
||||
transform(&result, element)
|
||||
return result
|
||||
}
|
||||
@@ -233,125 +209,73 @@ extension ExclusiveReductionsSequence: Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(
|
||||
iterator: base.makeIterator(),
|
||||
current: initial,
|
||||
transform: transform)
|
||||
@inlinable public func makeIterator() -> Iterator {
|
||||
Iterator(iterator: base.makeIterator(), current: initial, transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension ExclusiveReductionsSequence: Collection where Base: Collection {
|
||||
extension ExclusiveReductions: Collection where Base: Collection {
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal enum Representation {
|
||||
case base(Base.Index, Result)
|
||||
case end
|
||||
}
|
||||
@usableFromInline internal let representation: ReductionsIndexRepresentation<Base.Index, Result>
|
||||
|
||||
@usableFromInline
|
||||
internal let representation: Representation
|
||||
|
||||
@inlinable
|
||||
internal init(_ representation: Representation) {
|
||||
@inlinable internal init(_ representation: ReductionsIndexRepresentation<Base.Index, Result>) {
|
||||
self.representation = representation
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs.representation, rhs.representation) {
|
||||
case (.base(let lhs, _), .base(let rhs, _)):
|
||||
return lhs == rhs
|
||||
case (.end, .end):
|
||||
return true
|
||||
case (.base, .end), (.end, .base):
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs.representation, rhs.representation) {
|
||||
case (.end, _):
|
||||
return false
|
||||
case (_, .end):
|
||||
return true
|
||||
case (.base(let lhs, _), .base(let rhs, _)):
|
||||
return lhs < rhs
|
||||
}
|
||||
@inlinable public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.representation < rhs.representation
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(.base(base.startIndex, initial))
|
||||
}
|
||||
@inlinable public var startIndex: Index { Index(.start) }
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(.end)
|
||||
}
|
||||
@inlinable public var endIndex: Index { Index(.end) }
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Result {
|
||||
@inlinable public subscript(position: Index) -> Result {
|
||||
switch position.representation {
|
||||
case .base(_, let result):
|
||||
return result
|
||||
case .end:
|
||||
fatalError("Cannot get element of end index.")
|
||||
case .start: return initial
|
||||
case .base(_, let result): return result
|
||||
case .end: fatalError("Cannot get element of end index.")
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after index: Index) -> Index {
|
||||
switch index.representation {
|
||||
case .base(base.endIndex, _):
|
||||
return Index(.end)
|
||||
case .base(let index, var result):
|
||||
transform(&result, base[index])
|
||||
return Index(.base(base.index(after: index), result))
|
||||
case .end:
|
||||
fatalError("Cannot get index after 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 {
|
||||
@inlinable public func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (start.representation, end.representation) {
|
||||
case (.base(let start, _), .base(let end, _)):
|
||||
return base.distance(from: start, to: end)
|
||||
case (.base(let index, _), .end):
|
||||
return base.distance(from: index, to: base.endIndex) + 1
|
||||
case (.end, .base(let index, _)):
|
||||
return base.distance(from: base.endIndex, to: index) - 1
|
||||
case (.end, .end):
|
||||
return 0
|
||||
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 ExclusiveReductionsSequence: LazySequenceProtocol {}
|
||||
extension ExclusiveReductions: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
extension ExclusiveReductionsSequence: LazyCollectionProtocol
|
||||
where Base: Collection {}
|
||||
|
||||
extension ExclusiveReductionsSequence.Index: Hashable
|
||||
where Base.Index: Hashable {
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
switch representation {
|
||||
case .base(let base, _):
|
||||
hasher.combine(base)
|
||||
case .end:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
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.
|
||||
///
|
||||
@@ -365,20 +289,19 @@ extension LazySequenceProtocol {
|
||||
/// // prints [1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter transform: A closure that combines the previously reduced
|
||||
/// result and the next element in the receiving sequence.
|
||||
/// - 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
|
||||
) -> InclusiveReductionsSequence<Elements> {
|
||||
InclusiveReductionsSequence(base: elements, transform: transform)
|
||||
}
|
||||
@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.
|
||||
///
|
||||
@@ -408,60 +331,52 @@ extension Sequence {
|
||||
/// If the sequence has one element, `transform` is never executed and
|
||||
/// an array containing only that first element is returned.
|
||||
///
|
||||
/// - Parameter transform: A closure that combines the previously reduced
|
||||
/// result and the next element in the receiving sequence.
|
||||
/// - 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] {
|
||||
@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 InclusiveReductionsSequence<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
public struct InclusiveReductions<Base: Sequence> {
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (Base.Element, Base.Element) -> Base.Element
|
||||
@usableFromInline internal let transform: (Base.Element, Base.Element) -> Base.Element
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
transform: @escaping (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 InclusiveReductionsSequence: Sequence {
|
||||
extension InclusiveReductions: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
@usableFromInline internal var iterator: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal var element: Base.Element?
|
||||
@usableFromInline internal var element: Base.Element?
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (Base.Element, Base.Element) -> Base.Element
|
||||
@usableFromInline internal let transform: (Base.Element, Base.Element) -> Base.Element
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
iterator: Base.Iterator,
|
||||
@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? {
|
||||
@inlinable public mutating func next() -> Base.Element? {
|
||||
guard let previous = element else {
|
||||
element = iterator.next()
|
||||
return element
|
||||
@@ -472,148 +387,141 @@ extension InclusiveReductionsSequence: Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
@inlinable public func makeIterator() -> Iterator {
|
||||
Iterator(iterator: base.makeIterator(), transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension InclusiveReductionsSequence: Collection where Base: Collection {
|
||||
extension InclusiveReductions: Collection where Base: Collection {
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let base: Base.Index
|
||||
@usableFromInline internal let representation:
|
||||
ReductionsIndexRepresentation<Base.Index, Base.Element>
|
||||
|
||||
@usableFromInline
|
||||
internal let result: Element?
|
||||
@inlinable internal init(
|
||||
_ representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
|
||||
) { self.representation = representation }
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base.Index, result: Element?) {
|
||||
self.base = base
|
||||
self.result = result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.base < rhs.base
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.base == rhs.base
|
||||
@inlinable public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.representation < rhs.representation
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(base: base.startIndex, result: base.first)
|
||||
@inlinable public var startIndex: Index {
|
||||
guard base.startIndex != base.endIndex else { return endIndex }
|
||||
return Index(.start)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(base: base.endIndex, result: nil)
|
||||
}
|
||||
@inlinable public var endIndex: Index { Index(.end) }
|
||||
|
||||
@inlinable
|
||||
public subscript(index: Index) -> Base.Element {
|
||||
guard let result = index.result else {
|
||||
fatalError("Can't subscript using endIndex")
|
||||
@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.")
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after index: Index) -> Index {
|
||||
guard let result = index.result else {
|
||||
fatalError("Can't advance past endIndex")
|
||||
@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.")
|
||||
}
|
||||
|
||||
let index = base.index(after: index.base)
|
||||
let nextResult =
|
||||
index == base.endIndex
|
||||
? nil
|
||||
: transform(result, base[index])
|
||||
|
||||
return Index(base: index, result: nextResult)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
base.distance(from: start.base, to: end.base)
|
||||
@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 InclusiveReductionsSequence: LazySequenceProtocol {}
|
||||
extension InclusiveReductions: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
extension InclusiveReductionsSequence: LazyCollectionProtocol
|
||||
where Base: Collection {}
|
||||
extension InclusiveReductions: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
||||
|
||||
extension InclusiveReductionsSequence.Index: Hashable
|
||||
where Base.Index: Hashable {
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(base)
|
||||
// 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
|
||||
) -> ExclusiveReductionsSequence<Elements, Result> {
|
||||
reductions(initial, transform)
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
|
||||
@inlinable
|
||||
@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
|
||||
) -> ExclusiveReductionsSequence<Elements, Result> {
|
||||
reductions(into: initial, transform)
|
||||
}
|
||||
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
|
||||
@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)
|
||||
}
|
||||
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(
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(_:) instead.") @inlinable public func scan(
|
||||
_ transform: @escaping (Element, Element) -> Element
|
||||
) -> InclusiveReductionsSequence<Elements> {
|
||||
reductions(transform)
|
||||
}
|
||||
) -> InclusiveReductions<Self> { reductions(transform) }
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
@available(*, deprecated, message: "Use reductions(_:) instead.")
|
||||
@inlinable
|
||||
public func scan(
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(_:) instead.") @inlinable public func scan(
|
||||
_ transform: (Element, Element) throws -> Element
|
||||
) rethrows -> [Element] {
|
||||
try reductions(transform)
|
||||
}
|
||||
) rethrows -> [Element] { try reductions(transform) }
|
||||
}
|
||||
@@ -15,10 +15,8 @@
|
||||
|
||||
extension MutableCollection where Self: BidirectionalCollection {
|
||||
/// Reverses the elements of the collection, moving from each end until
|
||||
/// `limit` is reached from either direction.
|
||||
///
|
||||
/// The returned indices are the start and end of the range of unreversed
|
||||
/// elements.
|
||||
/// `limit` is reached from either direction. The returned indices are the
|
||||
/// start and end of the range of unreversed elements.
|
||||
///
|
||||
/// Input:
|
||||
/// [a b c d e f g h i j k l m n o p]
|
||||
@@ -30,12 +28,9 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
/// lower upper
|
||||
///
|
||||
/// - Postcondition: For returned indices `(lower, upper)`:
|
||||
/// `lower == limit || upper == limit`.
|
||||
@inlinable
|
||||
@discardableResult
|
||||
internal mutating func _reverse(
|
||||
subrange: Range<Index>,
|
||||
until limit: Index
|
||||
/// `lower == limit || upper == limit`
|
||||
@inlinable @discardableResult internal mutating func _reverse(
|
||||
subrange: Range<Index>, until limit: Index
|
||||
) -> (Index, Index) {
|
||||
var lower = subrange.lowerBound
|
||||
var upper = subrange.upperBound
|
||||
@@ -59,8 +54,7 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
/// - Parameter subrange: The subrange of this collection to reverse.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of `subrange`.
|
||||
@inlinable
|
||||
public mutating func reverse(subrange: Range<Index>) {
|
||||
@inlinable public mutating func reverse(subrange: Range<Index>) {
|
||||
if subrange.isEmpty { return }
|
||||
var lower = subrange.lowerBound
|
||||
var upper = subrange.upperBound
|
||||
@@ -78,10 +72,8 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
|
||||
extension MutableCollection {
|
||||
/// Swaps the elements of the two given subranges, up to the upper bound of
|
||||
/// the smaller subrange.
|
||||
///
|
||||
/// The returned indices are the ends of the two ranges that were actually
|
||||
/// swapped.
|
||||
/// the smaller subrange. The returned indices are the ends of the two
|
||||
/// ranges that were actually swapped.
|
||||
///
|
||||
/// Input:
|
||||
/// [a b c d e f g h i j k l m n o p]
|
||||
@@ -99,10 +91,8 @@ extension MutableCollection {
|
||||
/// - distance(from: lhs.lowerBound, to: p) == distance(from:
|
||||
/// rhs.lowerBound, to: q)
|
||||
/// - p == lhs.upperBound || q == rhs.upperBound
|
||||
@inlinable
|
||||
internal mutating func _swapNonemptySubrangePrefixes(
|
||||
_ lhs: Range<Index>,
|
||||
_ rhs: Range<Index>
|
||||
@inlinable internal mutating func _swapNonemptySubrangePrefixes(
|
||||
_ lhs: Range<Index>, _ rhs: Range<Index>
|
||||
) -> (Index, Index) {
|
||||
assert(!lhs.isEmpty)
|
||||
assert(!rhs.isEmpty)
|
||||
@@ -117,8 +107,8 @@ extension MutableCollection {
|
||||
return (p, q)
|
||||
}
|
||||
|
||||
/// Rotates the elements within the given subrange so that the element at the
|
||||
/// specified index becomes the start of the subrange.
|
||||
/// Rotates the elements within the given subrange so that the element
|
||||
/// at the specified index becomes the start of the subrange.
|
||||
///
|
||||
/// Rotating a collection is equivalent to breaking the collection into two
|
||||
/// sections at the index `newStart`, and then swapping those two sections.
|
||||
@@ -138,11 +128,8 @@ extension MutableCollection {
|
||||
/// `subrange` pre-rotation.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of `subrange`.
|
||||
@inlinable
|
||||
@discardableResult
|
||||
public mutating func rotate(
|
||||
subrange: Range<Index>,
|
||||
toStartAt newStart: Index
|
||||
@inlinable @discardableResult public mutating func rotate(
|
||||
subrange: Range<Index>, toStartAt newStart: Index
|
||||
) -> Index {
|
||||
var m = newStart
|
||||
var s = subrange.lowerBound
|
||||
@@ -152,9 +139,10 @@ extension MutableCollection {
|
||||
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 (element j).
|
||||
// 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
|
||||
// (element j).
|
||||
//
|
||||
// [a b c d e f g|h i j] or [a b c|d e f g h i j]
|
||||
// ^ ^ ^ ^ ^ ^
|
||||
@@ -162,8 +150,8 @@ extension MutableCollection {
|
||||
//
|
||||
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).
|
||||
// Exchange the leading elements of each region (up to the
|
||||
// length of the shorter region).
|
||||
//
|
||||
// [a b c d e f g|h i j] or [a b c|d e f g h i j]
|
||||
// ^^^^^ ^^^^^ ^^^^^ ^^^^^
|
||||
@@ -174,20 +162,21 @@ extension MutableCollection {
|
||||
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 is in s1.
|
||||
// Left-hand case: we have moved element j into position. if
|
||||
// we haven't already, we can capture the return value which
|
||||
// is in s1.
|
||||
//
|
||||
// Note: the STL breaks the loop into two just to avoid this comparison
|
||||
// once the return value is known. I'm not sure it's a worthwhile
|
||||
// optimization, though.
|
||||
// Note: the STL breaks the loop into two just to avoid this
|
||||
// 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.
|
||||
// Now we have a smaller problem that is also a rotation, so we
|
||||
// can adjust our bounds and repeat.
|
||||
//
|
||||
// h i j[d e f g|a b c] or d e f[a b c|g h i j]
|
||||
// ^ ^ ^ ^ ^ ^
|
||||
@@ -199,8 +188,8 @@ extension MutableCollection {
|
||||
return ret
|
||||
}
|
||||
|
||||
/// Rotates the elements of this collection so that the element at the
|
||||
/// specified index becomes the start of the collection.
|
||||
/// Rotates the elements of this collection so that the element
|
||||
/// at the specified index becomes the start of the collection.
|
||||
///
|
||||
/// Rotating a collection is equivalent to breaking the collection into two
|
||||
/// sections at the index `newStart`, and then swapping those two sections.
|
||||
@@ -217,16 +206,14 @@ extension MutableCollection {
|
||||
/// - Returns: The new index of the element that was first pre-rotation.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
@discardableResult
|
||||
public mutating func rotate(toStartAt newStart: Index) -> Index {
|
||||
@inlinable @discardableResult public mutating func rotate(toStartAt newStart: Index) -> Index {
|
||||
rotate(subrange: startIndex..<endIndex, toStartAt: newStart)
|
||||
}
|
||||
}
|
||||
|
||||
extension MutableCollection where Self: BidirectionalCollection {
|
||||
/// Rotates the elements within the given subrange so that the element at the
|
||||
/// specified index becomes the start of the subrange.
|
||||
/// Rotates the elements within the given subrange so that the element
|
||||
/// at the specified index becomes the start of the subrange.
|
||||
///
|
||||
/// Rotating a collection is equivalent to breaking the collection into two
|
||||
/// sections at the index `newStart`, and then swapping those two sections.
|
||||
@@ -246,11 +233,8 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
/// `subrange` pre-rotation.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of `subrange`.
|
||||
@inlinable
|
||||
@discardableResult
|
||||
public mutating func rotate(
|
||||
subrange: Range<Index>,
|
||||
toStartAt newStart: Index
|
||||
@inlinable @discardableResult public mutating func rotate(
|
||||
subrange: Range<Index>, toStartAt newStart: Index
|
||||
) -> Index {
|
||||
reverse(subrange: subrange.lowerBound..<newStart)
|
||||
reverse(subrange: newStart..<subrange.upperBound)
|
||||
@@ -259,13 +243,13 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
return newStart == p ? q : p
|
||||
}
|
||||
|
||||
/// Rotates the elements of this collection so that the element at the
|
||||
/// specified index becomes the start of the collection.
|
||||
/// Rotates the elements of this collection so that the element
|
||||
/// at the specified index becomes the start of the collection.
|
||||
///
|
||||
/// Rotating a collection is equivalent to breaking the collection into two
|
||||
/// sections at the index `newStart`, and then swapping those two sections. In
|
||||
/// this example, the `numbers` array is rotated so that the element at index
|
||||
/// `3` (`40`) is first:
|
||||
/// sections at the index `newStart`, and then swapping those two sections.
|
||||
/// In this example, the `numbers` array is rotated so that the element at
|
||||
/// index `3` (`40`) is first:
|
||||
///
|
||||
/// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
/// let oldStart = numbers.rotate(toStartAt: 3)
|
||||
@@ -277,9 +261,19 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
/// - Returns: The new index of the element that was first pre-rotation.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
@discardableResult
|
||||
public mutating func rotate(toStartAt newStart: Index) -> Index {
|
||||
@inlinable @discardableResult public mutating func rotate(toStartAt newStart: Index) -> Index {
|
||||
rotate(subrange: startIndex..<endIndex, toStartAt: newStart)
|
||||
}
|
||||
}
|
||||
|
||||
// Deprecations
|
||||
|
||||
extension MutableCollection {
|
||||
@available(*, deprecated, renamed: "rotate(subrange:toStartAt:)") @discardableResult
|
||||
public mutating func rotate(subrange: Range<Index>, at newStart: Index) -> Index {
|
||||
rotate(subrange: subrange, toStartAt: newStart)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "rotate(toStartAt:)") @discardableResult
|
||||
public mutating func rotate(at newStart: Index) -> Index { rotate(toStartAt: newStart) }
|
||||
}
|
||||
+109
-198
@@ -14,175 +14,130 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Returns a sequence stepping through the elements every `step` starting at
|
||||
/// the first value.
|
||||
/// Returns a sequence stepping through the elements every `step` starting
|
||||
/// at the first value. Any remainders of the stride will be trimmed.
|
||||
///
|
||||
/// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]
|
||||
/// (0...10).striding(by: 3) // == [0, 3, 6, 9]
|
||||
///
|
||||
/// - Complexity: O(1). Access to successive values is O(k) where _k_ is the
|
||||
/// striding `step`.
|
||||
/// - Complexity: O(1). Access to successive values is O(k) where
|
||||
/// _k_ is the striding `step`.
|
||||
///
|
||||
/// - Parameter step: The amount to step with each iteration.
|
||||
/// - Returns: A sequence for stepping through the elements by the specified
|
||||
/// amount. Any remaining elements after the last multiple of the stride
|
||||
/// are omitted.
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> StridingSequence<Self> {
|
||||
StridingSequence(base: self, stride: step)
|
||||
/// - Returns: Returns a sequence for stepping through the
|
||||
/// elements by the specified amount.
|
||||
@inlinable public func striding(by step: Int) -> StrideSequence<Self> {
|
||||
StrideSequence(base: self, stride: step)
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
/// Returns a sequence stepping through the elements every `step` starting at
|
||||
/// the first value.
|
||||
/// Returns a sequence stepping through the elements every `step` starting
|
||||
/// at the first value. Any remainders of the stride will be trimmed.
|
||||
///
|
||||
/// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]
|
||||
/// (0...10).striding(by: 3) // == [0, 3, 6, 9]
|
||||
///
|
||||
/// - Complexity: O(1). Access to successive values is O(k) where _k_ is the
|
||||
/// striding `step`.
|
||||
/// - Complexity: O(1). Access to successive values is O(1) if the
|
||||
/// collection conforms to `RandomAccessCollection`; otherwise,
|
||||
/// O(_k_), where _k_ is the striding `step`.
|
||||
///
|
||||
/// - Parameter step: The amount to step with each iteration.
|
||||
/// - Returns: A sequence for stepping through the elements by the specified
|
||||
/// amount. Any remaining elements after the last multiple of the stride
|
||||
/// are omitted.
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> StridingCollection<Self> {
|
||||
StridingCollection(base: self, stride: step)
|
||||
/// - Returns: Returns a collection for stepping through the
|
||||
/// elements by the specified amount.
|
||||
@inlinable public func striding(by step: Int) -> StrideCollection<Self> {
|
||||
StrideCollection(base: self, stride: step)
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper that strides over a base sequence.
|
||||
public struct StridingSequence<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
public struct StrideSequence<Base: Sequence>: Sequence {
|
||||
|
||||
@usableFromInline
|
||||
internal let stride: Int
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, stride: Int) {
|
||||
precondition(stride > 0, "Stride must be greater than zero")
|
||||
self.base = base
|
||||
self.stride = stride
|
||||
}
|
||||
}
|
||||
@usableFromInline internal let stride: Int
|
||||
|
||||
extension StridingSequence {
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> Self {
|
||||
Self(base: base, stride: stride * step)
|
||||
}
|
||||
}
|
||||
|
||||
extension StridingSequence: Sequence {
|
||||
/// An iterator over a `StridingSequence` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal let stride: Int
|
||||
|
||||
@usableFromInline
|
||||
internal var striding: Bool = false
|
||||
|
||||
@inlinable
|
||||
internal init(iterator: Base.Iterator, stride: Int) {
|
||||
self.iterator = iterator
|
||||
self.stride = stride
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element? {
|
||||
guard striding else {
|
||||
striding = true
|
||||
return iterator.next()
|
||||
}
|
||||
for _ in 0..<stride - 1 {
|
||||
guard iterator.next() != nil else { break }
|
||||
}
|
||||
return iterator.next()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(iterator: base.makeIterator(), stride: stride)
|
||||
}
|
||||
}
|
||||
|
||||
extension StridingSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
/// A wrapper that strides over a base collection.
|
||||
public struct StridingCollection<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let stride: Int
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, stride: Int) {
|
||||
@inlinable internal init(base: Base, stride: Int) {
|
||||
precondition(stride > 0, "striding must be greater than zero")
|
||||
self.base = base
|
||||
self.stride = stride
|
||||
}
|
||||
}
|
||||
|
||||
extension StridingCollection {
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> Self {
|
||||
Self(base: base, stride: stride * step)
|
||||
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
|
||||
|
||||
@inlinable internal init(iterator: Base.Iterator, stride: Int) {
|
||||
self.iterator = iterator
|
||||
self.stride = stride
|
||||
}
|
||||
|
||||
@inlinable public mutating func next() -> Base.Element? {
|
||||
guard striding else {
|
||||
striding = true
|
||||
return iterator.next()
|
||||
}
|
||||
for _ in 0..<stride - 1 { guard iterator.next() != nil else { break } }
|
||||
return iterator.next()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable public func makeIterator() -> Iterator {
|
||||
Iterator(iterator: base.makeIterator(), stride: stride)
|
||||
}
|
||||
}
|
||||
|
||||
extension StridingCollection: Collection {
|
||||
/// A position in a `StridingCollection` instance.
|
||||
extension StrideSequence {
|
||||
@inlinable public func striding(by step: Int) -> Self { Self(base: base, stride: stride * step) }
|
||||
}
|
||||
|
||||
/// A wrapper that strides over a base collection.
|
||||
public struct StrideCollection<Base: Collection> {
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@usableFromInline internal let stride: Int
|
||||
|
||||
@inlinable internal init(base: Base, stride: Int) {
|
||||
precondition(stride > 0, "striding must be greater than zero")
|
||||
self.base = base
|
||||
self.stride = stride
|
||||
}
|
||||
}
|
||||
|
||||
extension StrideCollection {
|
||||
@inlinable public func striding(by step: Int) -> Self { Self(base: base, stride: stride * step) }
|
||||
}
|
||||
|
||||
extension StrideCollection: Collection {
|
||||
|
||||
/// A position in a `Stride` collection.
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let base: Base.Index
|
||||
@usableFromInline internal let base: Base.Index
|
||||
|
||||
@usableFromInline
|
||||
internal init(_ base: Base.Index) {
|
||||
self.base = base
|
||||
}
|
||||
@usableFromInline internal init(_ base: Base.Index) { self.base = base }
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.base < rhs.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 startIndex: Index { Index(base.startIndex) }
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(base.endIndex)
|
||||
}
|
||||
@inlinable public var endIndex: Index { Index(base.endIndex) }
|
||||
|
||||
@inlinable
|
||||
public subscript(i: Index) -> Base.Element {
|
||||
base[i.base]
|
||||
}
|
||||
@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")
|
||||
@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,
|
||||
offsetBy n: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@inlinable public func index(_ i: Index, offsetBy n: Int, limitedBy limit: Index) -> Index? {
|
||||
guard n != 0 else { return i }
|
||||
guard limit != i else { return nil }
|
||||
|
||||
@@ -191,99 +146,55 @@ extension StridingCollection: Collection {
|
||||
: offsetBackward(i, offsetBy: -n, limitedBy: limit)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ i: Index,
|
||||
offsetBy n: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@inlinable internal func offsetForward(_ i: Index, offsetBy n: Int, limitedBy limit: Index)
|
||||
-> Index?
|
||||
{
|
||||
if limit < i {
|
||||
guard
|
||||
let idx = base.index(
|
||||
i.base,
|
||||
offsetBy: n * stride,
|
||||
limitedBy: base.endIndex
|
||||
)
|
||||
else {
|
||||
if let idx = base.index(i.base, offsetBy: n * stride, limitedBy: base.endIndex) {
|
||||
return Index(idx)
|
||||
} else {
|
||||
assert(distance(from: i, to: endIndex) == n, "Advancing past end index")
|
||||
return endIndex
|
||||
}
|
||||
return Index(idx)
|
||||
} else if let idx = base.index(
|
||||
i.base,
|
||||
offsetBy: n * stride,
|
||||
limitedBy: limit.base
|
||||
) {
|
||||
} else if let idx = base.index(i.base, offsetBy: n * stride, limitedBy: limit.base) {
|
||||
return Index(idx)
|
||||
} else {
|
||||
return distance(from: i, to: limit) == n
|
||||
? endIndex
|
||||
: nil
|
||||
return distance(from: i, to: limit) == n ? endIndex : nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ i: Index,
|
||||
offsetBy n: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
// We typically use the ternary operator but this significantly increases
|
||||
// compile times when using Swift 5.3.2
|
||||
// https://github.com/apple/swift-algorithms/issues/146
|
||||
let distance: Int
|
||||
if i == endIndex {
|
||||
distance = -((base.count - 1) % stride + 1) + (n - 1) * -stride
|
||||
} else {
|
||||
distance = n * -stride
|
||||
}
|
||||
return base.index(
|
||||
i.base,
|
||||
offsetBy: distance,
|
||||
limitedBy: limit.base
|
||||
).map(Index.init)
|
||||
@inlinable internal func offsetBackward(_ i: Index, offsetBy n: Int, limitedBy limit: Index)
|
||||
-> Index?
|
||||
{
|
||||
let distance =
|
||||
i == endIndex ? -((base.count - 1) % stride + 1) + (n - 1) * -stride : n * -stride
|
||||
return base.index(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 var count: Int { base.isEmpty ? 0 : (base.count - 1) / stride + 1 }
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
@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")
|
||||
precondition(
|
||||
distance >= 0 || i.base != base.startIndex,
|
||||
"Incrementing past start index")
|
||||
@inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
precondition(distance <= 0 || i.base < base.endIndex, "Advancing past end index")
|
||||
precondition(distance >= 0 || i.base > base.startIndex, "Incrementing past start index")
|
||||
let limit = distance > 0 ? endIndex : startIndex
|
||||
guard let idx = index(i, offsetBy: distance, limitedBy: limit) else {
|
||||
preconditionFailure(
|
||||
"The distance \(distance) is not valid for this collection")
|
||||
}
|
||||
return idx
|
||||
let idx = index(i, offsetBy: distance, limitedBy: limit)
|
||||
precondition(idx != nil, "The distance \(distance) is not valid for this collection")
|
||||
return idx!
|
||||
}
|
||||
}
|
||||
|
||||
extension StridingCollection: BidirectionalCollection
|
||||
where Base: RandomAccessCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(i.base != base.startIndex, "Incrementing past start index")
|
||||
extension StrideCollection: BidirectionalCollection where Base: RandomAccessCollection {
|
||||
|
||||
@inlinable public func index(before i: Index) -> Index {
|
||||
precondition(i.base > base.startIndex, "Incrementing past start index")
|
||||
return index(i, offsetBy: -1)
|
||||
}
|
||||
}
|
||||
|
||||
extension StridingCollection: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
extension StridingCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension StridingCollection.Index: Hashable where Base.Index: Hashable {}
|
||||
extension StrideCollection: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
extension StrideCollection.Index: Hashable where Base.Index: Hashable {}
|
||||
@@ -14,22 +14,16 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension BidirectionalCollection {
|
||||
/// Returns a subsequence containing the suffix of this collection where
|
||||
/// all elements pass the given closure.
|
||||
/// Returns a subsequence containing the elements from the end until
|
||||
/// `predicate` returns `false` and skipping the remaining elements.
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the sequence as
|
||||
/// its argument and returns `true` if the element should be included or
|
||||
/// `false` if it should be excluded. Once the predicate returns `false` it
|
||||
/// will not be called again.
|
||||
/// - Returns: A subsequence that is a suffix of the collection, where
|
||||
/// `predicate` returns `true` for all the elements of the returned
|
||||
/// subsequence.
|
||||
/// - Parameter predicate: A closure that takes an element of the
|
||||
/// sequence as its argument and returns `true` if the element should
|
||||
/// be included or `false` if it should be excluded. Once the predicate
|
||||
/// returns `false` it will not be called again.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func suffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> SubSequence {
|
||||
@inlinable public func suffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence {
|
||||
try self[startOfSuffix(while: predicate)...]
|
||||
}
|
||||
}
|
||||
@@ -46,18 +40,12 @@ extension Collection {
|
||||
/// as its argument and returns `true` if the element is part of the prefix
|
||||
/// or `false` if it is not. Once the predicate returns `false` it will not
|
||||
/// be called again.
|
||||
/// - Returns: The index of the first element for which `predicate` does not
|
||||
/// succeed, or `endIndex` if all the collection's elements pass.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func endOfPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
@inlinable internal func endOfPrefix(while predicate: (Element) throws -> Bool) rethrows -> Index
|
||||
{
|
||||
var index = startIndex
|
||||
while try index != endIndex && predicate(self[index]) {
|
||||
formIndex(after: &index)
|
||||
}
|
||||
while try index != endIndex && predicate(self[index]) { formIndex(after: &index) }
|
||||
return index
|
||||
}
|
||||
}
|
||||
@@ -74,21 +62,16 @@ extension BidirectionalCollection {
|
||||
/// as its argument and returns `true` if the element is part of the suffix
|
||||
/// or `false` if it is not. Once the predicate returns `false` it will not
|
||||
/// be called again.
|
||||
/// - Returns: The index of the last element for which `predicate` does not
|
||||
/// succeed, or `startIndex` if all the collection's elements pass.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func startOfSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
@inlinable internal func startOfSuffix(while predicate: (Element) throws -> Bool) rethrows
|
||||
-> Index
|
||||
{
|
||||
var index = endIndex
|
||||
while index != startIndex {
|
||||
let after = index
|
||||
formIndex(before: &index)
|
||||
if try !predicate(self[index]) {
|
||||
return after
|
||||
}
|
||||
if try !predicate(self[index]) { return after }
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
+10
-218
@@ -9,234 +9,26 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// trimmingPrefix(while:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection {
|
||||
/// Returns a `SubSequence` formed by discarding all elements at the start of
|
||||
/// the collection that satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trimmingPrefix(while:)` to get a substring without the
|
||||
/// white space at the beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// print(myString.trimmingPrefix(while: \.isWhitespace))
|
||||
/// // Prints "hello, world "
|
||||
///
|
||||
/// - Parameter predicate: A closure that determines if the element should be
|
||||
/// omitted from the result.
|
||||
/// - Returns: A subsequence of this collection, starting at the first element
|
||||
/// for which `predicate` returns `false`.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public func trimmingPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> SubSequence {
|
||||
let start = try endOfPrefix(while: predicate)
|
||||
return self[start..<endIndex]
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// trimPrefix(while:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection where Self: RangeReplaceableCollection {
|
||||
/// Mutates the collection by discarding all elements at the start that
|
||||
/// satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trimPrefix(while:)` to remove the white space at the
|
||||
/// beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// myString.trimPrefix(while: \.isWhitespace)
|
||||
/// print(myString)
|
||||
/// // Prints "hello, world "
|
||||
///
|
||||
/// - Parameter predicate: A closure that determines if the element should be
|
||||
/// removed from the result.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
@_disfavoredOverload
|
||||
public mutating func trimPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
let startOfResult = try endOfPrefix(while: predicate)
|
||||
removeSubrange(startIndex..<startOfResult)
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection where Self == Self.SubSequence {
|
||||
/// Mutates the collection by discarding all elements at the start that
|
||||
/// satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trimPrefix(while:)` to remove the white space at the
|
||||
/// beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// myString.trimPrefix(while: \.isWhitespace)
|
||||
/// print(myString) // "hello, world "
|
||||
///
|
||||
/// - Parameters predicate: A closure that determines if the element should
|
||||
/// be removed from the string.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public mutating func trimPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
self = try trimmingPrefix(while: predicate)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// trimming(while:) / trimmingSuffix(while:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension BidirectionalCollection {
|
||||
/// Returns a `SubSequence` formed by discarding all elements at the start and
|
||||
/// end of the collection that satisfy the given predicate.
|
||||
/// end of the collection which satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trimming(while:)` to get a substring without the white
|
||||
/// space at the beginning and end of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// print(myString.trimming(while: \.isWhitespace))
|
||||
/// // Prints "hello, world"
|
||||
/// print(myString.trimming(while: \.isWhitespace)) // "hello, world"
|
||||
///
|
||||
/// - Parameter predicate: A closure that determines if the element should be
|
||||
/// omitted from the resulting slice.
|
||||
/// - Returns: A subsequence of this collection, starting at the first element
|
||||
/// for which `predicate` returns `false` and ending at the last element for
|
||||
/// which `predicate` returns `true`.
|
||||
/// - Parameters:
|
||||
/// - predicate: A closure which determines if the element should be
|
||||
/// omitted from the resulting slice.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public func trimming(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> SubSequence {
|
||||
try trimmingPrefix(while: predicate).trimmingSuffix(while: predicate)
|
||||
}
|
||||
|
||||
/// Returns a `SubSequence` formed by discarding all elements at the end of
|
||||
/// the collection that satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trimmingSuffix(while:)` to get a substring without the
|
||||
/// white space at the end of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// print(myString.trimmingSuffix(while: \.isWhitespace)) // " hello, world"
|
||||
///
|
||||
/// - Parameter predicate: A closure that determines if the element should be
|
||||
/// omitted from the resulting slice.
|
||||
/// - Returns: A subsequence of this collection, ending at the last element
|
||||
/// for which `predicate` returns `true`.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public func trimmingSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> SubSequence {
|
||||
let end = try startOfSuffix(while: predicate)
|
||||
return self[startIndex..<end]
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// trim(while:) / trimSuffix(while:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension BidirectionalCollection where Self: RangeReplaceableCollection {
|
||||
/// Mutates a `BidirectionalCollection` by discarding all elements at the
|
||||
/// start and at the end of it that satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trim(while:)` to remove the white space at the
|
||||
/// beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// myString.trim(while: \.isWhitespace)
|
||||
/// print(myString) // "hello, world"
|
||||
///
|
||||
/// - Parameter predicate: A closure that determines if the element should be
|
||||
/// removed from the string.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
@_disfavoredOverload
|
||||
public mutating func trim(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
try trimSuffix(while: predicate)
|
||||
try trimPrefix(while: predicate)
|
||||
}
|
||||
|
||||
/// Mutates a `BidirectionalCollection` by discarding all elements at the end
|
||||
/// of it that satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trimSuffix(while:)` to remove the white space at the
|
||||
/// beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// myString.trimSuffix(while: \.isWhitespace)
|
||||
/// print(myString) // " hello, world"
|
||||
///
|
||||
/// - Parameter predicate: A closure that determines if the element should be
|
||||
/// removed from the string.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
@_disfavoredOverload
|
||||
public mutating func trimSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
let endOfResult = try startOfSuffix(while: predicate)
|
||||
removeSubrange(endOfResult..<endIndex)
|
||||
}
|
||||
}
|
||||
|
||||
extension BidirectionalCollection where Self == Self.SubSequence {
|
||||
/// Mutates a `BidirectionalCollection` by discarding all elements at the
|
||||
/// start and at the end of it that satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trim(while:)` to remove the white space at the
|
||||
/// beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// myString.trim(while: \.isWhitespace)
|
||||
/// print(myString) // "hello, world"
|
||||
///
|
||||
/// - Parameter predicate: A closure that determines if the element should be
|
||||
/// removed from the string.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public mutating func trim(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
self = try trimming(while: predicate)
|
||||
}
|
||||
|
||||
/// Mutates a `BidirectionalCollection` by discarding all elements at the end
|
||||
/// of it that satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trimSuffix(while:)` to remove the white space at the
|
||||
/// beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// myString.trimSuffix(while: \.isWhitespace)
|
||||
/// print(myString) // " hello, world"
|
||||
///
|
||||
/// - Parameter predicate: A closure that determines if the element should be
|
||||
/// removed from the string.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public mutating func trimSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
self = try trimmingSuffix(while: predicate)
|
||||
@inlinable public func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
{
|
||||
let start = try endOfPrefix(while: predicate)
|
||||
let end = try self[start...].startOfSuffix(while: predicate)
|
||||
return self[start..<end]
|
||||
}
|
||||
}
|
||||
@@ -10,62 +10,49 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence wrapper that leaves out duplicate elements of a base sequence.
|
||||
public struct UniquedSequence<Base: Sequence, Subject: Hashable> {
|
||||
public struct Uniqued<Base: Sequence, Subject: Hashable> {
|
||||
/// The base collection.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
/// The projection function.
|
||||
@usableFromInline
|
||||
internal let projection: (Base.Element) -> Subject
|
||||
@usableFromInline internal let projection: (Base.Element) -> Subject
|
||||
|
||||
@usableFromInline
|
||||
internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {
|
||||
@usableFromInline internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {
|
||||
self.base = base
|
||||
self.projection = projection
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquedSequence: Sequence {
|
||||
/// The iterator for a `UniquedSequence` instance.
|
||||
extension Uniqued: Sequence {
|
||||
/// The iterator for a `Uniqued` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var base: Base.Iterator
|
||||
@usableFromInline internal var base: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal let projection: (Base.Element) -> Subject
|
||||
@usableFromInline internal let projection: (Base.Element) -> Subject
|
||||
|
||||
@usableFromInline
|
||||
internal var seen: Set<Subject> = []
|
||||
@usableFromInline internal var seen: Set<Subject> = []
|
||||
|
||||
@usableFromInline
|
||||
internal init(
|
||||
base: Base.Iterator,
|
||||
projection: @escaping (Base.Element) -> 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? {
|
||||
@inlinable public mutating func next() -> Base.Element? {
|
||||
while let element = base.next() {
|
||||
if seen.insert(projection(element)).inserted {
|
||||
return element
|
||||
}
|
||||
if seen.insert(projection(element)).inserted { return element }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
@inlinable public func makeIterator() -> Iterator {
|
||||
Iterator(base: base.makeIterator(), projection: projection)
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquedSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension Uniqued: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// uniqued()
|
||||
@@ -83,9 +70,8 @@ extension Sequence where Element: Hashable {
|
||||
/// - Returns: A sequence with only the unique elements of this sequence.
|
||||
/// .
|
||||
/// - Complexity: O(1).
|
||||
@inlinable
|
||||
public func uniqued() -> UniquedSequence<Self, Element> {
|
||||
UniquedSequence(base: self, projection: { $0 })
|
||||
@inlinable public func uniqued() -> Uniqued<Self, Element> {
|
||||
Uniqued(base: self, projection: { $0 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,24 +89,21 @@ extension Sequence {
|
||||
/// // Prints '["dog", "pig", "cat", "ox"]'
|
||||
///
|
||||
/// - Parameter projection: A closure that transforms an element into the
|
||||
/// value to use for uniqueness. If `projection` returns the same value for
|
||||
/// two different elements, the second element will be excluded from the
|
||||
/// resulting array.
|
||||
/// value to use for uniqueness. If `projection` returns the same value
|
||||
/// for two different elements, the second element will be excluded
|
||||
/// from the resulting array.
|
||||
///
|
||||
/// - Returns: An array with only the unique elements of this sequence, as
|
||||
/// determined by the result of `projection` for each element.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func uniqued<Subject: Hashable>(
|
||||
on projection: (Element) throws -> Subject
|
||||
) rethrows -> [Element] {
|
||||
@inlinable public func uniqued<Subject: Hashable>(on projection: (Element) throws -> Subject)
|
||||
rethrows -> [Element]
|
||||
{
|
||||
var seen: Set<Subject> = []
|
||||
var result: [Element] = []
|
||||
for element in self {
|
||||
if seen.insert(try projection(element)).inserted {
|
||||
result.append(element)
|
||||
}
|
||||
if seen.insert(try projection(element)).inserted { result.append(element) }
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -136,10 +119,7 @@ extension LazySequenceProtocol {
|
||||
/// of each unique element.
|
||||
///
|
||||
/// - Complexity: O(1).
|
||||
@inlinable
|
||||
public func uniqued<Subject: Hashable>(
|
||||
on projection: @escaping (Element) -> Subject
|
||||
) -> UniquedSequence<Self, Subject> {
|
||||
UniquedSequence(base: self, projection: projection)
|
||||
}
|
||||
@inlinable public func uniqued<Subject: Hashable>(on projection: @escaping (Element) -> Subject)
|
||||
-> Uniqued<Self, Subject>
|
||||
{ Uniqued(base: self, projection: projection) }
|
||||
}
|
||||
@@ -38,144 +38,111 @@ extension Collection {
|
||||
/// - Complexity: O(1) if the collection conforms to
|
||||
/// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`.
|
||||
/// Access to successive windows is O(1).
|
||||
@inlinable
|
||||
public func windows(ofCount count: Int) -> WindowsOfCountCollection<Self> {
|
||||
WindowsOfCountCollection(base: self, windowSize: count)
|
||||
@inlinable public func windows(ofCount count: Int) -> Windows<Self> {
|
||||
Windows(base: self, size: count)
|
||||
}
|
||||
}
|
||||
|
||||
/// A collection wrapper that presents a sliding window over the elements of
|
||||
/// a collection.
|
||||
public struct WindowsOfCountCollection<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
public struct Windows<Base: Collection> {
|
||||
@usableFromInline internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let windowSize: Int
|
||||
@usableFromInline internal let size: Int
|
||||
|
||||
@usableFromInline
|
||||
internal var endOfFirstWindow: Base.Index?
|
||||
@usableFromInline internal var firstUpperBound: Base.Index?
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, windowSize: Int) {
|
||||
precondition(windowSize > 0, "Windows size must be greater than zero")
|
||||
@inlinable internal init(base: Base, size: Int) {
|
||||
precondition(size > 0, "Windows size must be greater than zero")
|
||||
self.base = base
|
||||
self.windowSize = windowSize
|
||||
self.endOfFirstWindow =
|
||||
base
|
||||
.index(base.startIndex, offsetBy: windowSize, limitedBy: base.endIndex)
|
||||
self.size = size
|
||||
self.firstUpperBound = base.index(base.startIndex, offsetBy: size, limitedBy: base.endIndex)
|
||||
}
|
||||
}
|
||||
|
||||
extension WindowsOfCountCollection: Collection {
|
||||
/// A position in a `WindowsOfCountCollection` instance.
|
||||
extension Windows: Collection {
|
||||
/// A position in a `Windows` collection.
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal var lowerBound: Base.Index
|
||||
@usableFromInline internal var lowerBound: Base.Index
|
||||
|
||||
@usableFromInline
|
||||
internal var upperBound: Base.Index
|
||||
@usableFromInline internal var upperBound: Base.Index
|
||||
|
||||
@inlinable
|
||||
internal init(lowerBound: Base.Index, upperBound: Base.Index) {
|
||||
@inlinable internal init(lowerBound: Base.Index, upperBound: Base.Index) {
|
||||
self.lowerBound = lowerBound
|
||||
self.upperBound = upperBound
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||
@inlinable public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.lowerBound == rhs.lowerBound
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.lowerBound < rhs.lowerBound
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
guard let upperBound = endOfFirstWindow else {
|
||||
@inlinable public var startIndex: Index {
|
||||
if let upperBound = firstUpperBound {
|
||||
return Index(lowerBound: base.startIndex, upperBound: upperBound)
|
||||
} else {
|
||||
return endIndex
|
||||
}
|
||||
return Index(lowerBound: base.startIndex, upperBound: upperBound)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
@inlinable public var endIndex: Index {
|
||||
Index(lowerBound: base.endIndex, upperBound: base.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(index: Index) -> Base.SubSequence {
|
||||
precondition(
|
||||
index.lowerBound != index.upperBound,
|
||||
"Windows index is out of range")
|
||||
@inlinable public subscript(index: Index) -> Base.SubSequence {
|
||||
precondition(index.lowerBound != index.upperBound, "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")
|
||||
@inlinable public func index(after index: Index) -> Index {
|
||||
precondition(index < endIndex, "Advancing past end index")
|
||||
guard index.upperBound < base.endIndex else { return endIndex }
|
||||
|
||||
let lowerBound =
|
||||
windowSize == 1
|
||||
? index.upperBound
|
||||
: base.index(after: index.lowerBound)
|
||||
let upperBound = base.index(after: index.upperBound)
|
||||
return Index(lowerBound: lowerBound, upperBound: upperBound)
|
||||
return Index(
|
||||
lowerBound: base.index(after: index.lowerBound),
|
||||
upperBound: base.index(after: index.upperBound))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
@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)
|
||||
return distance > 0 ? offsetForward(i, by: distance) : offsetBackward(i, by: -distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@inlinable public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index?
|
||||
{
|
||||
guard distance != 0 else { return i }
|
||||
guard limit != i else { return nil }
|
||||
|
||||
if distance > 0 {
|
||||
return limit > i
|
||||
? offsetForward(i, by: distance, limitedBy: limit)
|
||||
: offsetForward(i, by: distance)
|
||||
? offsetForward(i, by: distance, limitedBy: limit) : offsetForward(i, by: distance)
|
||||
} else {
|
||||
return limit < i
|
||||
? offsetBackward(i, by: -distance, limitedBy: limit)
|
||||
: offsetBackward(i, by: -distance)
|
||||
? offsetBackward(i, by: -distance, limitedBy: limit) : offsetBackward(i, by: -distance)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
@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") }
|
||||
@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 distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@inlinable internal func offsetForward(_ i: Index, by distance: Int, limitedBy limit: Index)
|
||||
-> Index?
|
||||
{
|
||||
assert(distance > 0)
|
||||
assert(limit > i)
|
||||
|
||||
@@ -190,7 +157,7 @@ extension WindowsOfCountCollection: Collection {
|
||||
// |> > >|>| 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 >= windowSize {
|
||||
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.
|
||||
@@ -201,22 +168,16 @@ extension WindowsOfCountCollection: Collection {
|
||||
|
||||
guard limit.lowerBound >= i.upperBound,
|
||||
let lowerBound = base.index(
|
||||
i.upperBound,
|
||||
offsetBy: distance - windowSize,
|
||||
limitedBy: limit.lowerBound),
|
||||
i.upperBound, offsetBy: distance - size, limitedBy: limit.lowerBound),
|
||||
let indexBeforeUpperBound = base.index(
|
||||
lowerBound,
|
||||
offsetBy: windowSize - 1,
|
||||
limitedBy: limit.upperBound)
|
||||
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))
|
||||
return Index(lowerBound: lowerBound, upperBound: base.index(after: indexBeforeUpperBound))
|
||||
} else {
|
||||
// input: [x|x x x x x x|x x x x x]
|
||||
// |> > > >| |> > >|>|
|
||||
@@ -224,15 +185,12 @@ extension WindowsOfCountCollection: Collection {
|
||||
|
||||
guard
|
||||
let indexBeforeUpperBound = base.index(
|
||||
i.upperBound,
|
||||
offsetBy: distance - 1,
|
||||
limitedBy: limit.upperBound)
|
||||
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 }
|
||||
guard indexBeforeUpperBound != limit.upperBound || limit == endIndex else { return nil }
|
||||
|
||||
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
|
||||
// `endIndex`.
|
||||
@@ -244,12 +202,9 @@ extension WindowsOfCountCollection: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ i: Index,
|
||||
by distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@inlinable internal func offsetBackward(_ i: Index, by distance: Int, limitedBy limit: Index)
|
||||
-> Index?
|
||||
{
|
||||
assert(distance > 0)
|
||||
assert(limit < i)
|
||||
|
||||
@@ -265,15 +220,11 @@ extension WindowsOfCountCollection: Collection {
|
||||
|
||||
guard
|
||||
let upperBound = base.index(
|
||||
base.endIndex,
|
||||
offsetBy: -(distance - 1),
|
||||
limitedBy: limit.upperBound)
|
||||
base.endIndex, offsetBy: -(distance - 1), limitedBy: limit.upperBound)
|
||||
else { return nil }
|
||||
|
||||
return Index(
|
||||
lowerBound: base.index(upperBound, offsetBy: -windowSize),
|
||||
upperBound: upperBound)
|
||||
} else if distance >= windowSize {
|
||||
return Index(lowerBound: base.index(upperBound, offsetBy: -size), upperBound: upperBound)
|
||||
} else if distance >= size {
|
||||
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the upper
|
||||
// bound of the output is less than or equal to the lower bound of the
|
||||
// input.
|
||||
@@ -284,37 +235,28 @@ extension WindowsOfCountCollection: Collection {
|
||||
|
||||
guard limit.upperBound <= i.lowerBound,
|
||||
let upperBound = base.index(
|
||||
i.lowerBound,
|
||||
offsetBy: -(distance - windowSize),
|
||||
limitedBy: limit.upperBound)
|
||||
i.lowerBound, offsetBy: -(distance - size), limitedBy: limit.upperBound)
|
||||
else { return nil }
|
||||
|
||||
return Index(
|
||||
lowerBound: base.index(upperBound, offsetBy: -windowSize),
|
||||
upperBound: upperBound)
|
||||
return Index(lowerBound: base.index(upperBound, offsetBy: -size), upperBound: upperBound)
|
||||
} else {
|
||||
// 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)
|
||||
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))
|
||||
lowerBound: lowerBound, upperBound: base.index(i.lowerBound, offsetBy: -distance))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
@inlinable public func distance(from start: Index, to end: Index) -> Int {
|
||||
guard start <= end else { return -distance(from: end, to: start) }
|
||||
guard start != end else { return 0 }
|
||||
guard end != endIndex else {
|
||||
guard end < endIndex else {
|
||||
// We add 1 here because the index before `endIndex` also has
|
||||
// `base.endIndex` as its upper bound.
|
||||
return base[start.upperBound...].count + 1
|
||||
@@ -328,7 +270,7 @@ extension WindowsOfCountCollection: Collection {
|
||||
// |- - - -|> >|
|
||||
// end: [x x x x x x x|x x x x|x]
|
||||
|
||||
return windowSize + base[start.upperBound..<end.lowerBound].count
|
||||
return size + base[start.upperBound..<end.lowerBound].count
|
||||
} else {
|
||||
// start: [x|x x x x x x|x x x x x]
|
||||
// |> > > >|
|
||||
@@ -339,15 +281,12 @@ extension WindowsOfCountCollection: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
extension WindowsOfCountCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before index: Index) -> Index {
|
||||
precondition(index != startIndex, "Decrementing past start index")
|
||||
extension Windows: BidirectionalCollection where Base: BidirectionalCollection {
|
||||
@inlinable public func index(before index: Index) -> Index {
|
||||
precondition(index > startIndex, "Incrementing past start index")
|
||||
if index == endIndex {
|
||||
return Index(
|
||||
lowerBound: base.index(index.lowerBound, offsetBy: -windowSize),
|
||||
upperBound: index.upperBound)
|
||||
lowerBound: base.index(index.lowerBound, offsetBy: -size), upperBound: index.upperBound)
|
||||
} else {
|
||||
return Index(
|
||||
lowerBound: base.index(before: index.lowerBound),
|
||||
@@ -356,10 +295,7 @@ where Base: BidirectionalCollection {
|
||||
}
|
||||
}
|
||||
|
||||
extension WindowsOfCountCollection: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
extension WindowsOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension WindowsOfCountCollection.Index: Hashable where Base.Index: Hashable {}
|
||||
extension Windows: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension Windows: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
||||
extension Windows: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
extension Windows.Index: Hashable where Base.Index: Hashable {}
|
||||
@@ -0,0 +1,19 @@
|
||||
//===----------------------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Argument Parser open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#error("""
|
||||
|
||||
-----------------------------------------------------
|
||||
|
||||
Please test with `swift test --enable-test-discovery`
|
||||
|
||||
-----------------------------------------------------
|
||||
""")
|
||||
@@ -1,84 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class AdjacentPairsTests: XCTestCase {
|
||||
func testEmptySequence() {
|
||||
let pairs = (0...).prefix(0).adjacentPairs()
|
||||
expectEqualSequences(pairs, [], by: ==)
|
||||
}
|
||||
|
||||
func testOneElementSequence() {
|
||||
let pairs = (0...).prefix(1).adjacentPairs()
|
||||
expectEqualSequences(pairs, [], by: ==)
|
||||
}
|
||||
|
||||
func testTwoElementSequence() {
|
||||
let pairs = (0...).prefix(2).adjacentPairs()
|
||||
expectEqualSequences(pairs, [(0, 1)], by: ==)
|
||||
}
|
||||
|
||||
func testThreeElementSequence() {
|
||||
let pairs = (0...).prefix(3).adjacentPairs()
|
||||
expectEqualSequences(pairs, [(0, 1), (1, 2)], by: ==)
|
||||
}
|
||||
|
||||
func testManySequences() {
|
||||
for n in 4...100 {
|
||||
let pairs = (0...).prefix(n).adjacentPairs()
|
||||
expectEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==)
|
||||
}
|
||||
}
|
||||
|
||||
func testZeroElements() {
|
||||
let pairs = (0..<0).adjacentPairs()
|
||||
XCTAssertEqual(pairs.startIndex, pairs.endIndex)
|
||||
expectEqualSequences(pairs, [], by: ==)
|
||||
}
|
||||
|
||||
func testOneElement() {
|
||||
let pairs = (0..<1).adjacentPairs()
|
||||
XCTAssertEqual(pairs.startIndex, pairs.endIndex)
|
||||
expectEqualSequences(pairs, [], by: ==)
|
||||
}
|
||||
|
||||
func testTwoElements() {
|
||||
let pairs = (0..<2).adjacentPairs()
|
||||
expectEqualSequences(pairs, [(0, 1)], by: ==)
|
||||
}
|
||||
|
||||
func testThreeElements() {
|
||||
let pairs = (0..<3).adjacentPairs()
|
||||
expectEqualSequences(pairs, [(0, 1), (1, 2)], by: ==)
|
||||
}
|
||||
|
||||
func testManyElements() {
|
||||
for n in 4...100 {
|
||||
let pairs = (0..<n).adjacentPairs()
|
||||
expectEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==)
|
||||
}
|
||||
}
|
||||
|
||||
func testIndexTraversals() {
|
||||
let validator = IndexValidator<AdjacentPairsCollection<Range<Int>>>()
|
||||
validator.validate((0..<0).adjacentPairs(), expectedCount: 0)
|
||||
validator.validate((0..<1).adjacentPairs(), expectedCount: 0)
|
||||
validator.validate((0..<2).adjacentPairs(), expectedCount: 1)
|
||||
validator.validate((0..<5).adjacentPairs(), expectedCount: 4)
|
||||
}
|
||||
|
||||
func testLaziness() {
|
||||
requireLazySequence((0...).lazy.adjacentPairs())
|
||||
requireLazyCollection((0..<100).lazy.adjacentPairs())
|
||||
}
|
||||
}
|
||||
@@ -16,14 +16,14 @@ import XCTest
|
||||
final class ChainTests: XCTestCase {
|
||||
func testChainSequences() {
|
||||
let run = chain((1...).prefix(10), 20...)
|
||||
expectEqualSequences(run.prefix(20), Array(1...10) + (20..<30))
|
||||
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)
|
||||
expectEqualSequences(c, Array(s1) + Array(s2))
|
||||
XCTAssertEqualSequences(c, Array(s1) + Array(s2))
|
||||
}
|
||||
|
||||
func testChainBidirectionalCollection() {
|
||||
@@ -31,23 +31,18 @@ final class ChainTests: XCTestCase {
|
||||
let s2 = "klmnopqrstuv"
|
||||
let c = chain(s1, s2)
|
||||
|
||||
expectEqualSequences(c, "ABCDEFGHIJklmnopqrstuv")
|
||||
expectEqualSequences(c.reversed(), "ABCDEFGHIJklmnopqrstuv".reversed())
|
||||
expectEqualSequences(chain(s1.reversed(), s2), "JIHGFEDCBAklmnopqrstuv")
|
||||
XCTAssertEqualSequences(c, "ABCDEFGHIJklmnopqrstuv")
|
||||
XCTAssertEqualSequences(c.reversed(), "ABCDEFGHIJklmnopqrstuv".reversed())
|
||||
XCTAssertEqualSequences(chain(s1.reversed(), s2), "JIHGFEDCBAklmnopqrstuv")
|
||||
}
|
||||
|
||||
func testChainIndexTraversals() {
|
||||
let validator = IndexValidator<Chain2Sequence<String, String>>(
|
||||
indicesIncludingEnd: { chain in
|
||||
chain.base1.indices.map { .init(first: $0) }
|
||||
+ chain.base2.indices.map { .init(second: $0) }
|
||||
validateIndexTraversals(
|
||||
chain("abcd", "XYZ"), chain("abcd", ""), chain("", "XYZ"), chain("", ""),
|
||||
indices: { chain in
|
||||
chain.base1.indices.map { .init(first: $0) } + chain.base2.indices.map { .init(second: $0) }
|
||||
+ [.init(second: chain.base2.endIndex)]
|
||||
})
|
||||
|
||||
validator.validate(chain("abcd", "XYZ"), expectedCount: 4 + 3)
|
||||
validator.validate(chain("abcd", ""), expectedCount: 4 + 0)
|
||||
validator.validate(chain("", "XYZ"), expectedCount: 0 + 3)
|
||||
validator.validate(chain("", ""), expectedCount: 0 + 0)
|
||||
}
|
||||
|
||||
func testChainIndexOffsetAcrossBoundary() {
|
||||
|
||||
@@ -14,31 +14,22 @@ 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: [ArraySlice<String>] = [
|
||||
fruits[0..<3],
|
||||
fruits[3..<8],
|
||||
fruits[8..<12],
|
||||
fruits[12..<16],
|
||||
fruits[16..<18],
|
||||
fruits[18..<19],
|
||||
fruits[19..<22],
|
||||
fruits[0..<3], fruits[3..<8], fruits[8..<12], fruits[12..<16], fruits[16..<18],
|
||||
fruits[18..<19], fruits[19..<22],
|
||||
]
|
||||
expectEqualSequences(expectedChunks, fruitChunks, by: ==)
|
||||
XCTAssertEqualSequences(expectedChunks, fruitChunks, by: ==)
|
||||
|
||||
XCTAssertEqual(fruits[19..<22], fruitChunks.last)
|
||||
|
||||
XCTAssertEqual(
|
||||
"Currant", fruitChunks.first(where: { $0.count == 4 })?.first)
|
||||
XCTAssertEqual("Currant", fruitChunks.first(where: { $0.count == 4 })?.first)
|
||||
XCTAssertEqual("Date", fruitChunks.last(where: { $0.count == 4 })?.first)
|
||||
XCTAssertNil(fruitChunks.first(where: { $0.count == 0 }))
|
||||
XCTAssertNil(fruitChunks.last(where: { $0.count == 0 }))
|
||||
@@ -47,13 +38,8 @@ final class ChunkedTests: XCTestCase {
|
||||
func testSimple() {
|
||||
// Example
|
||||
let names = ["David", "Kyle", "Karoy", "Nate"]
|
||||
let chunks = names.chunked(on: { $0.first! })
|
||||
let expected: [(Character, ArraySlice<String>)] = [
|
||||
("D", ["David"]),
|
||||
("K", ["Kyle", "Karoy"]),
|
||||
("N", ["Nate"]),
|
||||
]
|
||||
expectEqualSequences(expected, chunks, by: ==)
|
||||
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)
|
||||
@@ -64,11 +50,10 @@ final class ChunkedTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testChunkedOn() {
|
||||
validateFruitChunks(fruits.chunked(on: { $0.first }).map { $1 })
|
||||
validateFruitChunks(fruits.chunked(on: { $0.first }))
|
||||
|
||||
let lazyChunks = fruits.lazy.chunked(on: { $0.first })
|
||||
validateFruitChunks(lazyChunks.map { $1 })
|
||||
IndexValidator().validate(lazyChunks)
|
||||
validateFruitChunks(lazyChunks)
|
||||
}
|
||||
|
||||
func testChunkedBy() {
|
||||
@@ -76,78 +61,49 @@ final class ChunkedTests: XCTestCase {
|
||||
|
||||
let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first })
|
||||
validateFruitChunks(lazyChunks)
|
||||
IndexValidator().validate(lazyChunks)
|
||||
}
|
||||
|
||||
func testChunkedByComparesConsecutiveElements() {
|
||||
expectEqualSequences(
|
||||
[1, 2, 3, 4, 6, 7, 8, 9].chunked(by: { $1 - $0 == 1 }),
|
||||
[[1, 2, 3, 4], [6, 7, 8, 9]])
|
||||
|
||||
expectEqualSequences(
|
||||
[1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }),
|
||||
[[1, 2, 3, 4], [6, 7, 8, 9]])
|
||||
|
||||
expectEqualSequences(
|
||||
[1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }).reversed(),
|
||||
[[6, 7, 8, 9], [1, 2, 3, 4]])
|
||||
|
||||
IndexValidator().validate([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 }))
|
||||
}
|
||||
|
||||
func testChunkedLazy() {
|
||||
requireLazySequence(fruits.lazy.chunked(by: { $0.first == $1.first }))
|
||||
requireLazySequence(fruits.lazy.chunked(on: { $0.first }))
|
||||
XCTAssertLazySequence(fruits.lazy.chunked(by: { $0.first == $1.first }))
|
||||
XCTAssertLazySequence(fruits.lazy.chunked(on: { $0.first }))
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Tests for `chunks(ofCount:)`
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
func testChunksOfCount() {
|
||||
expectEqualSequences([Int]().chunks(ofCount: 1), [])
|
||||
expectEqualSequences([Int]().chunks(ofCount: 5), [])
|
||||
XCTAssertEqualSequences([Int]().chunks(ofCount: 1), [])
|
||||
XCTAssertEqualSequences([Int]().chunks(ofCount: 5), [])
|
||||
|
||||
let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
expectEqualSequences(
|
||||
collection1.chunks(ofCount: 1),
|
||||
[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
|
||||
expectEqualSequences(
|
||||
collection1.chunks(ofCount: 3),
|
||||
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]])
|
||||
expectEqualSequences(
|
||||
collection1.chunks(ofCount: 5),
|
||||
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
|
||||
expectEqualSequences(
|
||||
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]
|
||||
expectEqualSequences(
|
||||
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]
|
||||
|
||||
expectEqualSequences(
|
||||
XCTAssertEqualSequences(
|
||||
collection1.chunks(ofCount: 1).reversed(),
|
||||
[[10], [9], [8], [7], [6], [5], [4], [3], [2], [1]])
|
||||
expectEqualSequences(
|
||||
collection1.chunks(ofCount: 3).reversed(),
|
||||
[[10], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
|
||||
expectEqualSequences(
|
||||
collection1.chunks(ofCount: 5).reversed(),
|
||||
[[6, 7, 8, 9, 10], [1, 2, 3, 4, 5]])
|
||||
expectEqualSequences(
|
||||
collection1.chunks(ofCount: 11).reversed(),
|
||||
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
|
||||
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]
|
||||
expectEqualSequences(
|
||||
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() {
|
||||
@@ -167,53 +123,15 @@ final class ChunkedTests: XCTestCase {
|
||||
func testEmptyChunksOfCountTraversal() {
|
||||
let emptyChunks = [Int]().chunks(ofCount: 1)
|
||||
|
||||
IndexValidator().validate(emptyChunks, expectedCount: 0)
|
||||
validateIndexTraversals(emptyChunks)
|
||||
}
|
||||
|
||||
func testChunksOfCountTraversal() {
|
||||
let validator = IndexValidator<ChunksOfCountCollection<ClosedRange<Int>>>()
|
||||
for i in 1..<10 {
|
||||
let collection = (1...50).map { $0 }
|
||||
let chunks = collection.chunks(ofCount: i)
|
||||
|
||||
for i in 1...10 {
|
||||
let range = 1...50
|
||||
let chunks = range.chunks(ofCount: i)
|
||||
validator.validate(
|
||||
chunks,
|
||||
expectedCount: range.count / i + (range.count % i).signum())
|
||||
}
|
||||
}
|
||||
|
||||
func testEvenChunks() {
|
||||
expectEqualSequences(
|
||||
(0..<10).evenlyChunked(in: 4),
|
||||
[0..<3, 3..<6, 6..<8, 8..<10])
|
||||
|
||||
expectEqualSequences(
|
||||
(0..<3).evenlyChunked(in: 5),
|
||||
[0..<1, 1..<2, 2..<3, 3..<3, 3..<3])
|
||||
|
||||
expectEqualSequences(
|
||||
"".evenlyChunked(in: 0),
|
||||
[])
|
||||
|
||||
expectEqualSequences(
|
||||
"".evenlyChunked(in: 1),
|
||||
[""])
|
||||
}
|
||||
|
||||
func testEvenChunksIndexTraversals() {
|
||||
let validator = IndexValidator<EvenlyChunkedCollection<Range<Int>>>()
|
||||
|
||||
for chunks in [
|
||||
(0..<10).evenlyChunked(in: 1),
|
||||
(0..<10).evenlyChunked(in: 2),
|
||||
(0..<10).evenlyChunked(in: 3),
|
||||
(0..<10).evenlyChunked(in: 10),
|
||||
(0..<10).evenlyChunked(in: 20),
|
||||
(0..<0).evenlyChunked(in: 0),
|
||||
(0..<0).evenlyChunked(in: 1),
|
||||
(0..<0).evenlyChunked(in: 10),
|
||||
] {
|
||||
validator.validate(chunks)
|
||||
validateIndexTraversals(chunks)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,62 +16,56 @@ final class CombinationsTests: XCTestCase {
|
||||
func testCount() {
|
||||
let c = "ABCD"
|
||||
|
||||
/// XCTAsserts that `x`'s `count` and `underestimatedCount` are both `l` at
|
||||
/// the given `file` and `line`.
|
||||
func check(
|
||||
_ x: CombinationsSequence<String>, countsAre l: Int,
|
||||
file: StaticString, line: UInt
|
||||
) {
|
||||
XCTAssertEqual(x.count, l, "unexpected count", file: file, line: line)
|
||||
XCTAssertEqual(
|
||||
x.underestimatedCount, l, "unexpected underestimatedCount",
|
||||
file: file, line: line)
|
||||
}
|
||||
let c0 = c.combinations(ofCount: 0).count
|
||||
XCTAssertEqual(c0, 1)
|
||||
|
||||
/// XCTAsserts that the `count` and `underestimatedCount` of
|
||||
/// `c.combinations(ofCount: l)` are both `n` at the given `file` and
|
||||
/// `line`.
|
||||
func check(
|
||||
cHas n: Int,
|
||||
combinationsOfLength l: Int,
|
||||
file: StaticString = #filePath, line: UInt = #line
|
||||
) {
|
||||
check(c.combinations(ofCount: l), countsAre: n, file: file, line: line)
|
||||
}
|
||||
let c1 = c.combinations(ofCount: 1).count
|
||||
XCTAssertEqual(c1, 4)
|
||||
|
||||
/// XCTAsserts that the `count` and `underestimatedCount` of
|
||||
/// `c.combinations(ofCount: l)` are both `n` at the given `file` and
|
||||
/// `line`.
|
||||
func check<R: RangeExpression>(
|
||||
cHas n: Int,
|
||||
combinationsOfLengths l: R,
|
||||
file: StaticString = #filePath, line: UInt = #line
|
||||
) where R.Bound == Int {
|
||||
check(c.combinations(ofCount: l), countsAre: n, file: file, line: line)
|
||||
}
|
||||
let c2 = c.combinations(ofCount: 2).count
|
||||
XCTAssertEqual(c2, 6)
|
||||
|
||||
check(cHas: 1, combinationsOfLength: 0)
|
||||
check(cHas: 4, combinationsOfLength: 1)
|
||||
check(cHas: 6, combinationsOfLength: 2)
|
||||
check(cHas: 1, combinationsOfLength: 4)
|
||||
let c3 = c.combinations(ofCount: 3).count
|
||||
XCTAssertEqual(c3, 4)
|
||||
|
||||
check(cHas: 1, combinationsOfLengths: 0...0)
|
||||
check(cHas: 4, combinationsOfLengths: 1...1)
|
||||
check(cHas: 10, combinationsOfLengths: 1...2)
|
||||
check(cHas: 14, combinationsOfLengths: 1...3)
|
||||
check(cHas: 11, combinationsOfLengths: 2...4)
|
||||
let c4 = c.combinations(ofCount: 4).count
|
||||
XCTAssertEqual(c4, 1)
|
||||
|
||||
let c5 = c.combinations(ofCount: 0...0).count
|
||||
XCTAssertEqual(c5, 1)
|
||||
|
||||
let c6 = c.combinations(ofCount: 1...1).count
|
||||
XCTAssertEqual(c6, 4)
|
||||
|
||||
let c7 = c.combinations(ofCount: 1...2).count
|
||||
XCTAssertEqual(c7, 10)
|
||||
|
||||
let c8 = c.combinations(ofCount: 1...3).count
|
||||
XCTAssertEqual(c8, 14)
|
||||
|
||||
let c9 = c.combinations(ofCount: 2...4).count
|
||||
XCTAssertEqual(c9, 11)
|
||||
|
||||
// `k` greater than element count results in same number of combinations
|
||||
check(cHas: 5, combinationsOfLengths: 3...10)
|
||||
let c10 = c.combinations(ofCount: 3...10).count
|
||||
XCTAssertEqual(c10, 5)
|
||||
|
||||
// `k` greater than element count results in same number of combinations
|
||||
check(cHas: 1, combinationsOfLengths: 4...10)
|
||||
let c11 = c.combinations(ofCount: 4...10).count
|
||||
XCTAssertEqual(c11, 1)
|
||||
|
||||
// `k` entirely greater than element count results in no combinations
|
||||
check(cHas: 0, combinationsOfLengths: 5...10)
|
||||
let c12 = c.combinations(ofCount: 5...10).count
|
||||
XCTAssertEqual(c12, 0)
|
||||
|
||||
check(cHas: 16, combinationsOfLengths: 0...)
|
||||
check(cHas: 15, combinationsOfLengths: ...3)
|
||||
let c13 = c.combinations(ofCount: 0...).count
|
||||
XCTAssertEqual(c13, 16)
|
||||
|
||||
let c14 = c.combinations(ofCount: ...3).count
|
||||
XCTAssertEqual(c14, 15)
|
||||
|
||||
let c15 = c.combinations(ofCount: 0...).count
|
||||
XCTAssertEqual(c15, 16)
|
||||
}
|
||||
|
||||
func testCombinations() {
|
||||
@@ -97,58 +91,54 @@ final class CombinationsTests: XCTestCase {
|
||||
let c6 = c.combinations(ofCount: 0...4)
|
||||
XCTAssertEqual(
|
||||
[
|
||||
"", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC",
|
||||
"ABD", "ACD", "BCD", "ABCD",
|
||||
"", "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",
|
||||
"", "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",
|
||||
"", "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) })
|
||||
["", "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) })
|
||||
["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
|
||||
expectEqualSequences([[]], "".combinations(ofCount: 0))
|
||||
expectEqualSequences([[]], "".combinations(ofCount: 0...0))
|
||||
expectEqualSequences([[]], "ABCD".combinations(ofCount: 0))
|
||||
expectEqualSequences([[]], "ABCD".combinations(ofCount: 0...0))
|
||||
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
|
||||
expectEqualSequences([], "".combinations(ofCount: 5))
|
||||
expectEqualSequences([], "".combinations(ofCount: 5...10))
|
||||
expectEqualSequences([], "ABCD".combinations(ofCount: 5))
|
||||
expectEqualSequences([], "ABCD".combinations(ofCount: 5...10))
|
||||
XCTAssertEqualSequences([], "".combinations(ofCount: 5))
|
||||
XCTAssertEqualSequences([], "".combinations(ofCount: 5...10))
|
||||
XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5))
|
||||
XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5...10))
|
||||
}
|
||||
|
||||
func testCombinationsLazy() {
|
||||
requireLazySequence("ABC".lazy.combinations(ofCount: 1))
|
||||
requireLazySequence("ABC".lazy.combinations(ofCount: 1...3))
|
||||
requireLazySequence("ABC".lazy.combinations(ofCount: 1...))
|
||||
requireLazySequence("ABC".lazy.combinations(ofCount: ...3))
|
||||
requireLazySequence("ABC".lazy.combinations(ofCount: 0...))
|
||||
XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1))
|
||||
XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1...3))
|
||||
XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1...))
|
||||
XCTAssertLazySequence("ABC".lazy.combinations(ofCount: ...3))
|
||||
XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 0...))
|
||||
}
|
||||
}
|
||||
@@ -14,33 +14,23 @@ import XCTest
|
||||
|
||||
final class CompactedTests: XCTestCase {
|
||||
|
||||
let tests: [[Int?]] =
|
||||
[nil, nil, nil, 0, 1, 2]
|
||||
.uniquePermutations(ofCount: 0...)
|
||||
.map(Array.init)
|
||||
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)
|
||||
expectEqualSequences(
|
||||
seq.compactMap({ $0 }), seq.compacted())
|
||||
expectEqualSequences(
|
||||
collection.compactMap({ $0 }), collection.compacted())
|
||||
XCTAssertEqualSequences(seq.compactMap({ $0 }), seq.compacted())
|
||||
XCTAssertEqualSequences(collection.compactMap({ $0 }), collection.compacted())
|
||||
}
|
||||
}
|
||||
|
||||
func testCompactedBidirectionalCollection() {
|
||||
for array in self.tests {
|
||||
expectEqualSequences(
|
||||
array.compactMap({ $0 }).reversed(),
|
||||
array.compacted().reversed())
|
||||
XCTAssertEqualSequences(array.compactMap({ $0 }).reversed(), array.compacted().reversed())
|
||||
}
|
||||
}
|
||||
|
||||
func testCollectionTraversals() {
|
||||
let validator = IndexValidator<CompactedCollection<[Int?], Int>>()
|
||||
for array in self.tests {
|
||||
validator.validate(array.compacted())
|
||||
}
|
||||
for array in self.tests { validateIndexTraversals(array.compacted()) }
|
||||
}
|
||||
}
|
||||
@@ -15,10 +15,8 @@ import XCTest
|
||||
final class CycleTests: XCTestCase {
|
||||
func testCycle() {
|
||||
let cycle = (1...4).cycled()
|
||||
expectEqualSequences(
|
||||
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
|
||||
cycle.prefix(20)
|
||||
)
|
||||
XCTAssertEqualSequences(
|
||||
[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() {
|
||||
@@ -31,15 +29,11 @@ final class CycleTests: XCTestCase {
|
||||
XCTAssert(empty.isEmpty)
|
||||
}
|
||||
|
||||
func testCycleLazy() {
|
||||
requireLazySequence((1...4).lazy.cycled())
|
||||
}
|
||||
func testCycleLazy() { XCTAssertLazySequence((1...4).lazy.cycled()) }
|
||||
|
||||
func testRepeated() {
|
||||
let repeats = (1...4).cycled(times: 3)
|
||||
expectEqualSequences(
|
||||
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
|
||||
repeats)
|
||||
XCTAssertEqualSequences([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], repeats)
|
||||
}
|
||||
|
||||
func testRepeatedClosedRange() {
|
||||
@@ -57,9 +51,7 @@ final class CycleTests: XCTestCase {
|
||||
XCTAssert(empty2.isEmpty)
|
||||
}
|
||||
|
||||
func testRepeatedLazy() {
|
||||
requireLazySequence((1...4).lazy.cycled(times: 3))
|
||||
}
|
||||
func testRepeatedLazy() { XCTAssertLazySequence((1...4).lazy.cycled(times: 3)) }
|
||||
|
||||
func testRepeatedIndexMethods() {
|
||||
let cycle = (1..<5).cycled(times: 2)
|
||||
@@ -73,9 +65,7 @@ final class CycleTests: XCTestCase {
|
||||
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)
|
||||
let outOfBounds = cycle.index(nextIndex, offsetBy: 1, limitedBy: cycle.endIndex)
|
||||
XCTAssertNil(outOfBounds)
|
||||
|
||||
let previousIndex = cycle.index(before: nextIndex)
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class EndsWithTests: XCTestCase {
|
||||
func testEndsWithCorrectSuffix() {
|
||||
let a = 8...10
|
||||
let b = 1...10
|
||||
|
||||
XCTAssertTrue(b.ends(with: a))
|
||||
}
|
||||
|
||||
func testDoesntEndWithWrongSuffix() {
|
||||
let a = 8...9
|
||||
let b = 1...10
|
||||
|
||||
XCTAssertFalse(b.ends(with: a))
|
||||
}
|
||||
|
||||
func testDoesntEndWithTooLongSuffix() {
|
||||
XCTAssertFalse((2...5).ends(with: (1...10)))
|
||||
}
|
||||
|
||||
func testEndsWithEmpty() {
|
||||
let a = 8...10
|
||||
let empty: [Int] = []
|
||||
XCTAssertTrue(a.ends(with: empty))
|
||||
}
|
||||
|
||||
func testEmptyEndsWithEmpty() {
|
||||
let empty: [Int] = []
|
||||
XCTAssertTrue(empty.ends(with: empty))
|
||||
}
|
||||
|
||||
func testEmptyDoesNotEndWithNonempty() {
|
||||
XCTAssertFalse([].ends(with: 1...10))
|
||||
}
|
||||
}
|
||||
|
||||
final class EndsWithNonEquatableTests: XCTestCase {
|
||||
func testEndsWithCorrectSuffix() {
|
||||
let a = nonEq(8...10)
|
||||
let b = nonEq(1...10)
|
||||
|
||||
XCTAssertTrue(b.ends(with: a, by: areEquivalent))
|
||||
}
|
||||
|
||||
func testDoesntEndWithWrongSuffix() {
|
||||
let a = nonEq(8...9)
|
||||
let b = nonEq(1...10)
|
||||
|
||||
XCTAssertFalse(b.ends(with: a, by: areEquivalent))
|
||||
}
|
||||
|
||||
func testDoesntEndWithTooLongSuffix() {
|
||||
XCTAssertFalse(nonEq(2...5).ends(with: nonEq(1...10), by: areEquivalent))
|
||||
}
|
||||
|
||||
func testEndsWithEmpty() {
|
||||
let a = nonEq(8...10)
|
||||
let empty: [NotEquatable<Int>] = []
|
||||
XCTAssertTrue(a.ends(with: empty, by: areEquivalent))
|
||||
}
|
||||
|
||||
func testEmptyEndsWithEmpty() {
|
||||
let empty: [NotEquatable<Int>] = []
|
||||
XCTAssertTrue(empty.ends(with: empty, by: areEquivalent))
|
||||
}
|
||||
|
||||
func testEmptyDoesNotEndWithNonempty() {
|
||||
XCTAssertFalse([].ends(with: nonEq(1...10), by: areEquivalent))
|
||||
}
|
||||
|
||||
private func nonEq(_ range: ClosedRange<Int>) -> [NotEquatable<Int>] {
|
||||
range.map(NotEquatable.init)
|
||||
}
|
||||
|
||||
private func areEquivalent<T: Equatable>(
|
||||
lhs: NotEquatable<T>, rhs: NotEquatable<T>
|
||||
) -> Bool {
|
||||
lhs.value == rhs.value
|
||||
}
|
||||
|
||||
private struct NotEquatable<T> {
|
||||
let value: T
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class GroupedTests: XCTestCase {
|
||||
private final class SampleError: Error {}
|
||||
|
||||
// Based on https://github.com/apple/swift/blob/4d1d8a9de5ebc132a17aee9fc267461facf89bf8/validation-test/stdlib/Dictionary.swift#L1974-L1988
|
||||
|
||||
func testGroupedBy() {
|
||||
let r = 0..<10
|
||||
|
||||
let d1 = r.grouped(by: { $0 % 3 })
|
||||
XCTAssertEqual(3, d1.count)
|
||||
XCTAssertEqual(d1[0]!, [0, 3, 6, 9])
|
||||
XCTAssertEqual(d1[1]!, [1, 4, 7])
|
||||
XCTAssertEqual(d1[2]!, [2, 5, 8])
|
||||
|
||||
let d2 = r.grouped(by: { $0 })
|
||||
XCTAssertEqual(10, d2.count)
|
||||
|
||||
let d3 = (0..<0).grouped(by: { $0 })
|
||||
XCTAssertEqual(0, d3.count)
|
||||
}
|
||||
|
||||
func testThrowingFromKeyFunction() {
|
||||
let input = ["Apple", "Banana", "Cherry"]
|
||||
let error = SampleError()
|
||||
|
||||
XCTAssertThrowsError(
|
||||
try input.grouped(by: { (_: String) -> Character in throw error })
|
||||
) { thrownError in
|
||||
XCTAssertIdentical(error, thrownError as? SampleError)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,5 @@ final class IndexedTests: XCTestCase {
|
||||
XCTAssertEqual("I", s[indexOfI])
|
||||
}
|
||||
|
||||
func testIndexedLazy() {
|
||||
requireLazyCollection("ABCD".lazy.indexed())
|
||||
}
|
||||
func testIndexedLazy() { XCTAssertLazyCollection("ABCD".lazy.indexed()) }
|
||||
}
|
||||
@@ -9,39 +9,42 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
@testable import Algorithms
|
||||
|
||||
final class IntersperseTests: XCTestCase {
|
||||
func testSequence() {
|
||||
let interspersed = (1...).prefix(5).interspersed(with: 0)
|
||||
expectEqualSequences(interspersed, [1, 0, 2, 0, 3, 0, 4, 0, 5])
|
||||
XCTAssertEqualSequences(interspersed, [1, 0, 2, 0, 3, 0, 4, 0, 5])
|
||||
}
|
||||
|
||||
func testSequenceEmpty() {
|
||||
let interspersed = (1...).prefix(0).interspersed(with: 0)
|
||||
expectEqualSequences(interspersed, [])
|
||||
XCTAssertEqualSequences(interspersed, [])
|
||||
}
|
||||
|
||||
func testString() {
|
||||
let interspersed = "ABCDE".interspersed(with: "-")
|
||||
expectEqualSequences(interspersed, "A-B-C-D-E")
|
||||
XCTAssertEqualSequences(interspersed, "A-B-C-D-E")
|
||||
validateIndexTraversals(interspersed)
|
||||
}
|
||||
|
||||
func testStringEmpty() {
|
||||
let interspersed = "".interspersed(with: "-")
|
||||
expectEqualSequences(interspersed, "")
|
||||
XCTAssertEqualSequences(interspersed, "")
|
||||
validateIndexTraversals(interspersed)
|
||||
}
|
||||
|
||||
func testArray() {
|
||||
let interspersed = [1, 2, 3, 4].interspersed(with: 0)
|
||||
expectEqualSequences(interspersed, [1, 0, 2, 0, 3, 0, 4])
|
||||
XCTAssertEqualSequences(interspersed, [1, 0, 2, 0, 3, 0, 4])
|
||||
validateIndexTraversals(interspersed)
|
||||
}
|
||||
|
||||
func testArrayEmpty() {
|
||||
let interspersed = [].interspersed(with: 0)
|
||||
expectEqualSequences(interspersed, [])
|
||||
XCTAssertEqualSequences(interspersed, [])
|
||||
validateIndexTraversals(interspersed)
|
||||
}
|
||||
|
||||
func testCollection() {
|
||||
@@ -51,56 +54,12 @@ final class IntersperseTests: XCTestCase {
|
||||
|
||||
func testBidirectionalCollection() {
|
||||
let reversed = "ABCDE".interspersed(with: "-").reversed()
|
||||
expectEqualSequences(reversed, "E-D-C-B-A")
|
||||
}
|
||||
|
||||
func testIndexTraversals() {
|
||||
let validator = IndexValidator<InterspersedSequence<String>>()
|
||||
validator.validate("".interspersed(with: "-"), expectedCount: 0)
|
||||
validator.validate("A".interspersed(with: "-"), expectedCount: 1)
|
||||
validator.validate("AB".interspersed(with: "-"), expectedCount: 3)
|
||||
validator.validate("ABCDE".interspersed(with: "-"), expectedCount: 9)
|
||||
XCTAssertEqualSequences(reversed, "E-D-C-B-A")
|
||||
validateIndexTraversals(reversed)
|
||||
}
|
||||
|
||||
func testIntersperseLazy() {
|
||||
requireLazySequence((1...).prefix(0).lazy.interspersed(with: 0))
|
||||
requireLazyCollection("ABCDE".lazy.interspersed(with: "-"))
|
||||
}
|
||||
|
||||
func testInterspersedMap() {
|
||||
expectEqualSequences(
|
||||
(0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
|
||||
[])
|
||||
|
||||
expectEqualSequences(
|
||||
(0..<1).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
|
||||
[0])
|
||||
|
||||
expectEqualSequences(
|
||||
(0..<5).lazy.interspersedMap({ $0 }, with: { $0 + $1 + 100 }),
|
||||
[0, 101, 1, 103, 2, 105, 3, 107, 4])
|
||||
}
|
||||
|
||||
func testInterspersedMapLazy() {
|
||||
requireLazySequence(
|
||||
AnySequence([]).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }))
|
||||
requireLazyCollection(
|
||||
(0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }))
|
||||
}
|
||||
|
||||
func testInterspersedMapIndexTraversals() {
|
||||
let validator = IndexValidator<InterspersedMapSequence<Range<Int>, Int>>()
|
||||
validator.validate(
|
||||
(0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
|
||||
expectedCount: 0)
|
||||
validator.validate(
|
||||
(0..<1).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
|
||||
expectedCount: 1)
|
||||
validator.validate(
|
||||
(0..<2).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
|
||||
expectedCount: 3)
|
||||
validator.validate(
|
||||
(0..<5).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
|
||||
expectedCount: 9)
|
||||
XCTAssertLazySequence((1...).prefix(0).lazy.interspersed(with: 0))
|
||||
XCTAssertLazyCollection("ABCDE".lazy.interspersed(with: "-"))
|
||||
}
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
|
||||
@testable import Algorithms
|
||||
|
||||
final class JoinedTests: XCTestCase {
|
||||
let stringArrays = [
|
||||
[],
|
||||
[""],
|
||||
["", ""],
|
||||
["foo"],
|
||||
["foo", "bar"],
|
||||
["", "", "foo", "", "bar", "baz", ""],
|
||||
]
|
||||
|
||||
func testJoined() {
|
||||
let expected = ["", "", "", "foo", "foobar", "foobarbaz"]
|
||||
|
||||
for (strings, expected) in zip(stringArrays, expected) {
|
||||
// regular sequence
|
||||
expectEqualSequences(AnySequence(strings).joined(), expected)
|
||||
|
||||
// lazy sequence
|
||||
expectEqualSequences(AnySequence(strings).lazy.joined(), expected)
|
||||
|
||||
// regular collection
|
||||
expectEqualSequences(strings.joined(), expected)
|
||||
|
||||
// lazy collection
|
||||
expectEqualSequences(
|
||||
strings.lazy.joined() as FlattenCollection, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedByElement() {
|
||||
let separator: Character = " "
|
||||
let expected = ["", "", " ", "foo", "foo bar", " foo bar baz "]
|
||||
|
||||
for (strings, expected) in zip(stringArrays, expected) {
|
||||
expectEqualSequences(
|
||||
AnySequence(strings).joined(by: separator), expected)
|
||||
expectEqualSequences(
|
||||
AnySequence(strings).lazy.joined(by: separator), expected)
|
||||
expectEqualSequences(strings.joined(by: separator), expected)
|
||||
expectEqualSequences(strings.lazy.joined(by: separator), expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedBySequence() {
|
||||
let separator = ", "
|
||||
let expected = ["", "", ", ", "foo", "foo, bar", ", , foo, , bar, baz, "]
|
||||
|
||||
for (strings, expected) in zip(stringArrays, expected) {
|
||||
expectEqualSequences(
|
||||
AnySequence(strings).joined(by: separator), expected)
|
||||
expectEqualSequences(
|
||||
AnySequence(strings).lazy.joined(by: separator), expected)
|
||||
expectEqualSequences(strings.joined(by: separator), expected)
|
||||
expectEqualSequences(strings.lazy.joined(by: separator), expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedByElementClosure() {
|
||||
let separator = { (left: String, right: String) -> Character in
|
||||
left.isEmpty || right.isEmpty ? " " : "-"
|
||||
}
|
||||
|
||||
let expected = ["", "", " ", "foo", "foo-bar", " foo bar-baz "]
|
||||
|
||||
for (strings, expected) in zip(stringArrays, expected) {
|
||||
expectEqualSequences(
|
||||
AnySequence(strings).joined(by: separator), expected)
|
||||
expectEqualSequences(
|
||||
AnySequence(strings).lazy.joined(by: separator), expected)
|
||||
expectEqualSequences(strings.joined(by: separator), expected)
|
||||
expectEqualSequences(strings.lazy.joined(by: separator), expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedBySequenceClosure() {
|
||||
let separator = { (left: String, right: String) in
|
||||
"(\(left.count), \(right.count))"
|
||||
}
|
||||
|
||||
let expected = [
|
||||
"",
|
||||
"",
|
||||
"(0, 0)",
|
||||
"foo",
|
||||
"foo(3, 3)bar",
|
||||
"(0, 0)(0, 3)foo(3, 0)(0, 3)bar(3, 3)baz(3, 0)",
|
||||
]
|
||||
|
||||
for (strings, expected) in zip(stringArrays, expected) {
|
||||
expectEqualSequences(
|
||||
AnySequence(strings).joined(by: separator), expected)
|
||||
expectEqualSequences(
|
||||
AnySequence(strings).lazy.joined(by: separator), expected)
|
||||
expectEqualSequences(strings.joined(by: separator), expected)
|
||||
expectEqualSequences(strings.lazy.joined(by: separator), expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedLazy() {
|
||||
requireLazySequence(AnySequence([[1], [2]]).lazy.joined())
|
||||
requireLazySequence(AnySequence([[1], [2]]).lazy.joined(by: 1))
|
||||
requireLazySequence(
|
||||
AnySequence([[1], [2]]).lazy.joined(by: { _, _ in 1 }))
|
||||
requireLazyCollection([[1], [2]].lazy.joined())
|
||||
requireLazyCollection([[1], [2]].lazy.joined(by: 1))
|
||||
requireLazyCollection([[1], [2]].lazy.joined(by: { _, _ in 1 }))
|
||||
}
|
||||
|
||||
func testJoinedIndexTraversals() {
|
||||
let validator = IndexValidator<FlattenCollection<[String]>>()
|
||||
|
||||
// the last test case takes too long to run
|
||||
for strings in stringArrays.dropLast() {
|
||||
validator.validate(strings.joined() as FlattenCollection)
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedByIndexTraversals() {
|
||||
let validator1 = IndexValidator<JoinedByCollection<[String], String>>()
|
||||
let validator2 = IndexValidator<
|
||||
JoinedByClosureCollection<[String], String>
|
||||
>()
|
||||
|
||||
// the last test case takes too long to run
|
||||
for (strings, separator) in product(
|
||||
stringArrays.dropLast(), ["", " ", ", "])
|
||||
{
|
||||
validator1.validate(strings.joined(by: separator))
|
||||
validator2.validate(strings.lazy.joined(by: { _, _ in separator }))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class KeyedTests: XCTestCase {
|
||||
private final class SampleError: Error {}
|
||||
|
||||
func testUniqueKeys() {
|
||||
let d = ["Apple", "Banana", "Cherry"].keyed(by: { $0.first! })
|
||||
XCTAssertEqual(d.count, 3)
|
||||
XCTAssertEqual(d["A"]!, "Apple")
|
||||
XCTAssertEqual(d["B"]!, "Banana")
|
||||
XCTAssertEqual(d["C"]!, "Cherry")
|
||||
XCTAssertNil(d["D"])
|
||||
}
|
||||
|
||||
func testEmpty() {
|
||||
let d = EmptyCollection<String>().keyed(by: { $0.first! })
|
||||
XCTAssertEqual(d.count, 0)
|
||||
}
|
||||
|
||||
func testNonUniqueKeys() throws {
|
||||
let d = ["Apple", "Avocado", "Banana", "Cherry"].keyed(by: { $0.first! })
|
||||
XCTAssertEqual(d.count, 3)
|
||||
XCTAssertEqual(
|
||||
d["A"]!, "Avocado",
|
||||
"On a key-collision, keyed(by:) should take the latest value.")
|
||||
XCTAssertEqual(d["B"]!, "Banana")
|
||||
XCTAssertEqual(d["C"]!, "Cherry")
|
||||
}
|
||||
|
||||
func testNonUniqueKeysWithMergeFunction() {
|
||||
var resolveCallHistory: [(key: Character, current: String, new: String)] =
|
||||
[]
|
||||
let expectedCallHistory = [
|
||||
(key: "A", current: "Apple", new: "Avocado"),
|
||||
(key: "C", current: "Cherry", new: "Coconut"),
|
||||
]
|
||||
|
||||
let d = ["Apple", "Avocado", "Banana", "Cherry", "Coconut"].keyed(
|
||||
by: { $0.first! },
|
||||
resolvingConflictsWith: { key, older, newer in
|
||||
resolveCallHistory.append((key, older, newer))
|
||||
return "\(older)-\(newer)"
|
||||
}
|
||||
)
|
||||
|
||||
XCTAssertEqual(d.count, 3)
|
||||
XCTAssertEqual(d["A"]!, "Apple-Avocado")
|
||||
XCTAssertEqual(d["B"]!, "Banana")
|
||||
XCTAssertEqual(d["C"]!, "Cherry-Coconut")
|
||||
XCTAssertNil(d["D"])
|
||||
|
||||
// Quick/dirty workaround: tuples aren't Equatable
|
||||
XCTAssertEqual(
|
||||
resolveCallHistory.map(String.init(describing:)),
|
||||
expectedCallHistory.map(String.init(describing:))
|
||||
)
|
||||
}
|
||||
|
||||
func testThrowingFromKeyFunction() {
|
||||
let input = ["Apple", "Banana", "Cherry"]
|
||||
let error = SampleError()
|
||||
|
||||
XCTAssertThrowsError(
|
||||
try input.keyed(by: { (_: String) -> Character in throw error })
|
||||
) { thrownError in
|
||||
XCTAssertIdentical(error, thrownError as? SampleError)
|
||||
}
|
||||
}
|
||||
|
||||
func testThrowingFromCombineFunction() {
|
||||
let input = ["Apple", "Avocado", "Banana", "Cherry"]
|
||||
let error = SampleError()
|
||||
|
||||
XCTAssertThrowsError(
|
||||
try input.keyed(
|
||||
by: { $0.first! }, resolvingConflictsWith: { _, _, _ in throw error })
|
||||
) { thrownError in
|
||||
XCTAssertIdentical(error, thrownError as? SampleError)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,625 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Algorithms
|
||||
import XCTest
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Tests for `LazySplitSequence` and `LazySplitCollection`
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
final class LazySplitTests: XCTestCase {
|
||||
func testEmpty() { Validator(subject: [], separator: .element(0), maxSplits: 1).validate() }
|
||||
|
||||
// The following test names indicate the sequence being split, using the
|
||||
// notation
|
||||
// S: Separator
|
||||
// E: Element
|
||||
//
|
||||
// Values of `maxSplit` are interesting when they're less than the number of
|
||||
// splits that would occur with the default. That varies depending on whether
|
||||
// empty subsequences are omitted or included. `Validator` tests both the
|
||||
// default and the value provided, but there are cases below where the
|
||||
// provided `maxSplit` isn't less than the number of splits when empty
|
||||
// subsequences are omitted.
|
||||
|
||||
//===--------------------------------------------------------------------===//
|
||||
// Length 1
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
func testE() { Validator(subject: [1], separator: .element(0), maxSplits: 0).validate() }
|
||||
|
||||
func testS() { Validator(subject: [0], separator: .element(0), maxSplits: 0).validate() }
|
||||
|
||||
//===--------------------------------------------------------------------===//
|
||||
// Length 2
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
func testEE() { Validator(subject: [1, 1], separator: .element(0), maxSplits: 0).validate() }
|
||||
|
||||
func testSS() { Validator(subject: [0, 0], separator: .element(0), maxSplits: 1).validate() }
|
||||
|
||||
func testES() { Validator(subject: [1, 0], separator: .element(0), maxSplits: 0).validate() }
|
||||
|
||||
func testSE() { Validator(subject: [0, 1], separator: .element(0), maxSplits: 0).validate() }
|
||||
|
||||
//===--------------------------------------------------------------------===//
|
||||
// Length 3
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
func testEEE() { Validator(subject: [1, 1, 1], separator: .element(0), maxSplits: 0).validate() }
|
||||
|
||||
func testSSS() { Validator(subject: [0, 0, 0], separator: .element(0), maxSplits: 1).validate() }
|
||||
|
||||
func testAllEES() {
|
||||
let permutations = [[1, 1, 0], [1, 0, 1], [0, 1, 1]]
|
||||
|
||||
for permutation in permutations {
|
||||
Validator(subject: permutation, separator: .element(0), maxSplits: 0).validate()
|
||||
}
|
||||
}
|
||||
|
||||
func testAllESS() {
|
||||
let permutations = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
|
||||
|
||||
for permutation in permutations {
|
||||
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
|
||||
}
|
||||
}
|
||||
|
||||
//===--------------------------------------------------------------------===//
|
||||
// Length 4 with less than two separators.
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
func testEEEE() {
|
||||
Validator(subject: [1, 1, 1, 1], separator: .element(0), maxSplits: 0).validate()
|
||||
}
|
||||
|
||||
func testAllEEES() {
|
||||
let permutations = [[1, 1, 1, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1]]
|
||||
|
||||
for permutation in permutations {
|
||||
Validator(subject: permutation, separator: .element(0), maxSplits: 0).validate()
|
||||
}
|
||||
}
|
||||
|
||||
//===--------------------------------------------------------------------===//
|
||||
// Unique permutations of sequences with at least two separators, so there can
|
||||
// be multiple adjacent separators at the beginning, middle, or end.
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
// All separators.
|
||||
func testSSSS() {
|
||||
Validator(subject: [0, 0, 0, 0], separator: .element(0), maxSplits: 1).validate()
|
||||
}
|
||||
|
||||
// Equal numbers of elements and separators.
|
||||
func testAllEESS() {
|
||||
let permutations = [
|
||||
[1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 0, 1, 1],
|
||||
]
|
||||
|
||||
for permutation in permutations {
|
||||
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
|
||||
}
|
||||
}
|
||||
|
||||
// More separators than elements.
|
||||
func testAllEESSS() {
|
||||
let permutations = [
|
||||
[1, 1, 0, 0, 0], [1, 0, 1, 0, 0], [1, 0, 0, 1, 0], [1, 0, 0, 0, 1], [0, 1, 1, 0, 0],
|
||||
[0, 1, 0, 1, 0], [0, 1, 0, 0, 1], [0, 0, 1, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 1, 1],
|
||||
]
|
||||
|
||||
for permutation in permutations {
|
||||
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
|
||||
}
|
||||
}
|
||||
|
||||
// More elements than separators.
|
||||
func testAllEEESS() {
|
||||
let permutations = [
|
||||
[1, 1, 1, 0, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 1], [1, 0, 1, 1, 0], [1, 0, 1, 0, 1],
|
||||
[1, 0, 0, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], [0, 1, 0, 1, 1], [0, 0, 1, 1, 1],
|
||||
]
|
||||
|
||||
for permutation in permutations {
|
||||
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
|
||||
}
|
||||
}
|
||||
|
||||
//===--------------------------------------------------------------------===//
|
||||
// Unique permutations of sequences with at least three separators.
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
func testAllESSS() {
|
||||
let permutations = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
|
||||
|
||||
for permutation in permutations {
|
||||
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
|
||||
}
|
||||
}
|
||||
|
||||
func testAllEEEESSS() {
|
||||
let permutations = [
|
||||
[1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0], [1, 1, 1, 0, 0, 1, 0], [1, 1, 1, 0, 0, 0, 1],
|
||||
[1, 1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1, 0], [1, 1, 0, 1, 0, 0, 1], [1, 1, 0, 0, 1, 1, 0],
|
||||
[1, 1, 0, 0, 1, 0, 1], [1, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0],
|
||||
[1, 0, 1, 1, 0, 0, 1], [1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 0, 1, 1],
|
||||
[1, 0, 0, 1, 1, 1, 0], [1, 0, 0, 1, 1, 0, 1], [1, 0, 0, 1, 0, 1, 1], [1, 0, 0, 0, 1, 1, 1],
|
||||
[0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0],
|
||||
[0, 1, 1, 0, 1, 0, 1], [0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 1, 1, 0], [0, 1, 0, 1, 1, 0, 1],
|
||||
[0, 1, 0, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 1],
|
||||
[0, 0, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1],
|
||||
]
|
||||
|
||||
for permutation in permutations {
|
||||
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
|
||||
}
|
||||
}
|
||||
|
||||
//===--------------------------------------------------------------------===//
|
||||
// Unique permutations of sequences with at least four separators, so there
|
||||
// can be two runs of multiple adjacent separators: beginning and end,
|
||||
// beginning and middle, or end and middle.
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
// Equal numbers of separators and elements.
|
||||
func testAllEEEESSSS() {
|
||||
let permutations = [
|
||||
[1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0, 0], [1, 1, 1, 0, 0, 1, 0, 0],
|
||||
[1, 1, 1, 0, 0, 0, 1, 0], [1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 0, 1, 1, 0, 0, 0],
|
||||
[1, 1, 0, 1, 0, 1, 0, 0], [1, 1, 0, 1, 0, 0, 1, 0], [1, 1, 0, 1, 0, 0, 0, 1],
|
||||
[1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 0, 1, 0], [1, 1, 0, 0, 1, 0, 0, 1],
|
||||
[1, 1, 0, 0, 0, 1, 1, 0], [1, 1, 0, 0, 0, 1, 0, 1], [1, 1, 0, 0, 0, 0, 1, 1],
|
||||
[1, 0, 1, 1, 1, 0, 0, 0], [1, 0, 1, 1, 0, 1, 0, 0], [1, 0, 1, 1, 0, 0, 1, 0],
|
||||
[1, 0, 1, 1, 0, 0, 0, 1], [1, 0, 1, 0, 1, 1, 0, 0], [1, 0, 1, 0, 1, 0, 1, 0],
|
||||
[1, 0, 1, 0, 1, 0, 0, 1], [1, 0, 1, 0, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 0, 1],
|
||||
[1, 0, 1, 0, 0, 0, 1, 1], [1, 0, 0, 1, 1, 1, 0, 0], [1, 0, 0, 1, 1, 0, 1, 0],
|
||||
[1, 0, 0, 1, 1, 0, 0, 1], [1, 0, 0, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0, 1, 0, 1],
|
||||
[1, 0, 0, 1, 0, 0, 1, 1], [1, 0, 0, 0, 1, 1, 1, 0], [1, 0, 0, 0, 1, 1, 0, 1],
|
||||
[1, 0, 0, 0, 1, 0, 1, 1], [1, 0, 0, 0, 0, 1, 1, 1], [0, 1, 1, 1, 1, 0, 0, 0],
|
||||
[0, 1, 1, 1, 0, 1, 0, 0], [0, 1, 1, 1, 0, 0, 1, 0], [0, 1, 1, 1, 0, 0, 0, 1],
|
||||
[0, 1, 1, 0, 1, 1, 0, 0], [0, 1, 1, 0, 1, 0, 1, 0], [0, 1, 1, 0, 1, 0, 0, 1],
|
||||
[0, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 0, 0, 0, 1, 1],
|
||||
[0, 1, 0, 1, 1, 1, 0, 0], [0, 1, 0, 1, 1, 0, 1, 0], [0, 1, 0, 1, 1, 0, 0, 1],
|
||||
[0, 1, 0, 1, 0, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 0, 1, 1],
|
||||
[0, 1, 0, 0, 1, 1, 1, 0], [0, 1, 0, 0, 1, 1, 0, 1], [0, 1, 0, 0, 1, 0, 1, 1],
|
||||
[0, 1, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 1, 0],
|
||||
[0, 0, 1, 1, 1, 0, 0, 1], [0, 0, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 0, 1, 0, 1],
|
||||
[0, 0, 1, 1, 0, 0, 1, 1], [0, 0, 1, 0, 1, 1, 1, 0], [0, 0, 1, 0, 1, 1, 0, 1],
|
||||
[0, 0, 1, 0, 1, 0, 1, 1], [0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1, 0],
|
||||
[0, 0, 0, 1, 1, 1, 0, 1], [0, 0, 0, 1, 1, 0, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1],
|
||||
[0, 0, 0, 0, 1, 1, 1, 1],
|
||||
]
|
||||
|
||||
for permutation in permutations {
|
||||
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
|
||||
}
|
||||
}
|
||||
|
||||
// More separators than elements.
|
||||
func testAllEEESSSS() {
|
||||
let permutations = [
|
||||
[1, 1, 1, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0], [1, 1, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 1, 0],
|
||||
[1, 1, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 0, 0], [1, 0, 1, 0, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0],
|
||||
[1, 0, 1, 0, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0], [1, 0, 0, 1, 0, 1, 0], [1, 0, 0, 1, 0, 0, 1],
|
||||
[1, 0, 0, 0, 1, 1, 0], [1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 1, 1], [0, 1, 1, 1, 0, 0, 0],
|
||||
[0, 1, 1, 0, 1, 0, 0], [0, 1, 1, 0, 0, 1, 0], [0, 1, 1, 0, 0, 0, 1], [0, 1, 0, 1, 1, 0, 0],
|
||||
[0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 0, 1], [0, 1, 0, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0, 1],
|
||||
[0, 1, 0, 0, 0, 1, 1], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1, 0], [0, 0, 1, 1, 0, 0, 1],
|
||||
[0, 0, 1, 0, 1, 1, 0], [0, 0, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 0],
|
||||
[0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 1, 1, 1],
|
||||
]
|
||||
|
||||
for permutation in permutations {
|
||||
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
|
||||
}
|
||||
}
|
||||
|
||||
// More elements than separators.
|
||||
func testAllEEEEESSSS() {
|
||||
let permutations = [
|
||||
[1, 1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 0, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 0],
|
||||
[1, 1, 1, 1, 0, 0, 0, 1, 0], [1, 1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 1, 0, 1, 1, 0, 0, 0],
|
||||
[1, 1, 1, 0, 1, 0, 1, 0, 0], [1, 1, 1, 0, 1, 0, 0, 1, 0], [1, 1, 1, 0, 1, 0, 0, 0, 1],
|
||||
[1, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 1, 0, 0, 1, 0, 1, 0], [1, 1, 1, 0, 0, 1, 0, 0, 1],
|
||||
[1, 1, 1, 0, 0, 0, 1, 1, 0], [1, 1, 1, 0, 0, 0, 1, 0, 1], [1, 1, 1, 0, 0, 0, 0, 1, 1],
|
||||
[1, 1, 0, 1, 1, 1, 0, 0, 0], [1, 1, 0, 1, 1, 0, 1, 0, 0], [1, 1, 0, 1, 1, 0, 0, 1, 0],
|
||||
[1, 1, 0, 1, 1, 0, 0, 0, 1], [1, 1, 0, 1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1, 0, 1, 0],
|
||||
[1, 1, 0, 1, 0, 1, 0, 0, 1], [1, 1, 0, 1, 0, 0, 1, 1, 0], [1, 1, 0, 1, 0, 0, 1, 0, 1],
|
||||
[1, 1, 0, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 1, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 1, 0],
|
||||
[1, 1, 0, 0, 1, 1, 0, 0, 1], [1, 1, 0, 0, 1, 0, 1, 1, 0], [1, 1, 0, 0, 1, 0, 1, 0, 1],
|
||||
[1, 1, 0, 0, 1, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1, 1, 0], [1, 1, 0, 0, 0, 1, 1, 0, 1],
|
||||
[1, 1, 0, 0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 0, 0, 1, 1, 1], [1, 0, 1, 1, 1, 1, 0, 0, 0],
|
||||
[1, 0, 1, 1, 1, 0, 1, 0, 0], [1, 0, 1, 1, 1, 0, 0, 1, 0], [1, 0, 1, 1, 1, 0, 0, 0, 1],
|
||||
[1, 0, 1, 1, 0, 1, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0, 1, 0], [1, 0, 1, 1, 0, 1, 0, 0, 1],
|
||||
[1, 0, 1, 1, 0, 0, 1, 1, 0], [1, 0, 1, 1, 0, 0, 1, 0, 1], [1, 0, 1, 1, 0, 0, 0, 1, 1],
|
||||
[1, 0, 1, 0, 1, 1, 1, 0, 0], [1, 0, 1, 0, 1, 1, 0, 1, 0], [1, 0, 1, 0, 1, 1, 0, 0, 1],
|
||||
[1, 0, 1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0, 0, 1, 1],
|
||||
[1, 0, 1, 0, 0, 1, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1], [1, 0, 1, 0, 0, 1, 0, 1, 1],
|
||||
[1, 0, 1, 0, 0, 0, 1, 1, 1], [1, 0, 0, 1, 1, 1, 1, 0, 0], [1, 0, 0, 1, 1, 1, 0, 1, 0],
|
||||
[1, 0, 0, 1, 1, 1, 0, 0, 1], [1, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 0, 1, 1, 0, 1, 0, 1],
|
||||
[1, 0, 0, 1, 1, 0, 0, 1, 1], [1, 0, 0, 1, 0, 1, 1, 1, 0], [1, 0, 0, 1, 0, 1, 1, 0, 1],
|
||||
[1, 0, 0, 1, 0, 1, 0, 1, 1], [1, 0, 0, 1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 1, 1, 1, 1, 0],
|
||||
[1, 0, 0, 0, 1, 1, 1, 0, 1], [1, 0, 0, 0, 1, 1, 0, 1, 1], [1, 0, 0, 0, 1, 0, 1, 1, 1],
|
||||
[1, 0, 0, 0, 0, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 0, 1, 0, 0],
|
||||
[0, 1, 1, 1, 1, 0, 0, 1, 0], [0, 1, 1, 1, 1, 0, 0, 0, 1], [0, 1, 1, 1, 0, 1, 1, 0, 0],
|
||||
[0, 1, 1, 1, 0, 1, 0, 1, 0], [0, 1, 1, 1, 0, 1, 0, 0, 1], [0, 1, 1, 1, 0, 0, 1, 1, 0],
|
||||
[0, 1, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 1, 0, 0, 0, 1, 1], [0, 1, 1, 0, 1, 1, 1, 0, 0],
|
||||
[0, 1, 1, 0, 1, 1, 0, 1, 0], [0, 1, 1, 0, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 0, 1, 1, 0],
|
||||
[0, 1, 1, 0, 1, 0, 1, 0, 1], [0, 1, 1, 0, 1, 0, 0, 1, 1], [0, 1, 1, 0, 0, 1, 1, 1, 0],
|
||||
[0, 1, 1, 0, 0, 1, 1, 0, 1], [0, 1, 1, 0, 0, 1, 0, 1, 1], [0, 1, 1, 0, 0, 0, 1, 1, 1],
|
||||
[0, 1, 0, 1, 1, 1, 1, 0, 0], [0, 1, 0, 1, 1, 1, 0, 1, 0], [0, 1, 0, 1, 1, 1, 0, 0, 1],
|
||||
[0, 1, 0, 1, 1, 0, 1, 1, 0], [0, 1, 0, 1, 1, 0, 1, 0, 1], [0, 1, 0, 1, 1, 0, 0, 1, 1],
|
||||
[0, 1, 0, 1, 0, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 1, 0, 1], [0, 1, 0, 1, 0, 1, 0, 1, 1],
|
||||
[0, 1, 0, 1, 0, 0, 1, 1, 1], [0, 1, 0, 0, 1, 1, 1, 1, 0], [0, 1, 0, 0, 1, 1, 1, 0, 1],
|
||||
[0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 1, 0, 0, 1, 0, 1, 1, 1], [0, 1, 0, 0, 0, 1, 1, 1, 1],
|
||||
[0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0, 1],
|
||||
[0, 0, 1, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 1, 0, 1, 0, 1], [0, 0, 1, 1, 1, 0, 0, 1, 1],
|
||||
[0, 0, 1, 1, 0, 1, 1, 1, 0], [0, 0, 1, 1, 0, 1, 1, 0, 1], [0, 0, 1, 1, 0, 1, 0, 1, 1],
|
||||
[0, 0, 1, 1, 0, 0, 1, 1, 1], [0, 0, 1, 0, 1, 1, 1, 1, 0], [0, 0, 1, 0, 1, 1, 1, 0, 1],
|
||||
[0, 0, 1, 0, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1, 1, 1, 1],
|
||||
[0, 0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 0, 1], [0, 0, 0, 1, 1, 1, 0, 1, 1],
|
||||
[0, 0, 0, 1, 1, 0, 1, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1, 1],
|
||||
]
|
||||
|
||||
for permutation in permutations {
|
||||
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
|
||||
}
|
||||
}
|
||||
|
||||
//===--------------------------------------------------------------------===//
|
||||
// Permutations of a sequence with six separators, so there can be multiple
|
||||
// adjacent separators at the beginning, middle, _and_ end.
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
// More separators than elements.
|
||||
func testAllEEESSSSSS() {
|
||||
let permutations = [
|
||||
[1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 1, 0, 0, 0, 0],
|
||||
[1, 1, 0, 0, 0, 1, 0, 0, 0], [1, 1, 0, 0, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 0, 0, 1, 0],
|
||||
[1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 0, 0, 0, 0], [1, 0, 1, 0, 1, 0, 0, 0, 0],
|
||||
[1, 0, 1, 0, 0, 1, 0, 0, 0], [1, 0, 1, 0, 0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 0, 0, 1, 0],
|
||||
[1, 0, 1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0, 0, 0], [1, 0, 0, 1, 0, 1, 0, 0, 0],
|
||||
[1, 0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 0, 1, 0, 0, 0, 1, 0], [1, 0, 0, 1, 0, 0, 0, 0, 1],
|
||||
[1, 0, 0, 0, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 0, 1, 0, 0], [1, 0, 0, 0, 1, 0, 0, 1, 0],
|
||||
[1, 0, 0, 0, 1, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1, 1, 0, 0], [1, 0, 0, 0, 0, 1, 0, 1, 0],
|
||||
[1, 0, 0, 0, 0, 1, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 1, 0], [1, 0, 0, 0, 0, 0, 1, 0, 1],
|
||||
[1, 0, 0, 0, 0, 0, 0, 1, 1], [0, 1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0, 0, 0],
|
||||
[0, 1, 1, 0, 0, 1, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 0, 0], [0, 1, 1, 0, 0, 0, 0, 1, 0],
|
||||
[0, 1, 1, 0, 0, 0, 0, 0, 1], [0, 1, 0, 1, 1, 0, 0, 0, 0], [0, 1, 0, 1, 0, 1, 0, 0, 0],
|
||||
[0, 1, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 1, 0, 0, 0, 0, 1],
|
||||
[0, 1, 0, 0, 1, 1, 0, 0, 0], [0, 1, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0, 0, 1, 0],
|
||||
[0, 1, 0, 0, 1, 0, 0, 0, 1], [0, 1, 0, 0, 0, 1, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 1, 0],
|
||||
[0, 1, 0, 0, 0, 1, 0, 0, 1], [0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0, 1],
|
||||
[0, 1, 0, 0, 0, 0, 0, 1, 1], [0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 1, 0, 0, 0],
|
||||
[0, 0, 1, 1, 0, 0, 1, 0, 0], [0, 0, 1, 1, 0, 0, 0, 1, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1],
|
||||
[0, 0, 1, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0, 1, 0],
|
||||
[0, 0, 1, 0, 1, 0, 0, 0, 1], [0, 0, 1, 0, 0, 1, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 1, 0],
|
||||
[0, 0, 1, 0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 0, 1, 0, 1],
|
||||
[0, 0, 1, 0, 0, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0, 0],
|
||||
[0, 0, 0, 1, 1, 0, 0, 1, 0], [0, 0, 0, 1, 1, 0, 0, 0, 1], [0, 0, 0, 1, 0, 1, 1, 0, 0],
|
||||
[0, 0, 0, 1, 0, 1, 0, 1, 0], [0, 0, 0, 1, 0, 1, 0, 0, 1], [0, 0, 0, 1, 0, 0, 1, 1, 0],
|
||||
[0, 0, 0, 1, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1, 1, 0, 0],
|
||||
[0, 0, 0, 0, 1, 1, 0, 1, 0], [0, 0, 0, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 1, 0, 1, 1, 0],
|
||||
[0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 0],
|
||||
[0, 0, 0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1],
|
||||
]
|
||||
|
||||
for permutation in permutations {
|
||||
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
|
||||
}
|
||||
}
|
||||
|
||||
//===--------------------------------------------------------------------===//
|
||||
// Specific examples of interest.
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
// The motivating example from
|
||||
// https://github.com/apple/swift-algorithms/issues/59.
|
||||
func testSplitFilenameComponents() {
|
||||
Validator(subject: "archive.tar.gz", separator: .element("."), maxSplits: 1).validate()
|
||||
}
|
||||
|
||||
// Examples from documentation.
|
||||
func testSequenceDocExamples() {
|
||||
// Closure version.
|
||||
let numbers = stride(from: 1, through: 16, by: 1)
|
||||
Validator(
|
||||
subject: Array(numbers), separator: .closure({ $0 % 3 == 0 || $0 % 5 == 0 }), maxSplits: 1
|
||||
).validate()
|
||||
|
||||
// Equatable element version.
|
||||
let numbers2 = [1, 2, 0, 3, 4, 0, 0, 5]
|
||||
Validator(subject: numbers2, separator: .element(0), maxSplits: 1).validate()
|
||||
}
|
||||
|
||||
func testCollectionDocExample() {
|
||||
let line = "BLANCHE: I don't want realism. I want magic!"
|
||||
Validator(subject: line, separator: .element("."), maxSplits: 1).validate()
|
||||
}
|
||||
|
||||
// Patterns tested in a previous version of this file which aren't tested
|
||||
// above. Preserved to ensure we're not losing any test coverage.
|
||||
func testVintagePatterns() {
|
||||
let pattern1 = [1, 2, 42, 3, 4, 42, 5, 6, 42, 7]
|
||||
Validator(subject: pattern1, separator: .element(42), maxSplits: 2).validate()
|
||||
Validator(subject: pattern1, separator: .element(42), maxSplits: 0).validate()
|
||||
|
||||
let pattern2 = [42, 1, 2, 42, 3, 4, 42, 5, 6, 42, 7]
|
||||
Validator(subject: pattern2, separator: .element(42), maxSplits: 2).validate()
|
||||
|
||||
let pattern3 = [1, 2, 42, 3, 4, 42, 42, 5, 6, 42, 7]
|
||||
Validator(subject: pattern3, separator: .element(42), maxSplits: 2).validate()
|
||||
|
||||
let pattern4 = [1, 2, 42, 3, 4, 42, 42, 5, 6, 42, 7, 42, 42, 42]
|
||||
Validator(subject: pattern4, separator: .element(42), maxSplits: 1).validate()
|
||||
}
|
||||
|
||||
//===--------------------------------------------------------------------===//
|
||||
// Protocol conformance.
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
func testLaziness() {
|
||||
let splitSequence = AnySequence([1, 2, 42, 3]).lazy.split(separator: 42)
|
||||
XCTAssertLazySequence(splitSequence)
|
||||
|
||||
let splitCollection = "foo.bar".lazy.split(separator: ".")
|
||||
XCTAssertLazySequence(splitCollection)
|
||||
XCTAssertLazyCollection(splitCollection)
|
||||
}
|
||||
|
||||
// TODO: Need a version of `validateIndexTraversals` that doesn't require
|
||||
// `BidirectionalCollection` conformance.
|
||||
|
||||
//===--------------------------------------------------------------------===//
|
||||
// Validator
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
/// Splits a collection as both a lazy sequence and a lazy collection, using
|
||||
/// the provided separator, and compares the results to those of the Standard
|
||||
/// Library's eager splits, which are assumed to be correct.
|
||||
///
|
||||
/// Tests all combinations of default and provided `maxSplit` arguments and
|
||||
/// default (true) and explicit false for `omittingEmptySubsequences`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - subject: The collection whose splits will be validated.
|
||||
/// - separator: The element of the collection--or a predicate function to
|
||||
/// determine the element--on which to split.
|
||||
/// - maxSplits: The value to pass for `maxSplits` during validation. The
|
||||
/// default value is also validated.
|
||||
fileprivate struct Validator<C: Collection> where C.Element: Equatable, C.SubSequence: Equatable {
|
||||
enum Separator {
|
||||
case element(C.Element)
|
||||
case closure((C.Element) -> Bool)
|
||||
}
|
||||
|
||||
let subject: C
|
||||
let separator: Separator
|
||||
let maxSplits: Int
|
||||
|
||||
func validate() {
|
||||
_validateAsSequence(AnySequence(subject))
|
||||
_validateAsCollection(subject)
|
||||
}
|
||||
|
||||
private enum MaxSplits: CustomStringConvertible {
|
||||
case provided(Int)
|
||||
case defaultValue
|
||||
|
||||
var description: String {
|
||||
switch self {
|
||||
case .provided(let value): return "maxSplits: \(value)"
|
||||
case .defaultValue: return "maxSplits: default"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum OmittingEmptySubsequences: CustomStringConvertible {
|
||||
case provided(Bool)
|
||||
case defaultValue
|
||||
|
||||
var description: String {
|
||||
switch self {
|
||||
case .provided(let value): return "omittingEmptySubsequences: \(value)"
|
||||
case .defaultValue: return "omittingEmptySubsequences: default"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func failureMessage<L: LazySequenceProtocol, S: Sequence>(
|
||||
actual: L, expected: S, maxSplits: MaxSplits,
|
||||
omittingEmptySubsequences: OmittingEmptySubsequences
|
||||
) -> String {
|
||||
"for \(Array(subject).debugDescription), \(maxSplits), \(omittingEmptySubsequences): \(Array(actual).debugDescription) != \(Array(expected).debugDescription)"
|
||||
}
|
||||
|
||||
private func _validateAsSequence<T: Sequence>(_ s: T) where T.Element == C.Element {
|
||||
// Default max splits, omitting empty sequences
|
||||
switch separator {
|
||||
case let .element(element):
|
||||
let expected = s.split(separator: element).map { Array($0) }
|
||||
let actual = s.lazy.split(separator: element)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .defaultValue,
|
||||
omittingEmptySubsequences: .defaultValue))
|
||||
case let .closure(closure):
|
||||
let expected = s.split(whereSeparator: closure).map { Array($0) }
|
||||
let actual = s.lazy.split(whereSeparator: closure)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .defaultValue,
|
||||
omittingEmptySubsequences: .defaultValue))
|
||||
}
|
||||
|
||||
// Provided max splits, omitting empty sequences
|
||||
switch separator {
|
||||
case let .element(element):
|
||||
let expected = s.split(separator: element, maxSplits: maxSplits).map { Array($0) }
|
||||
let actual = s.lazy.split(separator: element, maxSplits: maxSplits)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
|
||||
omittingEmptySubsequences: .defaultValue))
|
||||
case let .closure(closure):
|
||||
let expected = s.split(maxSplits: maxSplits, whereSeparator: closure).map { Array($0) }
|
||||
let actual = s.lazy.split(maxSplits: maxSplits, whereSeparator: closure)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
|
||||
omittingEmptySubsequences: .defaultValue))
|
||||
}
|
||||
|
||||
// Default max splits, including empty sequences
|
||||
switch separator {
|
||||
case let .element(element):
|
||||
let expected = s.split(separator: element, omittingEmptySubsequences: false).map {
|
||||
Array($0)
|
||||
}
|
||||
let actual = s.lazy.split(separator: element, omittingEmptySubsequences: false)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .defaultValue,
|
||||
omittingEmptySubsequences: .provided(false)))
|
||||
case let .closure(closure):
|
||||
let expected = s.split(omittingEmptySubsequences: false, whereSeparator: closure).map {
|
||||
Array($0)
|
||||
}
|
||||
let actual = s.lazy.split(omittingEmptySubsequences: false, whereSeparator: closure)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .defaultValue,
|
||||
omittingEmptySubsequences: .provided(false)))
|
||||
}
|
||||
|
||||
// Provided max splits, including empty sequences
|
||||
switch separator {
|
||||
case let .element(element):
|
||||
let expected = s.split(
|
||||
separator: element, maxSplits: maxSplits, omittingEmptySubsequences: false
|
||||
).map { Array($0) }
|
||||
let actual = s.lazy.split(
|
||||
separator: element, maxSplits: maxSplits, omittingEmptySubsequences: false)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
|
||||
omittingEmptySubsequences: .provided(false)))
|
||||
case let .closure(closure):
|
||||
let expected = s.split(
|
||||
maxSplits: maxSplits, omittingEmptySubsequences: false, whereSeparator: closure
|
||||
).map { Array($0) }
|
||||
let actual = s.lazy.split(
|
||||
maxSplits: maxSplits, omittingEmptySubsequences: false, whereSeparator: closure)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
|
||||
omittingEmptySubsequences: .provided(false)))
|
||||
}
|
||||
}
|
||||
|
||||
private func _validateAsCollection(_ c: C) {
|
||||
// Default max splits, omitting empty sequences
|
||||
switch separator {
|
||||
case let .element(element):
|
||||
let expected = c.split(separator: element)
|
||||
let actual = c.lazy.split(separator: element)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .defaultValue,
|
||||
omittingEmptySubsequences: .defaultValue))
|
||||
case let .closure(closure):
|
||||
let expected = c.split(whereSeparator: closure)
|
||||
let actual = c.lazy.split(whereSeparator: closure)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .defaultValue,
|
||||
omittingEmptySubsequences: .defaultValue))
|
||||
}
|
||||
|
||||
// Provided max splits, omitting empty sequences
|
||||
switch separator {
|
||||
case let .element(element):
|
||||
let expected = c.split(separator: element, maxSplits: maxSplits)
|
||||
let actual = c.lazy.split(separator: element, maxSplits: maxSplits)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
|
||||
omittingEmptySubsequences: .defaultValue))
|
||||
case let .closure(closure):
|
||||
let expected = c.split(maxSplits: maxSplits, whereSeparator: closure)
|
||||
let actual = c.lazy.split(maxSplits: maxSplits, whereSeparator: closure)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
|
||||
omittingEmptySubsequences: .defaultValue))
|
||||
}
|
||||
|
||||
// Default max splits, including empty sequences
|
||||
switch separator {
|
||||
case let .element(element):
|
||||
let expected = c.split(separator: element, omittingEmptySubsequences: false)
|
||||
let actual = c.lazy.split(separator: element, omittingEmptySubsequences: false)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .defaultValue,
|
||||
omittingEmptySubsequences: .provided(false)))
|
||||
case let .closure(closure):
|
||||
let expected = c.split(omittingEmptySubsequences: false, whereSeparator: closure)
|
||||
let actual = c.lazy.split(omittingEmptySubsequences: false, whereSeparator: closure)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .defaultValue,
|
||||
omittingEmptySubsequences: .provided(false)))
|
||||
}
|
||||
|
||||
// Provided max splits, including empty sequences
|
||||
switch separator {
|
||||
case let .element(element):
|
||||
let expected = c.split(
|
||||
separator: element, maxSplits: maxSplits, omittingEmptySubsequences: false)
|
||||
let actual = c.lazy.split(
|
||||
separator: element, maxSplits: maxSplits, omittingEmptySubsequences: false)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
|
||||
omittingEmptySubsequences: .provided(false)))
|
||||
case let .closure(closure):
|
||||
let expected = c.split(
|
||||
maxSplits: maxSplits, omittingEmptySubsequences: false, whereSeparator: closure)
|
||||
let actual = c.lazy.split(
|
||||
maxSplits: maxSplits, omittingEmptySubsequences: false, whereSeparator: closure)
|
||||
XCTAssertEqualSequences(
|
||||
expected, actual,
|
||||
failureMessage(
|
||||
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
|
||||
omittingEmptySubsequences: .provided(false)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,30 +17,28 @@ final class SortedPrefixTests: XCTestCase {
|
||||
// Replacement at start and end
|
||||
let input = [10, 11, 12, 1, 13, 2, 14, 3, 4, 5, 6, 0, 7, 8, 9]
|
||||
let min = input.min(count: 5)
|
||||
expectEqualSequences(min, 0..<5)
|
||||
XCTAssertEqualSequences(min, 0..<5)
|
||||
|
||||
// Stability with all equal values
|
||||
let maxZeroes = Array(repeating: 0, count: 100)
|
||||
.enumerated()
|
||||
.max(count: 5, sortedBy: { $0.element < $1.element })
|
||||
expectEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
|
||||
let maxZeroes = Array(repeating: 0, count: 100).enumerated().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]
|
||||
let max = input.max(count: 5)
|
||||
expectEqualSequences(max, 10..<15)
|
||||
XCTAssertEqualSequences(max, 10..<15)
|
||||
|
||||
// Stability with all equal values
|
||||
let maxZeroes = Array(repeating: 0, count: 100)
|
||||
.enumerated()
|
||||
.max(count: 5, sortedBy: { $0.element < $1.element })
|
||||
expectEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
|
||||
let maxZeroes = Array(repeating: 0, count: 100).enumerated().max(
|
||||
count: 5, sortedBy: { $0.element < $1.element })
|
||||
XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
|
||||
}
|
||||
|
||||
func testEmpty() {
|
||||
let array: [Int] = []
|
||||
let array = [Int]()
|
||||
XCTAssertEqual(array.min(count: 0), [])
|
||||
XCTAssertEqual(array.min(count: 100), [])
|
||||
|
||||
@@ -52,11 +50,11 @@ final class SortedPrefixTests: XCTestCase {
|
||||
let input = (1...100).shuffled().interspersed(with: 50)
|
||||
let seq = AnySequence(input)
|
||||
|
||||
expectEqualSequences(seq.min(count: 0), [])
|
||||
expectEqualSequences(seq.min(count: 5), 1...5)
|
||||
XCTAssertEqualSequences(seq.min(count: 0), [])
|
||||
XCTAssertEqualSequences(seq.min(count: 5), 1...5)
|
||||
|
||||
expectEqualSequences(seq.max(count: 0), [])
|
||||
expectEqualSequences(seq.max(count: 5), 96...100)
|
||||
XCTAssertEqualSequences(seq.max(count: 0), [])
|
||||
XCTAssertEqualSequences(seq.max(count: 5), 96...100)
|
||||
}
|
||||
|
||||
func testSortedPrefixComparable() {
|
||||
@@ -64,7 +62,7 @@ final class SortedPrefixTests: XCTestCase {
|
||||
|
||||
XCTAssertEqual(array.min(count: 0), [])
|
||||
XCTAssertEqual(array.min(count: 1), [1])
|
||||
expectEqualSequences(array.min(count: 5), array.sorted().prefix(5))
|
||||
XCTAssertEqualSequences(array.min(count: 5), array.sorted().prefix(5))
|
||||
XCTAssertEqual(array.min(count: 10), array.sorted())
|
||||
}
|
||||
|
||||
@@ -83,22 +81,14 @@ final class SortedPrefixTests: XCTestCase {
|
||||
XCTAssertEqual(input.min(count: 1, sortedBy: <), [range.lowerBound])
|
||||
XCTAssertEqual(input.min(count: 1, sortedBy: >), [range.upperBound])
|
||||
|
||||
expectEqualSequences(input.min(count: 5, sortedBy: <), range.prefix(5))
|
||||
expectEqualSequences(
|
||||
input.min(count: 5, sortedBy: >),
|
||||
range.suffix(5).reversed())
|
||||
XCTAssertEqualSequences(input.min(count: 5, sortedBy: <), range.prefix(5))
|
||||
XCTAssertEqualSequences(input.min(count: 5, sortedBy: >), range.suffix(5).reversed())
|
||||
|
||||
expectEqualSequences(
|
||||
input.min(count: 500, sortedBy: <),
|
||||
range.prefix(500))
|
||||
expectEqualSequences(
|
||||
input.min(count: 500, sortedBy: >),
|
||||
range.suffix(500).reversed())
|
||||
XCTAssertEqualSequences(input.min(count: 500, sortedBy: <), range.prefix(500))
|
||||
XCTAssertEqualSequences(input.min(count: 500, sortedBy: >), range.suffix(500).reversed())
|
||||
|
||||
expectEqualSequences(input.min(count: 1000, sortedBy: <), range)
|
||||
expectEqualSequences(
|
||||
input.min(count: 1000, sortedBy: >),
|
||||
range.reversed())
|
||||
XCTAssertEqualSequences(input.min(count: 1000, sortedBy: <), range)
|
||||
XCTAssertEqualSequences(input.min(count: 1000, sortedBy: >), range.reversed())
|
||||
}
|
||||
|
||||
func testMaxCountWithHugeInput() {
|
||||
@@ -111,22 +101,14 @@ final class SortedPrefixTests: XCTestCase {
|
||||
XCTAssertEqual(input.max(count: 1, sortedBy: <), [range.upperBound])
|
||||
XCTAssertEqual(input.max(count: 1, sortedBy: >), [range.lowerBound])
|
||||
|
||||
expectEqualSequences(input.max(count: 5, sortedBy: <), range.suffix(5))
|
||||
expectEqualSequences(
|
||||
input.max(count: 5, sortedBy: >),
|
||||
range.prefix(5).reversed())
|
||||
XCTAssertEqualSequences(input.max(count: 5, sortedBy: <), range.suffix(5))
|
||||
XCTAssertEqualSequences(input.max(count: 5, sortedBy: >), range.prefix(5).reversed())
|
||||
|
||||
expectEqualSequences(
|
||||
input.max(count: 500, sortedBy: <),
|
||||
range.suffix(500))
|
||||
expectEqualSequences(
|
||||
input.max(count: 500, sortedBy: >),
|
||||
range.prefix(500).reversed())
|
||||
XCTAssertEqualSequences(input.max(count: 500, sortedBy: <), range.suffix(500))
|
||||
XCTAssertEqualSequences(input.max(count: 500, sortedBy: >), range.prefix(500).reversed())
|
||||
|
||||
expectEqualSequences(input.max(count: 1000, sortedBy: <), range)
|
||||
expectEqualSequences(
|
||||
input.max(count: 1000, sortedBy: >),
|
||||
range.reversed())
|
||||
XCTAssertEqualSequences(input.max(count: 1000, sortedBy: <), range)
|
||||
XCTAssertEqualSequences(input.max(count: 1000, sortedBy: >), range.reversed())
|
||||
}
|
||||
|
||||
func testStability() {
|
||||
@@ -140,18 +122,10 @@ final class SortedPrefixTests: XCTestCase {
|
||||
assertStability(Array(repeating: 0, count: 100), withCount: 5)
|
||||
assertStability(Array(repeating: 0, count: 100), withCount: 20)
|
||||
assertStability(Array(repeating: 0, count: 100), withCount: 100)
|
||||
assertStability(
|
||||
Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50),
|
||||
withCount: 2)
|
||||
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(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 2)
|
||||
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)
|
||||
@@ -167,116 +141,19 @@ final class SortedPrefixTests: XCTestCase {
|
||||
assertStability([1, 1, 1, 0, 0, 0], withCount: 5)
|
||||
}
|
||||
|
||||
func assertStability(
|
||||
_ actual: [Int],
|
||||
withCount count: Int
|
||||
) {
|
||||
func stableOrder(
|
||||
a: (offset: Int, element: Int),
|
||||
b: (offset: Int, element: Int)
|
||||
) -> Bool {
|
||||
a.element == b.element
|
||||
? a.offset < b.offset
|
||||
: a.element < b.element
|
||||
func assertStability(_ actual: [Int], withCount count: Int) {
|
||||
func stableOrder(a: (offset: Int, element: Int), 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 }
|
||||
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 }
|
||||
let sorted = actual.enumerated().max(count: count) { $0.element < $1.element }
|
||||
XCTAssert(sorted.isSorted(by: stableOrder))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class MinAndMaxTests: XCTestCase {
|
||||
/// Confirms that empty sequences yield no results.
|
||||
func testEmpty() {
|
||||
XCTAssertNil(EmptyCollection<Int>().minAndMax())
|
||||
}
|
||||
|
||||
/// Confirms the same element is used when there is only one.
|
||||
func testSingleElement() {
|
||||
let result = CollectionOfOne(2).minAndMax()
|
||||
XCTAssertEqual(result?.min, 2)
|
||||
XCTAssertEqual(result?.max, 2)
|
||||
}
|
||||
|
||||
/// Confirms the same value is used when all the elements have it.
|
||||
func testSingleValueMultipleElements() {
|
||||
let result = repeatElement(3.3, count: 5).minAndMax()
|
||||
XCTAssertEqual(result?.min, 3.3)
|
||||
XCTAssertEqual(result?.max, 3.3)
|
||||
|
||||
// Even count
|
||||
let result2 = repeatElement("c" as Character, count: 6).minAndMax()
|
||||
XCTAssertEqual(result2?.min, "c")
|
||||
XCTAssertEqual(result2?.max, "c")
|
||||
}
|
||||
|
||||
/// Confirms when the minimum value is constantly updated, but the maximum
|
||||
/// never is.
|
||||
func testRampDown() {
|
||||
let result = (1...5).reversed().minAndMax()
|
||||
XCTAssertEqual(result?.min, 1)
|
||||
XCTAssertEqual(result?.max, 5)
|
||||
|
||||
// Even count
|
||||
let result2 = "fedcba".minAndMax()
|
||||
XCTAssertEqual(result2?.min, "a")
|
||||
XCTAssertEqual(result2?.max, "f")
|
||||
}
|
||||
|
||||
/// Confirms when the maximum value is constantly updated, but the minimum
|
||||
/// never is.
|
||||
func testRampUp() {
|
||||
let result = (1...5).minAndMax()
|
||||
XCTAssertEqual(result?.min, 1)
|
||||
XCTAssertEqual(result?.max, 5)
|
||||
|
||||
// Even count
|
||||
let result2 = "abcdef".minAndMax()
|
||||
XCTAssertEqual(result2?.min, "a")
|
||||
XCTAssertEqual(result2?.max, "f")
|
||||
}
|
||||
|
||||
/// Confirms when the maximum and minimum change during a run.
|
||||
func testUpsAndDowns() {
|
||||
let result = [4, 3, 3, 5, 2, 0, 7, 6].minAndMax()
|
||||
XCTAssertEqual(result?.min, 0)
|
||||
XCTAssertEqual(result?.max, 7)
|
||||
|
||||
// Odd count
|
||||
let result2 = "gfabdec".minAndMax()
|
||||
XCTAssertEqual(result2?.min, "a")
|
||||
XCTAssertEqual(result2?.max, "g")
|
||||
}
|
||||
|
||||
/// Confirms that the given predicate is used to find the min/max.
|
||||
func testPredicate() {
|
||||
let result = (1...5).minAndMax(by: >)
|
||||
XCTAssertEqual(result?.min, 5)
|
||||
XCTAssertEqual(result?.max, 1)
|
||||
|
||||
// Odd count
|
||||
let result2 = "gfabdec".minAndMax(by: >)
|
||||
XCTAssertEqual(result2?.min, "g")
|
||||
XCTAssertEqual(result2?.max, "a")
|
||||
}
|
||||
|
||||
/// Confirms that the min and max are "stable" as defined for minAndMax.
|
||||
func testStability() {
|
||||
for n in 1...10 {
|
||||
let result = repeatElement(0, count: n)
|
||||
.enumerated()
|
||||
.minAndMax(by: { $0.element < $1.element })
|
||||
XCTAssertEqual(result?.min.offset, 0)
|
||||
XCTAssertEqual(result?.max.offset, n - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,17 +30,17 @@ final class PartitionTests: XCTestCase {
|
||||
|
||||
var b = a
|
||||
var r = b[p..<q].stablePartition(by: f)
|
||||
expectEqualSequences(b[..<p], prefix)
|
||||
expectEqualSequences(b[q...], suffix)
|
||||
expectEqualSequences(b[p..<r], subrange.filter(notf))
|
||||
expectEqualSequences(b[r..<q], subrange.filter(f))
|
||||
XCTAssertEqualSequences(b[..<p], prefix)
|
||||
XCTAssertEqualSequences(b[q...], suffix)
|
||||
XCTAssertEqualSequences(b[p..<r], subrange.filter(notf))
|
||||
XCTAssertEqualSequences(b[r..<q], subrange.filter(f))
|
||||
|
||||
b = a
|
||||
r = b[p..<q].stablePartition(by: notf)
|
||||
expectEqualSequences(b[..<p], prefix)
|
||||
expectEqualSequences(b[q...], suffix)
|
||||
expectEqualSequences(b[p..<r], subrange.filter(f))
|
||||
expectEqualSequences(b[r..<q], subrange.filter(notf))
|
||||
XCTAssertEqualSequences(b[..<p], prefix)
|
||||
XCTAssertEqualSequences(b[q...], suffix)
|
||||
XCTAssertEqualSequences(b[p..<r], subrange.filter(f))
|
||||
XCTAssertEqualSequences(b[r..<q], subrange.filter(notf))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,13 +49,13 @@ final class PartitionTests: XCTestCase {
|
||||
let notf = { !f($0) }
|
||||
var b = a
|
||||
var r = b.stablePartition(by: f)
|
||||
expectEqualSequences(b[..<r], a.filter(notf))
|
||||
expectEqualSequences(b[r...], a.filter(f))
|
||||
XCTAssertEqualSequences(b[..<r], a.filter(notf))
|
||||
XCTAssertEqualSequences(b[r...], a.filter(f))
|
||||
|
||||
b = a
|
||||
r = b.stablePartition(by: notf)
|
||||
expectEqualSequences(b[..<r], a.filter(f))
|
||||
expectEqualSequences(b[r...], a.filter(notf))
|
||||
XCTAssertEqualSequences(b[..<r], a.filter(f))
|
||||
XCTAssertEqualSequences(b[r...], a.filter(notf))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,12 +72,10 @@ final class PartitionTests: XCTestCase {
|
||||
let p = b.stablePartition(subrange: partitionRange, by: condition)
|
||||
|
||||
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
||||
expectEqualSequences(
|
||||
b[partitionRange.lowerBound..<p],
|
||||
a[partitionRange].filter { !condition($0) })
|
||||
expectEqualSequences(
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -96,26 +94,6 @@ final class PartitionTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testPartitioningIndexWithEmptyInput() {
|
||||
let input: [Int] = []
|
||||
|
||||
let a = input.partitioningIndex(where: { _ in true })
|
||||
XCTAssertEqual(a, input.startIndex)
|
||||
|
||||
let b = input.partitioningIndex(where: { _ in false })
|
||||
XCTAssertEqual(b, input.endIndex)
|
||||
}
|
||||
|
||||
func testPartitioningIndexWithOneEmptyPartition() {
|
||||
let input: Range<Int> = (0..<10)
|
||||
|
||||
let a = input.partitioningIndex(where: { $0 > 10 })
|
||||
XCTAssertEqual(a, input.endIndex)
|
||||
|
||||
let b = input.partitioningIndex(where: { $0 >= 0 })
|
||||
XCTAssertEqual(b, input.startIndex)
|
||||
}
|
||||
|
||||
func testPartitionWithSubrangeBidirectionalCollection() {
|
||||
for length in 10...20 {
|
||||
let a = Array(0..<length)
|
||||
@@ -127,12 +105,10 @@ final class PartitionTests: XCTestCase {
|
||||
let p = b.partition(subrange: partitionRange, by: condition)
|
||||
|
||||
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
||||
expectEqualSequences(
|
||||
b[partitionRange.lowerBound..<p],
|
||||
a[partitionRange].filter { !condition($0) })
|
||||
expectUnorderedEqualSequences(
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,58 +127,18 @@ final class PartitionTests: XCTestCase {
|
||||
let bdcp = bdc.partition(subrange: partitionRange, by: condition)
|
||||
|
||||
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
||||
expectEqualSequences(
|
||||
b[partitionRange.lowerBound..<p],
|
||||
a[partitionRange].filter { !condition($0) })
|
||||
expectUnorderedEqualSequences(
|
||||
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.
|
||||
expectEqualSequences(
|
||||
b[partitionRange.lowerBound..<p],
|
||||
bdc[partitionRange.lowerBound..<bdcp])
|
||||
expectUnorderedEqualSequences(
|
||||
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])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testPartitionedWithEmptyInput() {
|
||||
let input: [Int] = []
|
||||
|
||||
let s0 = input.partitioned(by: { _ in true })
|
||||
|
||||
XCTAssertTrue(s0.0.isEmpty)
|
||||
XCTAssertTrue(s0.1.isEmpty)
|
||||
}
|
||||
|
||||
/// Test the example given in the `partitioned(by:)` documentation.
|
||||
func testPartitionedExample() throws {
|
||||
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
||||
let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
||||
XCTAssertEqual(longNames, ["Vivien", "Marlon"])
|
||||
XCTAssertEqual(shortNames, ["Kim", "Karl"])
|
||||
}
|
||||
|
||||
func testPartitionedWithPredicate() throws {
|
||||
let s0 = ["A", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() })
|
||||
let s1 = ["a", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() })
|
||||
let s2 = ["a", "B", "c", "D"].partitioned(by: { $0 == $0.lowercased() })
|
||||
let s3 = ["a", "B", "c", "d"].partitioned(by: { $0 == $0.lowercased() })
|
||||
|
||||
XCTAssertEqual(s0.0, ["A", "B", "C", "D"])
|
||||
XCTAssertEqual(s0.1, [])
|
||||
|
||||
XCTAssertEqual(s1.0, ["B", "C", "D"])
|
||||
XCTAssertEqual(s1.1, ["a"])
|
||||
|
||||
XCTAssertEqual(s2.0, ["B", "D"])
|
||||
XCTAssertEqual(s2.1, ["a", "c"])
|
||||
|
||||
XCTAssertEqual(s3.0, ["B"])
|
||||
XCTAssertEqual(s3.1, ["a", "c", "d"])
|
||||
}
|
||||
}
|
||||
@@ -29,16 +29,14 @@ final class PermutationsTests: XCTestCase {
|
||||
}
|
||||
|
||||
func ts<R: RangeExpression>(count: R) where R.Bound == Int {
|
||||
let p = count.relative(to: 0 ..< .max)
|
||||
.clamped(to: 0..<c.count + 1)
|
||||
.flatMap {
|
||||
c.permutations(ofCount: $0)
|
||||
}
|
||||
let p = count.relative(to: 0 ..< .max).clamped(to: 0..<c.count + 1).flatMap {
|
||||
c.permutations(ofCount: $0)
|
||||
}
|
||||
|
||||
let p2 = c.permutations(ofCount: count)
|
||||
|
||||
XCTAssertEqual(p.count, p2.count)
|
||||
expectEqualSequences(p, Array(p2))
|
||||
XCTAssertEqualSequences(p, Array(p2))
|
||||
}
|
||||
|
||||
t(count: 0)
|
||||
@@ -102,81 +100,43 @@ final class PermutationsTests: XCTestCase {
|
||||
XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], numbers)
|
||||
}
|
||||
|
||||
func testPermutationsLazy() {
|
||||
requireLazySequence("ABCD".lazy.permutations(ofCount: 2))
|
||||
}
|
||||
func testPermutationsLazy() { XCTAssertLazySequence("ABCD".lazy.permutations(ofCount: 2)) }
|
||||
|
||||
func testDocumentationExample1() {
|
||||
// From Guides/Permutations.md
|
||||
let numbers = [10, 20, 30]
|
||||
let permutations = numbers.permutations()
|
||||
expectEqualSequences(
|
||||
XCTAssertEqualSequences(
|
||||
permutations,
|
||||
[
|
||||
[10, 20, 30],
|
||||
[10, 30, 20],
|
||||
[20, 10, 30],
|
||||
[20, 30, 10],
|
||||
[30, 10, 20],
|
||||
[30, 20, 10],
|
||||
])
|
||||
[[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)
|
||||
expectEqualSequences(
|
||||
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()
|
||||
expectEqualSequences(
|
||||
XCTAssertEqualSequences(
|
||||
permutations,
|
||||
[
|
||||
[20, 10, 10],
|
||||
[20, 10, 10],
|
||||
[10, 20, 10],
|
||||
[10, 10, 20],
|
||||
[10, 20, 10],
|
||||
[10, 10, 20],
|
||||
])
|
||||
[[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...)
|
||||
expectEqualSequences(
|
||||
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],
|
||||
[], [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],
|
||||
])
|
||||
}
|
||||
|
||||
@@ -184,15 +144,11 @@ final class PermutationsTests: XCTestCase {
|
||||
// From Permutations.swift
|
||||
let names = ["Alex", "Celeste", "Davide"]
|
||||
let permutations = names.permutations(ofCount: 2)
|
||||
expectEqualSequences(
|
||||
XCTAssertEqualSequences(
|
||||
permutations,
|
||||
[
|
||||
["Alex", "Celeste"],
|
||||
["Alex", "Davide"],
|
||||
["Celeste", "Alex"],
|
||||
["Celeste", "Davide"],
|
||||
["Davide", "Alex"],
|
||||
["Davide", "Celeste"],
|
||||
["Alex", "Celeste"], ["Alex", "Davide"], ["Celeste", "Alex"], ["Celeste", "Davide"],
|
||||
["Davide", "Alex"], ["Davide", "Celeste"],
|
||||
])
|
||||
}
|
||||
|
||||
@@ -200,18 +156,11 @@ final class PermutationsTests: XCTestCase {
|
||||
// From Permutations.swift
|
||||
let names = ["Alex", "Celeste", "Davide"]
|
||||
let permutations = names.permutations(ofCount: 1...2)
|
||||
expectEqualSequences(
|
||||
XCTAssertEqualSequences(
|
||||
permutations,
|
||||
[
|
||||
["Alex"],
|
||||
["Celeste"],
|
||||
["Davide"],
|
||||
["Alex", "Celeste"],
|
||||
["Alex", "Davide"],
|
||||
["Celeste", "Alex"],
|
||||
["Celeste", "Davide"],
|
||||
["Davide", "Alex"],
|
||||
["Davide", "Celeste"],
|
||||
["Alex"], ["Celeste"], ["Davide"], ["Alex", "Celeste"], ["Alex", "Davide"],
|
||||
["Celeste", "Alex"], ["Celeste", "Davide"], ["Davide", "Alex"], ["Davide", "Celeste"],
|
||||
])
|
||||
}
|
||||
}
|
||||
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user