mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-24 04:17:48 +00:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
32aee022ce | ||
|
|
df51f1780b | ||
|
|
288d8b00f2 | ||
|
|
aa6349dea0 | ||
|
|
195e0316d7 | ||
|
|
da475ea9af | ||
|
|
19c1d00177 | ||
|
|
e2fa131d62 | ||
|
|
aeead5ab20 | ||
|
|
c5ea9e3e36 | ||
|
|
e195266e1f |
No files matched your search
+24
-1
@@ -42,6 +42,20 @@ 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`.
|
||||
@@ -69,11 +83,17 @@ 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_) operations, where _n_ is the length of the
|
||||
The existing partition is an O(_n_) operation, 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
|
||||
@@ -82,6 +102,9 @@ 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
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ let package = Package(
|
||||
targets: ["Algorithms"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"),
|
||||
.package(url: "https://github.com/apple/swift-numerics.git", from: "1.0.0"),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
|
||||
@@ -27,6 +27,7 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
||||
#### Subsetting operations
|
||||
|
||||
- [`compacted()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Compacted.md): Drops the `nil`s from a sequence or collection, unwrapping the remaining elements.
|
||||
- [`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.
|
||||
@@ -72,7 +73,7 @@ Finally, add `import Algorithms` to your source code.
|
||||
|
||||
## Source Stability
|
||||
|
||||
The Swift Numerics 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 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 version 1.0 of the `swift-algorithms` package consists of non-underscored declarations that are marked `public` in the `Algorithms` module. Interfaces that aren't part of the public API may continue to change in any release, including patch releases.
|
||||
|
||||
|
||||
@@ -303,7 +303,7 @@ extension Collection {
|
||||
/// A collection that presents the elements of its base collection in
|
||||
/// `SubSequence` chunks of any given count.
|
||||
///
|
||||
/// A `ChunksOfCountCollection` is a lazy view on the base Collection, but it
|
||||
/// A `ChunksOfCountCollection` is a lazy view on the base `Collection`, but it
|
||||
/// does not implicitly confer laziness on algorithms applied to its result. In
|
||||
/// other words, for ordinary collections `c`:
|
||||
///
|
||||
@@ -486,11 +486,11 @@ extension ChunksOfCountCollection {
|
||||
_ i: Index, _ distance: Int
|
||||
) -> Int {
|
||||
if i == endIndex {
|
||||
let remainder = base.count%chunkCount
|
||||
let remainder = base.count % chunkCount
|
||||
// We have to take it into account when calculating offsets.
|
||||
if remainder != 0 {
|
||||
// Distance "minus" one(at this point distance is negative) because we
|
||||
// need to adjust for the last position that have a variadic(remainder)
|
||||
// Distance "minus" one (at this point distance is negative) because we
|
||||
// need to adjust for the last position that have a variadic (remainder)
|
||||
// number of elements.
|
||||
return ((distance + 1) * chunkCount) - remainder
|
||||
}
|
||||
@@ -512,7 +512,7 @@ extension ChunksOfCountCollection {
|
||||
)
|
||||
}
|
||||
|
||||
// Helper to compute index(offsetBy:) index.
|
||||
// Helper to compute `index(offsetBy:)` index.
|
||||
@inlinable
|
||||
internal func makeOffsetIndex(
|
||||
from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int,
|
||||
@@ -525,13 +525,13 @@ extension ChunksOfCountCollection {
|
||||
|
||||
if let limit = limit {
|
||||
if baseIdx == nil {
|
||||
// If we past the bounds while advancing forward and the limit is the
|
||||
// `endIndex`, since the computation on base don't take into account the
|
||||
// remainder, we have to make sure that passing the bound was because of
|
||||
// the distance not just because of a remainder. Special casing is less
|
||||
// expensive than always use count(which could be O(n) for non-random
|
||||
// access collection base) to compute the base distance taking remainder
|
||||
// into account.
|
||||
// If we passed the bounds while advancing forward, and the limit is the
|
||||
// `endIndex`, since the computation on `base` don't take into account
|
||||
// the remainder, we have to make sure that passing the bound was
|
||||
// because of the distance not just because of a remainder. Special
|
||||
// casing is less expensive than always using `count` (which could be
|
||||
// O(n) for non-random access collection base) to compute the base
|
||||
// distance taking remainder into account.
|
||||
if baseDistance > 0 && limit == endIndex {
|
||||
if self.distance(from: i, to: limit) < distance {
|
||||
return nil
|
||||
@@ -561,7 +561,7 @@ extension Collection {
|
||||
/// Returns a `ChunksOfCountCollection<Self>` view presenting the elements in
|
||||
/// chunks with count of the given count parameter.
|
||||
///
|
||||
/// - Parameter count: The size of the chunks. If the count parameter is
|
||||
/// - Parameter count: The size of the chunks. If the `count` parameter is
|
||||
/// evenly divided by the count of the base `Collection` all the chunks will
|
||||
/// have the count equals to size. Otherwise, the last chunk will contain
|
||||
/// the remaining elements.
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// merge(at:by:) / merge(subrange:at:by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension MutableCollection where Self: BidirectionalCollection {
|
||||
public mutating func merge(
|
||||
at middle: Index,
|
||||
by areInAscendingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows {
|
||||
try merge(subrange: startIndex..<endIndex, at: middle, by: areInAscendingOrder)
|
||||
}
|
||||
|
||||
public mutating func merge(
|
||||
subrange: Range<Index>,
|
||||
at middle: Index,
|
||||
by areInAscendingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows {
|
||||
if subrange.lowerBound == middle || subrange.upperBound == middle { return }
|
||||
|
||||
let lowerBound = distance(from: startIndex, to: subrange.lowerBound)
|
||||
let rangeCount = distance(from: subrange.lowerBound, to: subrange.upperBound)
|
||||
let lowerCount = distance(from: subrange.lowerBound, to: middle)
|
||||
|
||||
// FIXME: Insertion sort for small counts?
|
||||
|
||||
let result: Void? = try withContiguousMutableStorageIfAvailable
|
||||
{ selfBuffer -> Void in
|
||||
let upperCount = rangeCount - lowerCount
|
||||
let upperBound = lowerBound + rangeCount
|
||||
let endOfLower = lowerBound + lowerCount
|
||||
|
||||
try withUnsafeTemporaryAllocation(
|
||||
of: Element.self, capacity: Swift.min(lowerCount, upperCount)
|
||||
) { tempBuffer in
|
||||
if lowerCount < upperCount {
|
||||
// Merge into lower section from start of tempBuffer and upper section,
|
||||
// prioritizing tempBuffer values
|
||||
|
||||
// Move elements from lower section to temporary buffer
|
||||
_ = tempBuffer.moveInitialize(
|
||||
fromContentsOf: selfBuffer[lowerBound..<endOfLower])
|
||||
|
||||
var firstUninitialized = selfBuffer.baseAddress! + lowerBound
|
||||
var tempSource = tempBuffer.baseAddress!
|
||||
let tempUpper = tempSource + tempBuffer.count
|
||||
var selfSource = selfBuffer.baseAddress! + endOfLower
|
||||
let selfUpper = selfBuffer.baseAddress! + upperBound
|
||||
|
||||
func finalize() {
|
||||
if tempSource < tempUpper {
|
||||
firstUninitialized.moveInitialize(
|
||||
from: tempSource,
|
||||
count: tempUpper - tempSource)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
while tempSource < tempUpper && selfSource < selfUpper {
|
||||
if try areInAscendingOrder(selfSource.pointee, tempSource.pointee) {
|
||||
firstUninitialized.moveInitialize(from: selfSource, count: 1)
|
||||
selfSource += 1
|
||||
} else {
|
||||
firstUninitialized.moveInitialize(from: tempSource, count: 1)
|
||||
tempSource += 1
|
||||
}
|
||||
firstUninitialized += 1
|
||||
}
|
||||
} catch {
|
||||
finalize()
|
||||
throw error
|
||||
}
|
||||
|
||||
finalize()
|
||||
} else {
|
||||
// Merge (backwards) into upper section from end of tempBuffer and lower,
|
||||
// prioritizing tempBuffer values
|
||||
_ = tempBuffer.moveInitialize(
|
||||
fromContentsOf: selfBuffer[endOfLower..<upperBound])
|
||||
|
||||
var lastUninitialized = selfBuffer.baseAddress! + upperBound - 1
|
||||
var tempSource = (tempBuffer.baseAddress! + tempBuffer.count) - 1
|
||||
let tempLowerBound = tempBuffer.baseAddress!
|
||||
var selfSource = (selfBuffer.baseAddress! + endOfLower) - 1
|
||||
let selfLowerBound = selfBuffer.baseAddress! + lowerBound
|
||||
|
||||
while tempSource >= tempLowerBound && selfSource >= selfLowerBound {
|
||||
// FIXME: Figure out throwing situation
|
||||
if try !areInAscendingOrder(tempSource.pointee, selfSource.pointee) {
|
||||
lastUninitialized.moveInitialize(from: tempSource, count: 1)
|
||||
if tempSource == tempLowerBound {
|
||||
break
|
||||
}
|
||||
tempSource -= 1
|
||||
assert(tempSource >= tempLowerBound)
|
||||
} else {
|
||||
lastUninitialized.moveInitialize(from: selfSource, count: 1)
|
||||
if selfSource == selfLowerBound {
|
||||
// Done moving from the lower section, but there could still
|
||||
// be elements in the temp buffer.
|
||||
|
||||
// Note: `tempSource` points to the last element in the temp
|
||||
// buffer, not the "past the end" position, hence the +1 here:
|
||||
let tempCount = (tempSource + 1) - tempLowerBound
|
||||
selfLowerBound.moveInitialize(from: tempLowerBound, count: tempCount)
|
||||
break
|
||||
}
|
||||
selfSource -= 1
|
||||
assert(selfSource >= selfLowerBound)
|
||||
}
|
||||
lastUninitialized -= 1
|
||||
assert(lastUninitialized >= selfLowerBound)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if result == nil {
|
||||
try mergeInPlace(subrange: subrange, at: middle, by: areInAscendingOrder)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension MutableCollection where Self: BidirectionalCollection, Element: Comparable {
|
||||
public mutating func merge(at middle: Index) {
|
||||
merge(at: middle, by: <)
|
||||
}
|
||||
|
||||
public mutating func merge(subrange: Range<Index>, at middle: Index) {
|
||||
merge(subrange: subrange, at: middle, by: <)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// mergeInPlace(at:by:) / mergeInPlace(subrange:at:by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension MutableCollection where Self: BidirectionalCollection {
|
||||
public mutating func mergeInPlace(
|
||||
at middle: Index,
|
||||
by areInAscendingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows {
|
||||
try mergeInPlace(subrange: startIndex..<endIndex, at: middle, by: areInAscendingOrder)
|
||||
}
|
||||
|
||||
public mutating func mergeInPlace(
|
||||
subrange: Range<Index>,
|
||||
at middle: Index,
|
||||
by areInAscendingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows {
|
||||
// If either side of `middle` is empty, there's no work to do.
|
||||
if subrange.lowerBound == middle || middle == subrange.upperBound {
|
||||
return
|
||||
}
|
||||
|
||||
let lowerCount = distance(from: subrange.lowerBound, to: middle)
|
||||
let upperCount = distance(from: middle, to: subrange.upperBound)
|
||||
// FIXME: Insertion sort for small counts?
|
||||
guard lowerCount + upperCount > 2 else {
|
||||
if try areInAscendingOrder(self[middle], self[subrange.lowerBound]) {
|
||||
swapAt(subrange.lowerBound, middle)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let lowerPivot: Index
|
||||
let upperPivot: Index
|
||||
|
||||
if lowerCount < upperCount {
|
||||
// a a b b c c d e f|a b b b c d d d e e e e e f f
|
||||
// ^ ^
|
||||
// lowerPivot upperPivot
|
||||
// (lower pivot must be strictly greater than element at upper)
|
||||
// after rotation:
|
||||
// a a b b c c d|a b b b c d d/e f|d e e e e e f f
|
||||
// ^
|
||||
// newMiddle
|
||||
upperPivot = index(middle, offsetBy: upperCount / 2)
|
||||
// FIXME: Binary search instead of linear? Require random access?
|
||||
lowerPivot = try self[subrange.lowerBound..<middle].startOfSuffix(
|
||||
while: { try areInAscendingOrder(self[upperPivot], $0) })
|
||||
} else {
|
||||
// a b b b c d d d e e e e e f f|a a b b c c d e f
|
||||
// ^ ^
|
||||
// lowerPivot upperPivot
|
||||
// (upper pivot must be first element equal or greater than lower)
|
||||
// after rotation:
|
||||
// a b b b c d|a a b b c c/d d e e e e e f f|d e f
|
||||
// ^
|
||||
// newMiddle
|
||||
lowerPivot = index(subrange.lowerBound, offsetBy: lowerCount / 2)
|
||||
// FIXME: Binary search instead of linear? Require random access?
|
||||
upperPivot = try self[middle..<subrange.upperBound].endOfPrefix(
|
||||
while: { try areInAscendingOrder($0, self[lowerPivot]) })
|
||||
}
|
||||
|
||||
let newMiddle = self.rotate(subrange: lowerPivot..<upperPivot, toStartAt: middle)
|
||||
try self.mergeInPlace(
|
||||
subrange: subrange.lowerBound..<newMiddle,
|
||||
at: lowerPivot,
|
||||
by: areInAscendingOrder)
|
||||
try self.mergeInPlace(
|
||||
subrange: newMiddle..<subrange.upperBound,
|
||||
at: upperPivot,
|
||||
by: areInAscendingOrder)
|
||||
}
|
||||
}
|
||||
|
||||
extension MutableCollection where Self: BidirectionalCollection, Element: Comparable {
|
||||
public mutating func mergeInPlace(at middle: Index) {
|
||||
mergeInPlace(at: middle, by: <)
|
||||
}
|
||||
|
||||
public mutating func mergeInPlace(
|
||||
subrange: Range<Index>,
|
||||
at middle: Index
|
||||
) {
|
||||
mergeInPlace(subrange: subrange, at: middle, by: <)
|
||||
}
|
||||
}
|
||||
@@ -28,11 +28,9 @@ extension Sequence {
|
||||
while let e = iterator.next() {
|
||||
// To be part of `result`, `e` must be strictly less than `result.last`.
|
||||
guard try areInIncreasingOrder(e, result.last!) else { continue }
|
||||
result.removeLast()
|
||||
let insertionIndex =
|
||||
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
|
||||
|
||||
assert(insertionIndex != result.endIndex)
|
||||
result.removeLast()
|
||||
result.insert(e, at: insertionIndex)
|
||||
}
|
||||
|
||||
@@ -127,7 +125,7 @@ extension Sequence {
|
||||
/// largest values:
|
||||
///
|
||||
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
/// let smallestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// let largestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// // [7, 8, 9]
|
||||
///
|
||||
/// If you need to sort a sequence but only need to access its largest
|
||||
@@ -199,7 +197,7 @@ extension Sequence where Element: Comparable {
|
||||
/// largest values:
|
||||
///
|
||||
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
/// let smallestThree = numbers.max(count: 3)
|
||||
/// let largestThree = numbers.max(count: 3)
|
||||
/// // [7, 8, 9]
|
||||
///
|
||||
/// If you need to sort a sequence but only need to access its largest
|
||||
@@ -282,7 +280,7 @@ extension Collection {
|
||||
/// largest values:
|
||||
///
|
||||
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
/// let smallestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// let largestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// // [7, 8, 9]
|
||||
///
|
||||
/// If you need to sort a collection but only need to access its largest
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Copyright (c) 2020-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
|
||||
@@ -168,8 +168,8 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection {
|
||||
/// Returns the index of the first element in the collection that matches
|
||||
/// the predicate.
|
||||
/// Returns the start index of the partition of a collection that matches
|
||||
/// the given predicate.
|
||||
///
|
||||
/// The collection must already be partitioned according to the predicate.
|
||||
/// That is, there should be an index `i` where for every element in
|
||||
@@ -179,7 +179,8 @@ extension Collection {
|
||||
/// - Parameter belongsInSecondPartition: A predicate that partitions the
|
||||
/// collection.
|
||||
/// - Returns: The index of the first element in the collection for which
|
||||
/// `predicate` returns `true`.
|
||||
/// `predicate` returns `true`, or `endIndex` if there are no elements
|
||||
/// for which `predicate` returns `true`.
|
||||
///
|
||||
/// - Complexity: O(log *n*), where *n* is the length of this collection if
|
||||
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
|
||||
@@ -204,3 +205,137 @@ extension Collection {
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// partitioned(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Returns two arrays containing, in order, the elements of the sequence that
|
||||
/// do and don’t satisfy the given predicate.
|
||||
///
|
||||
/// In this example, `partitioned(by:)` is used to separate the input based on
|
||||
/// whether a name is shorter than five characters:
|
||||
///
|
||||
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
||||
/// let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
||||
/// print(longNames)
|
||||
/// // Prints "["Vivien", "Marlon"]"
|
||||
/// print(shortNames)
|
||||
/// // Prints "["Kim", "Karl"]"
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the sequence as
|
||||
/// its argument and returns a Boolean value indicating whether the element
|
||||
/// should be included in the second returned array. Otherwise, the element
|
||||
/// will appear in the first returned array.
|
||||
///
|
||||
/// - Returns: Two arrays with all of the elements of the receiver. The
|
||||
/// first array contains all the elements that `predicate` didn’t allow, and
|
||||
/// the second array contains all the elements that `predicate` allowed.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func partitioned(
|
||||
by predicate: (Element) throws -> Bool
|
||||
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
|
||||
var lhs = [Element]()
|
||||
var rhs = [Element]()
|
||||
|
||||
for element in self {
|
||||
if try predicate(element) {
|
||||
rhs.append(element)
|
||||
} else {
|
||||
lhs.append(element)
|
||||
}
|
||||
}
|
||||
|
||||
return (lhs, rhs)
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
/// Returns two arrays containing, in order, the elements of the collection
|
||||
/// that do and don’t satisfy the given predicate.
|
||||
///
|
||||
/// In this example, `partitioned(by:)` is used to separate the input based on
|
||||
/// whether a name is shorter than five characters.
|
||||
///
|
||||
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
||||
/// let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
||||
/// print(longNames)
|
||||
/// // Prints "["Vivien", "Marlon"]"
|
||||
/// print(shortNames)
|
||||
/// // Prints "["Kim", "Karl"]"
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the collection
|
||||
/// as its argument and returns a Boolean value indicating whether the element
|
||||
/// should be included in the second returned array. Otherwise, the element
|
||||
/// will appear in the first returned array.
|
||||
///
|
||||
/// - Returns: Two arrays with all of the elements of the receiver. The
|
||||
/// first array contains all the elements that `predicate` didn’t allow, and
|
||||
/// the second array contains all the elements that `predicate` allowed.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func partitioned(
|
||||
by predicate: (Element) throws -> Bool
|
||||
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
|
||||
guard !self.isEmpty else {
|
||||
return ([], [])
|
||||
}
|
||||
|
||||
// Since collections have known sizes, we can allocate one array of size
|
||||
// `self.count`, then insert items at the beginning or end of that contiguous
|
||||
// block. This way, we don’t have to do any dynamic array resizing. Since we
|
||||
// insert the right elements on the right side in reverse order, we need to
|
||||
// reverse them back to the original order at the end.
|
||||
|
||||
let count = self.count
|
||||
|
||||
// Inside of the `initializer` closure, we set what the actual mid-point is.
|
||||
// We will use this to partition the single array into two.
|
||||
var midPoint: Int = 0
|
||||
|
||||
let elements = try [Element](
|
||||
unsafeUninitializedCapacity: count,
|
||||
initializingWith: { buffer, initializedCount in
|
||||
var lhs = buffer.baseAddress!
|
||||
var rhs = lhs + buffer.count
|
||||
do {
|
||||
for element in self {
|
||||
if try predicate(element) {
|
||||
rhs -= 1
|
||||
rhs.initialize(to: element)
|
||||
} else {
|
||||
lhs.initialize(to: element)
|
||||
lhs += 1
|
||||
}
|
||||
}
|
||||
|
||||
precondition(lhs == rhs, """
|
||||
Collection's `count` differed from the number of elements iterated.
|
||||
"""
|
||||
)
|
||||
|
||||
let rhsIndex = rhs - buffer.baseAddress!
|
||||
buffer[rhsIndex...].reverse()
|
||||
initializedCount = buffer.count
|
||||
|
||||
midPoint = rhsIndex
|
||||
} catch {
|
||||
let lhsCount = lhs - buffer.baseAddress!
|
||||
let rhsCount = (buffer.baseAddress! + buffer.count) - rhs
|
||||
buffer.baseAddress!.deinitialize(count: lhsCount)
|
||||
rhs.deinitialize(count: rhsCount)
|
||||
throw error
|
||||
}
|
||||
})
|
||||
|
||||
let lhs = elements[..<midPoint]
|
||||
let rhs = elements[midPoint...]
|
||||
return (
|
||||
Array(lhs),
|
||||
Array(rhs)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
|
||||
fileprivate var COWLoggingArray_CopyCount = 0
|
||||
|
||||
public func AssertNoCopyOnWrite<T>(
|
||||
_ elements: some Sequence<T>,
|
||||
_ message: @autoclosure () -> String = "",
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line,
|
||||
_ body: (inout COWLoggingArray<T>) -> Void
|
||||
) {
|
||||
let copyCountBeforeBody = COWLoggingArray_CopyCount
|
||||
var loggingArray = COWLoggingArray(elements)
|
||||
body(&loggingArray)
|
||||
XCTAssertEqual(
|
||||
copyCountBeforeBody,
|
||||
COWLoggingArray_CopyCount,
|
||||
message(), file: file, line: line)
|
||||
}
|
||||
|
||||
public struct COWLoggingArray<Element> {
|
||||
var storage: Storage
|
||||
|
||||
class Storage {
|
||||
var buffer: UnsafeMutableBufferPointer<Element>
|
||||
var count: Int
|
||||
var capacity: Int {
|
||||
buffer.count
|
||||
}
|
||||
|
||||
init(capacity: Int) {
|
||||
self.buffer = .allocate(capacity: capacity)
|
||||
self.count = 0
|
||||
}
|
||||
|
||||
deinit {
|
||||
buffer.baseAddress!.deinitialize(count: count)
|
||||
buffer.deallocate()
|
||||
}
|
||||
|
||||
func cloned(capacity: Int? = nil) -> Storage {
|
||||
let newCapacity = Swift.max(capacity ?? self.capacity, self.capacity)
|
||||
let newStorage = Storage(capacity: newCapacity)
|
||||
newStorage.buffer.baseAddress!
|
||||
.initialize(from: buffer.baseAddress!, count: count)
|
||||
newStorage.count = count
|
||||
return newStorage
|
||||
}
|
||||
}
|
||||
|
||||
mutating func _makeUnique() {
|
||||
if !isKnownUniquelyReferenced(&storage) {
|
||||
storage = storage.cloned()
|
||||
COWLoggingArray_CopyCount += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension COWLoggingArray: RandomAccessCollection, RangeReplaceableCollection,
|
||||
MutableCollection, ExpressibleByArrayLiteral
|
||||
{
|
||||
public var count: Int { storage.count }
|
||||
public var startIndex: Int { 0 }
|
||||
public var endIndex: Int { count }
|
||||
|
||||
public subscript(i: Int) -> Element {
|
||||
get {
|
||||
storage.buffer[i]
|
||||
}
|
||||
set {
|
||||
_makeUnique()
|
||||
storage.buffer[i] = newValue
|
||||
}
|
||||
}
|
||||
|
||||
public init() {
|
||||
storage = Storage(capacity: 10)
|
||||
}
|
||||
|
||||
public mutating func reserveCapacity(_ n: Int) {
|
||||
if !isKnownUniquelyReferenced(&storage) {
|
||||
COWLoggingArray_CopyCount += 1
|
||||
storage = storage.cloned(capacity: n)
|
||||
} else if count < n {
|
||||
storage = storage.cloned(capacity: n)
|
||||
}
|
||||
}
|
||||
|
||||
public mutating func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C)
|
||||
where C : Collection, Element == C.Element
|
||||
{
|
||||
_makeUnique()
|
||||
let newCount = (count - subrange.count) + newElements.count
|
||||
if newCount > storage.capacity {
|
||||
storage = storage.cloned(capacity: newCount)
|
||||
}
|
||||
|
||||
let startOfSubrange = storage.buffer.baseAddress! + subrange.lowerBound
|
||||
let endOfSubrange = startOfSubrange + subrange.count
|
||||
let endOfNewElements = startOfSubrange + newElements.count
|
||||
let countAfterSubrange = count - subrange.upperBound
|
||||
|
||||
// clear out old elements
|
||||
startOfSubrange.deinitialize(count: subrange.count)
|
||||
|
||||
// move elements above subrange
|
||||
endOfNewElements.moveInitialize(from: endOfSubrange, count: countAfterSubrange)
|
||||
|
||||
// assign new elements
|
||||
for (pointer, element) in zip(startOfSubrange..., newElements) {
|
||||
pointer.initialize(to: element)
|
||||
}
|
||||
|
||||
// update count
|
||||
storage.count = newCount
|
||||
}
|
||||
|
||||
public init(arrayLiteral elements: Element...) {
|
||||
storage = Storage(capacity: elements.count)
|
||||
replaceSubrange(0..<0, with: elements)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
|
||||
|
||||
final class MergeTests: XCTestCase {
|
||||
func _createInput(seed: UInt64, count: Int) -> (input: [Int], pivot: Int) {
|
||||
var rng = SplitMix64(seed: seed)
|
||||
// Create array of numbers with two sorted partitions
|
||||
var numbers = (1...count).map { _ in Int.random(in: 1...10, using: &rng) }
|
||||
let pivot = Int.random(in: 0...numbers.count, using: &rng)
|
||||
numbers[..<pivot].sort()
|
||||
numbers[pivot...].sort()
|
||||
|
||||
return (numbers, pivot)
|
||||
}
|
||||
|
||||
func _runMergeTest(_ input: [Int], pivot: Int) {
|
||||
var numbers = input
|
||||
|
||||
// Various copies for testing different merge strategies
|
||||
var inPlace = numbers
|
||||
var partial = numbers
|
||||
var partialInPlace = numbers
|
||||
var positional = Array(numbers.enumerated())
|
||||
var positionalInPlace = positional
|
||||
|
||||
// Merge with extra storage & in-place, verify equal
|
||||
numbers.merge(at: pivot)
|
||||
XCTAssertTrue(numbers.isSorted())
|
||||
inPlace.mergeInPlace(at: pivot)
|
||||
XCTAssertEqualSequences(numbers, inPlace)
|
||||
|
||||
// Merge subsequences with extra storage & in-place, verify expected
|
||||
let subrange = min(pivot, 5) ..< max(pivot, partial.count - 5)
|
||||
partial.merge(subrange: subrange, at: pivot, by: <)
|
||||
XCTAssertTrue(partial[subrange].isSorted(by: <))
|
||||
partialInPlace.mergeInPlace(subrange: subrange, at: pivot, by: <)
|
||||
XCTAssertEqualSequences(partial, partialInPlace)
|
||||
|
||||
// Check merge stability
|
||||
positional.merge(at: pivot, by: { $0.element < $1.element })
|
||||
XCTAssertTrue(positional.isSorted(by: { ($0.element, $0.offset) < ($1.element, $1.offset) }))
|
||||
XCTAssertEqualSequences(numbers, positional.map { $0.element })
|
||||
positionalInPlace.mergeInPlace(at: pivot, by: { $0.element < $1.element })
|
||||
XCTAssert(positional.elementsEqual(positionalInPlace, by: ==))
|
||||
}
|
||||
|
||||
func testMerge() {
|
||||
var empty: [Int] = []
|
||||
empty.merge(at: 0, by: <)
|
||||
empty.mergeInPlace(at: 0, by: <)
|
||||
|
||||
let range = 1...100
|
||||
var numbers = Array(range)
|
||||
for i in 0...numbers.count {
|
||||
numbers.merge(at: i, by: <)
|
||||
XCTAssertEqualSequences(numbers, range)
|
||||
numbers.mergeInPlace(at: i, by: <)
|
||||
XCTAssertEqualSequences(numbers, range)
|
||||
}
|
||||
|
||||
// Nonsense shouldn't crash or get stuck
|
||||
var nonsense = range.map { _ in Int.random(in: 1...10) }
|
||||
nonsense.merge(at: nonsense.count / 3, by: <)
|
||||
nonsense.mergeInPlace(at: nonsense.count / 3, by: <)
|
||||
}
|
||||
|
||||
func testFuzzMerge() {
|
||||
for _ in 0..<100 {
|
||||
let seed: UInt64 = UInt64.random(in: 0 ... .max)
|
||||
let (input, pivot) = _createInput(seed: seed, count: 300)
|
||||
_runMergeTest(input, pivot: pivot)
|
||||
}
|
||||
}
|
||||
|
||||
func testMergeCopyOnWrite() {
|
||||
var numbers = (1...100).shuffled()
|
||||
let pivot = 25
|
||||
numbers[..<pivot].sort()
|
||||
numbers[pivot...].sort()
|
||||
|
||||
AssertNoCopyOnWrite(numbers) { array in
|
||||
array.mergeInPlace(at: pivot, by: <)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,26 @@ final class PartitionTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testPartitioningIndexWithEmptyInput() {
|
||||
let input: [Int] = []
|
||||
|
||||
let a = input.partitioningIndex(where: { _ in return true })
|
||||
XCTAssertEqual(a, input.startIndex)
|
||||
|
||||
let b = input.partitioningIndex(where: { _ in return false })
|
||||
XCTAssertEqual(b, input.endIndex)
|
||||
}
|
||||
|
||||
func testPartitioningIndexWithOneEmptyPartition() {
|
||||
let input: Range<Int> = (0 ..< 10)
|
||||
|
||||
let a = input.partitioningIndex(where: { $0 > 10 })
|
||||
XCTAssertEqual(a, input.endIndex)
|
||||
|
||||
let b = input.partitioningIndex(where: { $0 >= 0 })
|
||||
XCTAssertEqual(b, input.startIndex)
|
||||
}
|
||||
|
||||
func testPartitionWithSubrangeBidirectionalCollection() {
|
||||
for length in 10...20 {
|
||||
let a = Array(0..<length)
|
||||
@@ -133,4 +153,40 @@ final class PartitionTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testPartitionedWithEmptyInput() {
|
||||
let input: [Int] = []
|
||||
|
||||
let s0 = input.partitioned(by: { _ in return true })
|
||||
|
||||
XCTAssertTrue(s0.0.isEmpty)
|
||||
XCTAssertTrue(s0.1.isEmpty)
|
||||
}
|
||||
|
||||
/// Test the example given in the `partitioned(by:)` documentation
|
||||
func testPartitionedExample() throws {
|
||||
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
||||
let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
||||
XCTAssertEqual(longNames, ["Vivien", "Marlon"])
|
||||
XCTAssertEqual(shortNames, ["Kim", "Karl"])
|
||||
}
|
||||
|
||||
func testPartitionedWithPredicate() throws {
|
||||
let s0 = ["A", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() })
|
||||
let s1 = ["a", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() })
|
||||
let s2 = ["a", "B", "c", "D"].partitioned(by: { $0 == $0.lowercased() })
|
||||
let s3 = ["a", "B", "c", "d"].partitioned(by: { $0 == $0.lowercased() })
|
||||
|
||||
XCTAssertEqual(s0.0, ["A", "B", "C", "D"])
|
||||
XCTAssertEqual(s0.1, [])
|
||||
|
||||
XCTAssertEqual(s1.0, ["B", "C", "D"])
|
||||
XCTAssertEqual(s1.1, ["a"])
|
||||
|
||||
XCTAssertEqual(s2.0, ["B", "D"])
|
||||
XCTAssertEqual(s2.1, ["a", "c"])
|
||||
|
||||
XCTAssertEqual(s3.0, ["B"])
|
||||
XCTAssertEqual(s3.1, ["a", "c", "d"])
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user