Compare commits

...
10 Commits
Author SHA1 Message Date
Nate Cook e25cf27e57 Update changelog for 0.2.0 release (#144) 2021-05-17 13:08:39 -05:00
Nate Cook 3484ac31f6 Make chunked(on:) include subject value in Element type (#142) 2021-05-16 15:02:03 -05:00
Nate Cook f9f3a5ccc4 Minor revisions to minAndMax() (#143)
* Settle on 2-way approach (s/o to @NevinBR)
* Add tests for predicate usage and stability
* Update the return value semantics
2021-05-13 12:31:13 -05:00
Daryle Walker 4038b5da40 Simultaneous Minimum and Maximum Evaluation (#90)
* Add function to find MIN and MAX in one pass

Add a method extending sequences that finds both the minimal and maximal elements of the receiver in a single pass, based off a given ordering predicate.  Add an overload that defaults the comparison predicate to the standard less-than operator.
2021-05-12 16:11:33 -05:00
Nate CookandTim Vermeulen 65ef6cb966 Update AdjacentPairs implementations and tests (#139)
* Update AdjacentPairs implementations and tests

* Add conditional lazy conformances

* Apply suggestions from code review

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

Co-authored-by: Tim Vermeulen <tvermeulen@apple.com>
2021-05-05 19:15:47 +02:00
Michael Pangburn 0f27d99c89 Introduce adjacentPairs (#119) 2021-05-04 13:08:33 -05:00
66a56e36e7 Add new heading and description for partitionIndex 🤷‍♂️. (#137)
* Add new heading and description for partitionIndex 🤷‍♂️.

* Move into Other useful ops.

* Update README.md

Co-authored-by: Nate Cook <natecook@apple.com>

* Update README.md

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

Co-authored-by: Nate Cook <natecook@apple.com>
Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
2021-05-03 13:30:25 -05:00
Pranav KasettiandImgBotApp 9901a50b03 [ImgBot] Optimize images (#133)
*Total -- 151.00kb -> 133.25kb (11.75%)

/Guides/Resources/SortedPrefix/FewElements.png -- 73.60kb -> 64.27kb (12.67%)
/Guides/Resources/SortedPrefix/ManyElements.png -- 77.40kb -> 68.98kb (10.87%)

Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com>

Co-authored-by: ImgBotApp <ImgBotHelp@gmail.com>
2021-04-29 15:49:40 -05:00
Pranav KasettiandXiaodi Wu 061501a712 PR template Contribution Guidelines link doesn't work (#136)
* Fix template relative URLs.

* Update .github/PULL_REQUEST_TEMPLATE.md

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

* Fix indent

Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
2021-04-23 11:14:44 +02:00
Nate Cook dbc48be5dd Update changelog for 0.1.1 release (#132) 2021-04-16 13:22:28 -05:00
15 changed files with 846 additions and 62 deletions

No files matched your search

+1 -1
View File
@@ -17,5 +17,5 @@ Replace this paragraph with a description of your changes and rationale. Provide
### Checklist
- [ ] I've added at least one test that validates that my change is working, if appropriate
- [ ] I've followed the code style of the rest of the project
- [ ] I've read the [Contribution Guidelines](../CONTRIBUTING.md)
- [ ] I've read the [Contribution Guidelines](../blob/main/CONTRIBUTING.md)
- [ ] I've updated the documentation if necessary
+1 -1
View File
@@ -34,5 +34,5 @@ What is the impact of this change on existing users? Does it deprecate or remove
### Checklist
- [ ] I've added at least one test that validates that my change is working, if appropriate
- [ ] I've followed the code style of the rest of the project
- [ ] I've read the [Contribution Guidelines](../../CONTRIBUTING.md)
- [ ] I've read the [Contribution Guidelines](../../blob/main/CONTRIBUTING.md)
- [ ] I've updated the documentation if necessary
+51 -2
View File
@@ -12,10 +12,52 @@ package updates, you can specify your package dependency using
## [Unreleased]
*No changes yet.*
*No new changes.*
---
## [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
@@ -149,7 +191,9 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
<!-- Link references for releases -->
[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.1.0...HEAD
[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.2.0...HEAD
[0.2.0]: https://github.com/apple/swift-algorithms/compare/0.1.1...0.2.0
[0.1.1]: https://github.com/apple/swift-algorithms/compare/0.1.0...0.1.1
[0.1.0]: https://github.com/apple/swift-algorithms/compare/0.0.4...0.1.0
[0.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
@@ -173,17 +217,21 @@ 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
[#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
<!-- Link references for contributors -->
[AustinConlon]: https://github.com/apple/swift-algorithms/commits?author=AustinConlon
[benrimmington]: https://github.com/apple/swift-algorithms/commits?author=benrimmington
[bjhomer]: https://github.com/apple/swift-algorithms/commits?author=bjhomer
[CTMacUser]: https://github.com/apple/swift-algorithms/commits?author=CTMacUser
[danielctull]: https://github.com/apple/swift-algorithms/commits?author=danielctull
[dhruvshah8]: https://github.com/apple/swift-algorithms/commits?author=dhruvshah8
[egorzhdan]: https://github.com/apple/swift-algorithms/commits?author=egorzhdan
@@ -197,6 +245,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
[markuswntr]: https://github.com/apple/swift-algorithms/commits?author=markuswntr
[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
[natecook1000]: https://github.com/apple/swift-algorithms/commits?author=natecook1000
[nordicio]: https://github.com/apple/swift-algorithms/commits?author=nordicio
[ollieatkinson]: https://github.com/apple/swift-algorithms/commits?author=ollieatkinson
+52
View File
@@ -0,0 +1,52 @@
# AdjacentPairs
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/AdjacentPairs.swift) |
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/AdjacentPairsTests.swift)]
Lazily iterates over tuples of adjacent elements.
This operation is available for any sequence by calling the `adjacentPairs()` method.
```swift
let numbers = (1...5)
let pairs = numbers.adjacentPairs()
// Array(pairs) == [(1, 2), (2, 3), (3, 4), (4, 5)]
```
## Detailed Design
The `adjacentPairs()` method is declared as a `Sequence` extension returning `AdjacentPairsSequence` and as a `Collection` extension returning `AdjacentPairsCollection`.
```swift
extension Sequence {
public func adjacentPairs() -> AdjacentPairsSequence<Self>
}
```
```swift
extension Collection {
public func adjacentPairs() -> AdjacentPairsCollection<Self>
}
```
The `AdjacentPairsSequence` type is a sequence, and the `AdjacentPairsCollection` type is a collection with conditional conformance to `BidirectionalCollection` and `RandomAccessCollection` when the underlying collection conforms.
### Complexity
Calling `adjacentPairs` is an O(1) operation.
### Naming
This method is named for clarity while remaining agnostic to any particular domain of programming. In natural language processing, this operation is akin to computing a list of bigrams; however, this algorithm is not specific to this use case.
[naming]: https://forums.swift.org/t/naming-of-chained-with/40999/
### 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`.
+17 -15
View File
@@ -22,18 +22,20 @@ let chunks = numbers.chunked(by: { $0 <= $1 })
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!)
// [["David"], ["Kyle", "Karoy"], ["Nate"]]
// [("D", ["David"]), ("K", ["Kyle", "Karoy"]), ("N", ["Nate"])]
```
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.
The `chunks(ofCount:)` method takes a `count` parameter (greater than zero)
and separates the collection into chunks of this given count.
If the `count` parameter is evenly divided by the count of the base `Collection`,
all the chunks will have a count equal to the parameter.
Otherwise, the last chunk will contain the remaining elements.
```swift
let names = ["David", "Kyle", "Karoy", "Nate"]
@@ -44,17 +46,17 @@ let remaining = names.chunks(ofCount: 3)
// equivalent to [["David", "Kyle", "Karoy"], ["Nate"]]
```
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.
The `chunks(ofCount:)` is the subject of an [existing SE proposal][proposal].
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 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
@@ -70,21 +72,21 @@ extension Collection {
public func chunked<Subject: Equatable>(
on projection: (Element) -> Subject
) -> [SubSequence]
) -> [(Subject, SubSequence)]
}
extension LazyCollectionProtocol {
public func chunked(
by belongInSameGroup: @escaping (Element, Element) -> Bool
) -> Chunked<Elements>
) -> ChunkedBy<Elements, Element>
public func chunked<Subject: Equatable>(
on projection: @escaping (Element) -> Subject
) -> Chunked<Elements>
) -> ChunkedOn<Elements, Subject>
}
```
The `Chunked` type is bidirectional when the wrapped collection is
The `ChunkedBy` and `ChunkedOn` types are bidirectional when the wrapped collection is
bidirectional.
### Complexity
+30 -3
View File
@@ -1,4 +1,4 @@
# Min/Max with Count
# Minima and/or Maxima
[[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)]
@@ -13,6 +13,17 @@ 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:
@@ -31,6 +42,16 @@ 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:
```swift
@@ -39,20 +60,26 @@ 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 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 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)`.
Here are some benchmarks we made that demonstrates how this implementation (SmallestM) behaves when *k* increases (before implementing the fallback):
![Benchmark](Resources/SortedPrefix/FewElements.png)
![Benchmark 2](Resources/SortedPrefix/ManyElements.png)
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.
**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.
**Python:** Defines a `heapq` priority queue that can be used to manually achieve the same result.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 69 KiB

+3
View File
@@ -32,6 +32,7 @@ Read more about the package, and the intent behind it, in the [announcement on s
- [`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.
- [`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
@@ -39,10 +40,12 @@ Read more about the package, and the intent behind it, in the [announcement on s
#### 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.
- [`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.
- [`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/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.
+315
View File
@@ -0,0 +1,315 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Sequence {
/// Creates a sequence of adjacent pairs of elements from this sequence.
///
/// In the `AdjacentPairsSequence` returned by this method, the elements of
/// the *i*th pair are the *i*th and *(i+1)*th elements of the underlying
/// sequence.
/// The following example uses the `adjacentPairs()` method to iterate over
/// adjacent pairs of integers:
///
/// for pair in (1...).prefix(5).adjacentPairs() {
/// print(pair)
/// }
/// // Prints "(1, 2)"
/// // Prints "(2, 3)"
/// // Prints "(3, 4)"
/// // Prints "(4, 5)"
@inlinable
public func adjacentPairs() -> AdjacentPairsSequence<Self> {
AdjacentPairsSequence(base: self)
}
}
extension Collection {
/// A collection of adjacent pairs of elements built from an underlying
/// collection.
///
/// In an `AdjacentPairsCollection`, the elements of the *i*th pair are the
/// *i*th and *(i+1)*th elements of the underlying sequence. The following
/// example uses the `adjacentPairs()` method to iterate over adjacent pairs
/// of integers:
///
/// for pair in (1...5).adjacentPairs() {
/// print(pair)
/// }
/// // Prints "(1, 2)"
/// // Prints "(2, 3)"
/// // Prints "(3, 4)"
/// // Prints "(4, 5)"
@inlinable
public func adjacentPairs() -> AdjacentPairsCollection<Self> {
AdjacentPairsCollection(base: self)
}
}
/// A sequence of adjacent pairs of elements built from an underlying sequence.
///
/// Use the `adjacentPairs()` method on a sequence to create an
/// `AdjacentPairsSequence` instance.
public struct AdjacentPairsSequence<Base: Sequence> {
@usableFromInline
internal let base: Base
/// Creates an instance that makes pairs of adjacent elements from `base`.
@inlinable
internal init(base: Base) {
self.base = base
}
}
extension AdjacentPairsSequence {
/// The iterator for an `AdjacentPairsSequence` or `AdjacentPairsCollection`.
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
public let startIndex: Index
@inlinable
internal init(base: Base) {
self.base = base
// Lazily build the end index, since we can't use the instance
// property pre-initialization
var endIndex: Index {
Index(first: base.endIndex, second: base.endIndex)
}
// Precompute `startIndex` to ensure O(1) behavior.
guard !base.isEmpty else {
self.startIndex = endIndex
return
}
// If there's only one element (i.e. the second index of base == endIndex)
// then this collection should be empty.
let secondIndex = base.index(after: base.startIndex)
self.startIndex = secondIndex == base.endIndex
? endIndex
: Index(first: base.startIndex, second: secondIndex)
}
}
extension AdjacentPairsCollection {
public typealias Iterator = AdjacentPairsSequence<Base>.Iterator
@inlinable
public func makeIterator() -> Iterator {
Iterator(base: base.makeIterator())
}
}
extension AdjacentPairsCollection {
/// A position in an `AdjacentPairsCollection`.
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 endIndex: Index {
Index(first: base.endIndex, second: base.endIndex)
}
@inlinable
public subscript(position: Index) -> (Base.Element, Base.Element) {
(base[position.first], base[position.second])
}
@inlinable
public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance beyond endIndex")
let next = base.index(after: i.second)
return next == base.endIndex
? endIndex
: Index(first: i.second, second: next)
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i }
guard let result = distance > 0
? offsetForward(i, by: distance, limitedBy: endIndex)
: offsetBackward(i, by: -distance, limitedBy: startIndex)
else { fatalError("Index out of bounds") }
return result
}
@inlinable
public func index(
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
) -> Index? {
guard distance != 0 else { return i }
guard limit != i else { return nil }
if distance > 0 {
let limit = limit > i ? limit : endIndex
return offsetForward(i, by: distance, limitedBy: limit)
} else {
let limit = limit < i ? limit : startIndex
return offsetBackward(i, by: -distance, limitedBy: limit)
}
}
@inlinable
internal func offsetForward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance > 0)
assert(limit > i)
guard let newFirst = base.index(i.second, offsetBy: distance - 1, limitedBy: limit.first),
newFirst != base.endIndex
else { return nil }
let newSecond = base.index(after: newFirst)
precondition(newSecond <= base.endIndex, "Can't advance beyond endIndex")
return newSecond == base.endIndex
? endIndex
: Index(first: newFirst, second: newSecond)
}
@inlinable
internal func offsetBackward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance > 0)
assert(limit < i)
let offset = i == endIndex ? 0 : 1
guard let newSecond = base.index(
i.first,
offsetBy: -(distance - offset),
limitedBy: limit.second)
else { return nil }
let newFirst = base.index(newSecond, offsetBy: -1)
precondition(newFirst >= base.startIndex, "Can't move before startIndex")
return Index(first: newFirst, second: newSecond)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
// While there's a 2-step gap between the `first` base index values in
// `endIndex` and the penultimate index of this collection, the `second`
// base index values are consistently one step apart throughout the
// entire collection.
base.distance(from: start.second, to: end.second)
}
@inlinable
public var count: Int {
Swift.max(0, base.count - 1)
}
}
extension AdjacentPairsCollection: BidirectionalCollection
where Base: BidirectionalCollection
{
@inlinable
public func index(before i: Index) -> Index {
precondition(i != startIndex, "Can't offset before startIndex")
let second = i == endIndex
? base.index(before: base.endIndex)
: i.first
let first = base.index(before: second)
return Index(first: first, second: second)
}
}
extension AdjacentPairsCollection: RandomAccessCollection
where Base: RandomAccessCollection {}
extension AdjacentPairsCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
extension AdjacentPairsCollection.Index: Hashable where Base.Index: Hashable {
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(first)
}
}
+95 -35
View File
@@ -10,8 +10,10 @@
//===----------------------------------------------------------------------===//
/// A collection wrapper that breaks a collection into chunks based on a
/// predicate or projection.
public struct Chunked<Base: Collection, Subject> {
/// predicate.
///
/// Call `lazy.chunked(by:)` on a collection to create an instance of this type.
public struct ChunkedBy<Base: Collection, Subject> {
/// The collection that this instance provides a view onto.
@usableFromInline
internal let base: Base
@@ -45,7 +47,7 @@ public struct Chunked<Base: Collection, Subject> {
}
}
extension Chunked: LazyCollectionProtocol {
extension ChunkedBy: LazyCollectionProtocol {
/// A position in a chunked collection.
public struct Index: Comparable {
/// The range corresponding to the chunk at this position.
@@ -106,9 +108,9 @@ extension Chunked: LazyCollectionProtocol {
}
}
extension Chunked.Index: Hashable where Base.Index: Hashable {}
extension ChunkedBy.Index: Hashable where Base.Index: Hashable {}
extension Chunked: BidirectionalCollection
extension ChunkedBy: BidirectionalCollection
where Base: BidirectionalCollection
{
/// Returns the index in the base collection of the start of the chunk ending
@@ -131,11 +133,64 @@ extension Chunked: BidirectionalCollection
}
}
@available(*, deprecated, renamed: "Chunked")
public typealias LazyChunked<Base: Collection, Subject> = Chunked<Base, Subject>
@available(*, deprecated, renamed: "ChunkedBy")
public typealias LazyChunked<Base: Collection, Subject> = ChunkedBy<Base, Subject>
@available(*, deprecated, renamed: "ChunkedBy")
public typealias Chunked<Base: Collection, Subject> = ChunkedBy<Base, Subject>
/// A collection wrapper that breaks a collection into chunks based on a
/// predicate.
///
/// Call `lazy.chunked(on:)` on a collection to create an instance of this type.
public struct ChunkedOn<Base: Collection, Subject> {
@usableFromInline
internal var chunked: ChunkedBy<Base, Subject>
@inlinable
internal init(
base: Base,
projection: @escaping (Base.Element) -> Subject,
belongInSameGroup: @escaping (Subject, Subject) -> Bool
) {
self.chunked = ChunkedBy(base: base, projection: projection, belongInSameGroup: belongInSameGroup)
}
}
extension ChunkedOn: LazyCollectionProtocol {
public typealias Index = ChunkedBy<Base, Subject>.Index
@inlinable
public var startIndex: Index {
chunked.startIndex
}
@inlinable
public var endIndex: Index {
chunked.endIndex
}
@inlinable
public subscript(position: Index) -> (Subject, Base.SubSequence) {
let subsequence = chunked[position]
let subject = chunked.projection(subsequence.first!)
return (subject, subsequence)
}
@inlinable
public func index(after i: Index) -> Index {
chunked.index(after: i)
}
}
extension ChunkedOn: BidirectionalCollection where Base: BidirectionalCollection {
public func index(before i: Index) -> Index {
chunked.index(before: i)
}
}
//===----------------------------------------------------------------------===//
// lazy.chunked(by:)
// lazy.chunked(by:) / lazy.chunked(on:)
//===----------------------------------------------------------------------===//
extension LazyCollectionProtocol {
@@ -146,8 +201,8 @@ extension LazyCollectionProtocol {
@inlinable
public func chunked(
by belongInSameGroup: @escaping (Element, Element) -> Bool
) -> Chunked<Elements, Element> {
Chunked(
) -> ChunkedBy<Elements, Element> {
ChunkedBy(
base: elements,
projection: { $0 },
belongInSameGroup: belongInSameGroup)
@@ -160,8 +215,8 @@ extension LazyCollectionProtocol {
@inlinable
public func chunked<Subject: Equatable>(
on projection: @escaping (Element) -> Subject
) -> Chunked<Elements, Subject> {
Chunked(
) -> ChunkedOn<Elements, Subject> {
ChunkedOn(
base: elements,
projection: projection,
belongInSameGroup: ==)
@@ -169,32 +224,29 @@ extension LazyCollectionProtocol {
}
//===----------------------------------------------------------------------===//
// chunked(by:)
// chunked(by:) / chunked(on:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns a collection of subsequences of this collection, chunked by
/// grouping elements that project to the same value according to the given
/// predicate.
/// the given predicate.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable
internal func chunked<Subject>(
on projection: (Element) throws -> Subject,
by belongInSameGroup: (Subject, Subject) throws -> Bool
public func chunked(
by belongInSameGroup: (Element, Element) throws -> Bool
) rethrows -> [SubSequence] {
guard !isEmpty else { return [] }
var result: [SubSequence] = []
var start = startIndex
var subject = try projection(self[start])
var current = self[start]
for (index, element) in indexed().dropFirst() {
let nextSubject = try projection(element)
if try !belongInSameGroup(subject, nextSubject) {
if try !belongInSameGroup(current, element) {
result.append(self[start..<index])
start = index
subject = nextSubject
current = element
}
}
@@ -204,17 +256,6 @@ extension Collection {
return result
}
/// Returns a collection of subsequences of this collection, chunked by
/// the given predicate.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable
public func chunked(
by belongInSameGroup: (Element, Element) throws -> Bool
) rethrows -> [SubSequence] {
try chunked(on: { $0 }, by: belongInSameGroup)
}
/// Returns a collection of subsequences of this collection, chunked by
/// grouping elements that project to the same value.
@@ -223,8 +264,27 @@ extension Collection {
@inlinable
public func chunked<Subject: Equatable>(
on projection: (Element) throws -> Subject
) rethrows -> [SubSequence] {
try chunked(on: projection, by: ==)
) rethrows -> [(Subject, SubSequence)] {
guard !isEmpty else { return [] }
var result: [(Subject, SubSequence)] = []
var start = startIndex
var subject = try projection(self[start])
for (index, element) in indexed().dropFirst() {
let nextSubject = try projection(element)
if subject != nextSubject {
result.append((subject, self[start..<index]))
start = index
subject = nextSubject
}
}
if start != endIndex {
result.append((subject, self[start..<endIndex]))
}
return result
}
}
+99
View File
@@ -383,3 +383,102 @@ extension Collection where Element: Comparable {
return max(count: count, sortedBy: <)
}
}
//===----------------------------------------------------------------------===//
// Simultaneous minimum and maximum evaluation
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns both the minimum and maximum elements in the sequence, using the
/// given predicate as the comparison between elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// This example shows how to use the `minAndMax(by:)` method on a
/// dictionary to find the key-value pair with the lowest value and the pair
/// with the highest value.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// if let extremeHues = hues.minAndMax(by: {$0.value < $1.value}) {
/// print(extremeHues.min, extremeHues.max)
/// } else {
/// print("There are no hues")
/// }
/// // Prints: "(key: "Coral", value: 16) (key: "Heliotrope", value: 296)"
///
/// - Precondition: The sequence is finite.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: A tuple with the sequence's minimum element, followed by its
/// maximum element. If the sequence provides multiple qualifying minimum
/// elements, the first equivalent element is returned; of multiple maximum
/// elements, the last is returned. If the sequence has no elements, the
/// method returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
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)? {
return minAndMax(by: <)
}
}
@@ -0,0 +1,84 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import Algorithms
final class AdjacentPairsTests: XCTestCase {
func testEmptySequence() {
let pairs = (0...).prefix(0).adjacentPairs()
XCTAssertEqualSequences(pairs, [], by: ==)
}
func testOneElementSequence() {
let pairs = (0...).prefix(1).adjacentPairs()
XCTAssertEqualSequences(pairs, [], by: ==)
}
func testTwoElementSequence() {
let pairs = (0...).prefix(2).adjacentPairs()
XCTAssertEqualSequences(pairs, [(0, 1)], by: ==)
}
func testThreeElementSequence() {
let pairs = (0...).prefix(3).adjacentPairs()
XCTAssertEqualSequences(pairs, [(0, 1), (1, 2)], by: ==)
}
func testManySequences() {
for n in 4...100 {
let pairs = (0...).prefix(n).adjacentPairs()
XCTAssertEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==)
}
}
func testZeroElements() {
let pairs = (0..<0).adjacentPairs()
XCTAssertEqual(pairs.startIndex, pairs.endIndex)
XCTAssertEqualSequences(pairs, [], by: ==)
}
func testOneElement() {
let pairs = (0..<1).adjacentPairs()
XCTAssertEqual(pairs.startIndex, pairs.endIndex)
XCTAssertEqualSequences(pairs, [], by: ==)
}
func testTwoElements() {
let pairs = (0..<2).adjacentPairs()
XCTAssertEqualSequences(pairs, [(0, 1)], by: ==)
}
func testThreeElements() {
let pairs = (0..<3).adjacentPairs()
XCTAssertEqualSequences(pairs, [(0, 1), (1, 2)], by: ==)
}
func testManyElements() {
for n in 4...100 {
let pairs = (0..<n).adjacentPairs()
XCTAssertEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==)
}
}
func testIndexTraversals() {
validateIndexTraversals(
(0..<0).adjacentPairs(),
(0..<1).adjacentPairs(),
(0..<2).adjacentPairs(),
(0..<5).adjacentPairs())
}
func testLaziness() {
XCTAssertLazySequence((0...).lazy.adjacentPairs())
XCTAssertLazyCollection((0..<100).lazy.adjacentPairs())
}
}
+11 -5
View File
@@ -47,8 +47,12 @@ final class ChunkedTests: XCTestCase {
func testSimple() {
// Example
let names = ["David", "Kyle", "Karoy", "Nate"]
let chunks = names.chunked(on: { $0.first })
XCTAssertEqualSequences([["David"], ["Kyle", "Karoy"], ["Nate"]], chunks)
let chunks = names.chunked(on: { $0.first! })
let expected: [(Character, ArraySlice<String>)] = [
("D", ["David"]),
("K", ["Kyle", "Karoy"]),
("N", ["Nate"])]
XCTAssertEqualSequences(expected, chunks, by: ==)
// Empty sequence
XCTAssertEqual(0, names.prefix(0).chunked(on: { $0.first }).count)
@@ -59,10 +63,11 @@ final class ChunkedTests: XCTestCase {
}
func testChunkedOn() {
validateFruitChunks(fruits.chunked(on: { $0.first }))
validateFruitChunks(fruits.chunked(on: { $0.first }).map { $1 })
let lazyChunks = fruits.lazy.chunked(on: { $0.first })
validateFruitChunks(lazyChunks)
validateFruitChunks(lazyChunks.map { $1 })
validateIndexTraversals(lazyChunks)
}
func testChunkedBy() {
@@ -70,6 +75,7 @@ final class ChunkedTests: XCTestCase {
let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first })
validateFruitChunks(lazyChunks)
validateIndexTraversals(lazyChunks)
}
func testChunkedLazy() {
@@ -77,10 +83,10 @@ final class ChunkedTests: XCTestCase {
XCTAssertLazySequence(fruits.lazy.chunked(on: { $0.first }))
}
//===----------------------------------------------------------------------===//
// Tests for `chunks(ofCount:)`
//===----------------------------------------------------------------------===//
func testChunksOfCount() {
XCTAssertEqualSequences([Int]().chunks(ofCount: 1), [])
XCTAssertEqualSequences([Int]().chunks(ofCount: 5), [])
@@ -185,3 +185,90 @@ final class SortedPrefixTests: XCTestCase {
}
}
}
final class MinAndMaxTests: XCTestCase {
/// Confirms that empty sequences yield no results.
func testEmpty() {
XCTAssertNil(EmptyCollection<Int>().minAndMax())
}
/// Confirms the same element is used when there is only one.
func testSingleElement() {
let result = CollectionOfOne(2).minAndMax()
XCTAssertEqual(result?.min, 2)
XCTAssertEqual(result?.max, 2)
}
/// Confirms the same value is used when all the elements have it.
func testSingleValueMultipleElements() {
let result = repeatElement(3.3, count: 5).minAndMax()
XCTAssertEqual(result?.min, 3.3)
XCTAssertEqual(result?.max, 3.3)
// Even count
let result2 = repeatElement("c" as Character, count: 6).minAndMax()
XCTAssertEqual(result2?.min, "c")
XCTAssertEqual(result2?.max, "c")
}
/// Confirms when the minimum value is constantly updated, but the maximum
/// never is.
func testRampDown() {
let result = (1...5).reversed().minAndMax()
XCTAssertEqual(result?.min, 1)
XCTAssertEqual(result?.max, 5)
// Even count
let result2 = "fedcba".minAndMax()
XCTAssertEqual(result2?.min, "a")
XCTAssertEqual(result2?.max, "f")
}
/// Confirms when the maximum value is constantly updated, but the minimum
/// never is.
func testRampUp() {
let result = (1...5).minAndMax()
XCTAssertEqual(result?.min, 1)
XCTAssertEqual(result?.max, 5)
// Even count
let result2 = "abcdef".minAndMax()
XCTAssertEqual(result2?.min, "a")
XCTAssertEqual(result2?.max, "f")
}
/// Confirms when the maximum and minimum change during a run.
func testUpsAndDowns() {
let result = [4, 3, 3, 5, 2, 0, 7, 6].minAndMax()
XCTAssertEqual(result?.min, 0)
XCTAssertEqual(result?.max, 7)
// Odd count
let result2 = "gfabdec".minAndMax()
XCTAssertEqual(result2?.min, "a")
XCTAssertEqual(result2?.max, "g")
}
/// Confirms that the given predicate is used to find the min/max.
func testPredicate() {
let result = (1...5).minAndMax(by: >)
XCTAssertEqual(result?.min, 5)
XCTAssertEqual(result?.max, 1)
// Odd count
let result2 = "gfabdec".minAndMax(by: >)
XCTAssertEqual(result2?.min, "g")
XCTAssertEqual(result2?.max, "a")
}
/// Confirms that the min and max are "stable" as defined for minAndMax.
func testStability() {
for n in 1...10 {
let result = repeatElement(0, count: n)
.enumerated()
.minAndMax(by: { $0.element < $1.element })
XCTAssertEqual(result?.min.offset, 0)
XCTAssertEqual(result?.max.offset, n - 1)
}
}
}