Compare commits

..
Author SHA1 Message Date
Nate Cook 32aee022ce Implements mutable merge algorithm
This change implements mutable merge algorithms, both in place and
using a temporary buffer. The temporary buffer is only used if the
mutable collection supports accessing its storage as a contiguous
unsafe buffer; if not, the in-place merge is used instead.
2023-07-13 15:17:07 -05:00
27 changed files with 544 additions and 932 deletions

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
version: 1
builder:
configs:
- documentation_targets: [Algorithms]
+2 -51
View File
@@ -12,49 +12,6 @@ This project follows semantic versioning.
---
## [1.1.0] - 2023-08-24
### 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
@@ -312,8 +269,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.1.0...HEAD
[1.1.0]: https://github.com/apple/swift-algorithms/compare/1.0.0...1.1.0
[Unreleased]: https://github.com/apple/swift-algorithms/compare/1.0.0...HEAD
[1.0.0]: https://github.com/apple/swift-algorithms/compare/0.2.1...1.0.0
[0.2.1]: https://github.com/apple/swift-algorithms/compare/0.2.0...0.2.1
[0.2.0]: https://github.com/apple/swift-algorithms/compare/0.1.1...0.2.0
@@ -343,7 +299,6 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
[#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
@@ -352,7 +307,6 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
[#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
<!-- Link references for contributors -->
@@ -363,13 +317,11 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
[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
[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
[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
[iainsmith]: https://github.com/apple/swift-algorithms/commits?author=iainsmith
[iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7
[karwa]: https://github.com/apple/swift-algorithms/commits?author=karwa
[kylemacomber]: https://github.com/apple/swift-algorithms/commits?author=kylemacomber
@@ -381,7 +333,6 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
[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
[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
+39 -56
View File
@@ -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]
@@ -31,10 +31,11 @@ let chunks = names.chunked(on: \.first!)
// [("D", ["David"]), ("K", ["Kyle", "Karoy"]), ("N", ["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:)` 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"]
@@ -45,26 +46,11 @@ 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]
```
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 results in a collection equivalent
to the original.
Joining the result of a chunking method call recreates the original collection.
```swift
c.elementsEqual(c.chunked(...).joined())
@@ -75,45 +61,42 @@ c.elementsEqual(c.chunked(...).joined())
## 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 three methods are added as extension to `Collection`. `chunked(by:)` and
`chunked(on:)` are eager by default, both with a matching version that return a
lazy wrapper added to `LazySequenceProtocol`.
```swift
extension Collection {
public func chunked(
by belongInSameGroup: (Element, Element) -> Bool
) -> [SubSequence]
public func chunked(
by belongInSameGroup: (Element, Element) -> Bool
) -> [SubSequence]
public func chunked<Subject: Equatable>(
public func chunked<Subject: Equatable>(
on projection: (Element) -> Subject
) -> [SubSequence]
public func chunks(ofCount count: Int) -> ChunkedByCount<Self>
public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection<Self>
) -> [(Subject, SubSequence)]
public func chunks(ofCount count: Int) -> ChunksOfCountCollection<Self>
}
extension LazyCollectionProtocol {
public func chunked(
by belongInSameGroup: @escaping (Element, Element) -> Bool
) -> ChunkedByCollection<Elements>
extension LazySequenceProtocol where Self: Collection, Elements: Collection {
public func chunked(
by belongInSameGroup: @escaping (Element, Element) -> Bool
) -> ChunkedByCollection<Elements, Element>
public func chunked<Subject: Equatable>(
on projection: @escaping (Element) -> Subject
) -> ChunkedOnCollection<Elements, Subject>
public func chunked<Subject: Equatable>(
on projection: @escaping (Element) -> Subject
) -> ChunkedOnCollection<Elements, Subject>
}
```
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 `ChunkedByCollection`, `ChunkedOnCollection`, and `ChunksOfCountCollection`
types are bidirectional when the wrapped collection is bidirectional.
`ChunksOfCountCollection` also conforms to `LazySequenceProtocol` when the base
collection conforms.
### 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
@@ -137,5 +120,5 @@ into potentially overlapping subsequences.
**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.
+1 -1
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.4
// swift-tools-version:5.1
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
+2 -13
View File
@@ -10,8 +10,7 @@
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a sequence of overlapping adjacent pairs of the elements of this
/// 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
@@ -25,11 +24,6 @@ extension Sequence {
/// // 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)
@@ -37,7 +31,7 @@ extension Sequence {
}
extension Collection {
/// Returns a collection of overlapping adjacent pairs of the elements of this
/// A collection of adjacent pairs of elements built from an underlying
/// collection.
///
/// In an `AdjacentPairsCollection`, the elements of the *i*th pair are the
@@ -52,11 +46,6 @@ extension Collection {
/// // 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)
+15 -302
View File
@@ -198,210 +198,6 @@ extension ChunkedOnCollection: BidirectionalCollection
extension ChunkedOnCollection: LazyCollectionProtocol {}
/// A collection wrapper that evenly breaks a collection into a given number of
/// chunks.
public struct EvenlyChunkedCollection<Base: Collection> {
/// The base collection.
@usableFromInline
internal let base: Base
/// The number of equal chunks the base collection is divided into.
@usableFromInline
internal let numberOfChunks: Int
/// The count of the base collection.
@usableFromInline
internal let baseCount: Int
/// The upper bound of the first chunk.
@usableFromInline
internal var firstUpperBound: Base.Index
@inlinable
internal init(base: Base, numberOfChunks: Int) {
self.base = base
self.numberOfChunks = numberOfChunks
self.baseCount = base.count
self.firstUpperBound = base.startIndex
if numberOfChunks > 0 {
firstUpperBound = endOfChunk(startingAt: base.startIndex, offset: 0)
}
}
}
extension EvenlyChunkedCollection {
/// Returns the number of chunks with size `smallChunkSize + 1` at the start
/// of this collection.
@inlinable
internal var numberOfLargeChunks: Int {
baseCount % numberOfChunks
}
/// Returns the size of a chunk at a given offset.
@inlinable
internal func sizeOfChunk(offset: Int) -> Int {
let isLargeChunk = offset < numberOfLargeChunks
return baseCount / numberOfChunks + (isLargeChunk ? 1 : 0)
}
/// Returns the index in the base collection of the end of the chunk starting
/// at the given index.
@inlinable
internal func endOfChunk(startingAt start: Base.Index, offset: Int) -> Base.Index {
base.index(start, offsetBy: sizeOfChunk(offset: offset))
}
/// Returns the index in the base collection of the start of the chunk ending
/// at the given index.
@inlinable
internal func startOfChunk(endingAt end: Base.Index, offset: Int) -> Base.Index {
base.index(end, offsetBy: -sizeOfChunk(offset: offset))
}
/// Returns the index that corresponds to the chunk that starts at the given
/// base index.
@inlinable
internal func indexOfChunk(startingAt start: Base.Index, offset: Int) -> Index {
guard offset != numberOfChunks else { return endIndex }
let end = endOfChunk(startingAt: start, offset: offset)
return Index(start..<end, offset: offset)
}
/// Returns the index that corresponds to the chunk that ends at the given
/// base index.
@inlinable
internal func indexOfChunk(endingAt end: Base.Index, offset: Int) -> Index {
let start = startOfChunk(endingAt: end, offset: offset)
return Index(start..<end, offset: offset)
}
}
extension EvenlyChunkedCollection: Collection {
public struct Index: Comparable {
/// The range corresponding to the chunk at this position.
@usableFromInline
internal var baseRange: Range<Base.Index>
/// The offset corresponding to the chunk at this position. The first chunk
/// has offset `0` and all other chunks have an offset `1` greater than the
/// previous.
@usableFromInline
internal var offset: Int
@inlinable
internal init(_ baseRange: Range<Base.Index>, offset: Int) {
self.baseRange = baseRange
self.offset = offset
}
@inlinable
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.offset == rhs.offset
}
@inlinable
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.offset < rhs.offset
}
}
public typealias Element = Base.SubSequence
@inlinable
public var startIndex: Index {
Index(base.startIndex..<firstUpperBound, offset: 0)
}
@inlinable
public var endIndex: Index {
Index(base.endIndex..<base.endIndex, offset: numberOfChunks)
}
@inlinable
public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance past endIndex")
let start = i.baseRange.upperBound
return indexOfChunk(startingAt: start, offset: i.offset + 1)
}
@inlinable
public subscript(position: Index) -> Element {
precondition(position != endIndex)
return base[position.baseRange]
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
/// Returns the base distance between two `EvenChunksCollection` indices
/// from the end of one to the start of the other, when given their offsets.
func baseDistance(from offsetA: Int, to offsetB: Int) -> Int {
let smallChunkSize = baseCount / numberOfChunks
let numberOfChunks = (offsetB - offsetA) - 1
let largeChunksEnd = Swift.min(self.numberOfLargeChunks, offsetB)
let largeChunksStart = Swift.min(self.numberOfLargeChunks, offsetA + 1)
let numberOfLargeChunks = largeChunksEnd - largeChunksStart
return smallChunkSize * numberOfChunks + numberOfLargeChunks
}
if distance == 0 {
return i
} else if distance > 0 {
let offset = i.offset + distance
let baseOffset = baseDistance(from: i.offset, to: offset)
let start = base.index(i.baseRange.upperBound, offsetBy: baseOffset)
return indexOfChunk(startingAt: start, offset: offset)
} else {
let offset = i.offset + distance
let baseOffset = baseDistance(from: offset, to: i.offset)
let end = base.index(i.baseRange.lowerBound, offsetBy: -baseOffset)
return indexOfChunk(endingAt: end, offset: offset)
}
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? {
if distance >= 0 {
if (0..<distance).contains(self.distance(from: i, to: limit)) {
return nil
}
} else {
if (0..<(-distance)).contains(self.distance(from: limit, to: i)) {
return nil
}
}
return index(i, offsetBy: distance)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
end.offset - start.offset
}
}
extension EvenlyChunkedCollection.Index: Hashable where Base.Index: Hashable {}
extension EvenlyChunkedCollection: BidirectionalCollection
where Base: BidirectionalCollection
{
@inlinable
public func index(before i: Index) -> Index {
precondition(i != startIndex, "Can't advance before startIndex")
return indexOfChunk(endingAt: i.baseRange.lowerBound, offset: i.offset - 1)
}
}
extension EvenlyChunkedCollection: RandomAccessCollection
where Base: RandomAccessCollection {}
extension EvenlyChunkedCollection: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension EvenlyChunkedCollection: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
//===----------------------------------------------------------------------===//
// lazy.chunked(by:) / lazy.chunked(on:)
//===----------------------------------------------------------------------===//
@@ -410,9 +206,6 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
/// Returns a lazy collection of subsequences of this collection, chunked by
/// the given predicate.
///
/// - Parameter belongInSameGroup: A closure that takes two adjacent elements
/// of the sequence and returns whether or not they belong in the same group.
///
/// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable
public func chunked(
@@ -425,11 +218,7 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
}
/// Returns a lazy collection of subsequences of this collection, chunked by
/// grouping elements that project to equal values.
///
/// - Parameter projection: A closure that takes an element in the sequence
/// and returns an `Equatable` value that can be used to determine if adjacent
/// elements belong in the same group.
/// grouping elements that project to the same value.
///
/// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable
@@ -450,10 +239,6 @@ extension Collection {
/// Returns a collection of subsequences of this collection, chunked by the
/// given predicate.
///
/// - Parameter belongInSameGroup: A closure that takes two adjacent elements
/// of the collection and returns whether or not they belong in the same
/// group.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable
public func chunked(
@@ -481,11 +266,7 @@ extension Collection {
}
/// Returns a collection of subsequences of this collection, chunked by
/// grouping elements that project to equal values.
///
/// - Parameter projection: A closure that takes an element in the collection
/// and returns an `Equatable` value that can be used to determine if adjacent
/// elements belong in the same group.
/// grouping elements that project to the same value.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable
@@ -777,37 +558,22 @@ extension ChunksOfCountCollection {
}
extension Collection {
/// Returns a collection of subsequences, each with up to the specified
/// length.
/// Returns a `ChunksOfCountCollection<Self>` view presenting the elements in
/// chunks with count of the given count parameter.
///
/// If the number of elements in the collection is evenly divided by `count`,
/// then every chunk will have a length equal to `count`. Otherwise, every
/// chunk but the last will have a length equal to `count`, with the
/// remaining elements in the last chunk.
/// - 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.
///
/// let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
/// for chunk in numbers.chunks(ofCount: 5) {
/// print(chunk)
/// }
/// // [1, 2, 3, 4, 5]
/// // [6, 7, 8, 9, 10]
/// let c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
/// print(c.chunks(ofCount: 5).map(Array.init))
/// // [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
///
/// for chunk in numbers.chunks(ofCount: 3) {
/// print(chunk)
/// }
/// // [1, 2, 3]
/// // [4, 5, 5]
/// // [7, 8, 9]
/// // [10]
///
/// - Parameter count: The desired size of each chunk.
/// - Returns: A collection of consescutive, non-overlapping subseqeunces of
/// this collection, where each subsequence (except possibly the last) has
/// the length `count`.
///
/// - Complexity: O(1) if the collection conforms to `RandomAccessCollection`;
/// otherwise, O(*k*), where *k* is equal to `count`.
/// print(c.chunks(ofCount: 3).map(Array.init))
/// // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
///
/// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable
public func chunks(ofCount count: Int) -> ChunksOfCountCollection<Self> {
precondition(count > 0, "Cannot chunk with count <= 0!")
@@ -817,58 +583,5 @@ extension Collection {
extension ChunksOfCountCollection.Index: Hashable where Base.Index: Hashable {}
extension ChunksOfCountCollection: LazySequenceProtocol
extension ChunksOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {}
extension ChunksOfCountCollection: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
//===----------------------------------------------------------------------===//
// evenlyChunked(in:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns a collection of evenly divided consecutive subsequences of this
/// collection.
///
/// This method divides the collection into a given number of evenly sized
/// chunks. If the length of the collection is not divisible by `count`, the
/// chunks at the start will be longer than the chunks at the end, like in
/// this example:
///
/// for chunk in "Hello, world!".evenlyChunked(in: 5) {
/// print(chunk)
/// }
/// // "Hel"
/// // "lo,"
/// // " wo"
/// // "rl"
/// // "d!"
///
/// If the number passed as `count` is greater than the number of elements in
/// the collection, the result will include one or more empty subsequences.
///
/// for chunk in "Hi!".evenlyChunked(in: 5) {
/// print(chunk)
/// }
/// // "H"
/// // "i"
/// // "!"
/// // ""
/// // ""
///
/// - Parameter count: The number of chunks to evenly divide this collection
/// into. If this collection is non-empty, `count` must be greater than
/// zero; otherwise, `count` may be zero or greater.
/// - Returns: A collection of `count` subsequences of this collection,
/// divided as evenly as possible.
///
/// - Complexity: O(1) if the collection conforms to `RandomAccessCollection`;
/// otherwise, O(*n*), where *n* is the length of the collection.
@inlinable
public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection<Self> {
precondition(count >= 0, "Can't divide into a negative number of chunks")
precondition(count > 0 || isEmpty, "Can't divide a non-empty collection into 0 chunks")
return EvenlyChunkedCollection(base: self, numberOfChunks: count)
}
}
+2 -2
View File
@@ -289,8 +289,8 @@ extension Collection {
/// - Parameter k: The number of elements to include in each 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.
/// 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.")
@@ -1,41 +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: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,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 Simulataneously
- ``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,27 +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:)``
+1 -5
View File
@@ -94,10 +94,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.
///
@@ -109,7 +105,7 @@ extension Collection {
/// }
/// }
///
/// - Returns: A collection of paired indices and elements of this collection.
/// Returns: A collection of paired indices and elements of this collection.
@inlinable
public func indexed() -> IndexedCollection<Self> {
IndexedCollection(base: self)
+230
View File
@@ -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: <)
}
}
+19
View File
@@ -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`
-----------------------------------------------------
""")
@@ -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)
}
}
+3 -33
View File
@@ -87,6 +87,9 @@ final class ChunkedTests: XCTestCase {
[1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }),
[[1, 2, 3, 4], [6, 7, 8, 9]])
print(Array([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 })))
print(Array([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 }).reversed()))
XCTAssertEqualSequences(
[1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }).reversed(),
[[6, 7, 8, 9], [1, 2, 3, 4]])
@@ -170,37 +173,4 @@ final class ChunkedTests: XCTestCase {
expectedCount: range.count / i + (range.count % i).signum())
}
}
func testEvenChunks() {
XCTAssertEqualSequences(
(0..<10).evenlyChunked(in: 4),
[0..<3, 3..<6, 6..<8, 8..<10])
XCTAssertEqualSequences(
(0..<3).evenlyChunked(in: 5),
[0..<1, 1..<2, 2..<3, 3..<3, 3..<3])
XCTAssertEqualSequences(
"".evenlyChunked(in: 0),
[])
XCTAssertEqualSequences(
"".evenlyChunked(in: 1),
[""])
}
func testEvenChunksIndexTraversals() {
let validator = IndexValidator<EvenlyChunkedCollection<Range<Int>>>()
[
(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),
].forEach { validator.validate($0) }
}
}
@@ -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: <)
}
}
}