Compare commits

..
14 changed files with 1137 additions and 89 deletions

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
# SlidingWindows
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/SlidingWindows.swift) |
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/SlidingWindowsTests.swift)]
Break a collection into overlapping contiguous window subsequences where
elements are slices from the original collection.
The `slidingWindows(ofCount:)` method takes in a integer size and returns a collection
of subsequences.
```swift
let swift = "swift"
let windowed = swift.slidingWindows(ofCount: 2)
// windowed == [ "sw", "wi", "if", "ft" ]
```
## Detailed Design
The `slidingWindows(ofCount:)` is added as a method on an extension of `Collection`
```swift
extension Collection {
public func slidingWindows(ofCount count: Int) -> SlidingWindows<Self> {
SlidingWindows(base: self, size: count)
}
}
```
If a size larger than the collection length is specified, an empty collection is returned.
The first upper bound is computed eagerly because it determines if the collection
`startIndex` returns `endIndex`.
```swift
[1, 2, 3].slidingWindows(ofCount: 5).isEmpty // true
```
The resulting `SlidingWindows` type is a collection, with conditional conformance to the
`BidirectionalCollection`, and `RandomAccessCollection` when the base collection
conforms.
### Complexity
The call to `slidingWindows(ofCount: k)` is O(_1_) if the collection conforms to
`RandomAccessCollection`, otherwise O(_k_). Access to the next window is O(_1_).
### Naming
The type `SlidingWindows` takes its name from the algorithm, similarly the method takes
it's name from it too `slidingWindows(ofCount: k)`.
The label on the method `ofCount` was chosen to create a consistent feel to the API
available in swift-algorithms repository. Inspiration was taken from
`combinations(ofCount:)` and `permutations(ofCount:)`.
Previously the name `windows` was considered but was deemed to potentially create
ambiguity with the Windows operating system.
### Comparison with other languages
[rust](https://doc.rust-lang.org/std/slice/struct.Windows.html) has
`std::slice::Windows` which is a method available on slices. It has the same
semantics as described here.
+114
View File
@@ -0,0 +1,114 @@
# Trim
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Trim.swift) |
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/TrimTests.swift)]
Returns a `SubSequence` formed by discarding all elements at the start and end of the collection
which satisfy the given predicate.
This example uses `trimming(where:)` to get a substring without the white space at the beginning and end of the string.
```swift
let myString = " hello, world "
print(myString.trimming(where: \.isWhitespace)) // "hello, world"
let results = [2, 10, 11, 15, 20, 21, 100].trimming(where: { $0.isMultiple(of: 2) })
print(results) // [11, 15, 20, 21]
```
## Detailed Design
A new method is added to `BidirectionalCollection`:
```swift
extension BidirectionalCollection {
public func trimming(where predicate: (Element) throws -> Bool) rethrows -> SubSequence
}
```
This method requires `BidirectionalCollection` for an efficient implementation which visits as few elements as possible.
A less-efficient implementation is _possible_ for any `Collection`, which would involve always traversing the
entire collection. This implementation is not provided, as it would mean developers of generic algorithms who forget
to add the `BidirectionalCollection` constraint will receive that inefficient implementation:
```swift
func myAlgorithm<Input>(input: Input) where Input: Collection {
let trimmedInput = input.trimming(where: { ... }) // Uses least-efficient implementation.
}
func myAlgorithm2<Input>(input: Input) where Input: BidirectionalCollection {
let trimmedInput = input.trimming(where: { ... }) // Uses most-efficient implementation.
}
```
Swift provides the `BidirectionalCollection` protocol for marking types which support reverse traversal,
and generic types and algorithms which want to make use of that should add it to their constraints.
### Complexity
Calling this method is O(_n_).
### Naming
The name `trim` has precedent in other programming languages. Another popular alternative might be `strip`.
| Example usage | Languages |
|-|-|
| ''String''.Trim([''chars'']) | C#, VB.NET, Windows PowerShell |
| ''string''.strip(); | D |
| (.trim ''string'') | Clojure |
| ''sequence'' [ predicate? ] trim | Factor |
| (string-trim '(#\Space #\Tab #\Newline) ''string'') | Common Lisp |
| (string-trim ''string'') | Scheme |
| ''string''.trim() | Java, JavaScript (1.8.1+), Rust |
| Trim(''String'') | Pascal, QBasic, Visual Basic, Delphi |
| ''string''.strip() | Python |
| strings.Trim(''string'', ''chars'') | Go |
| LTRIM(RTRIM(''String'')) | Oracle SQL, T-SQL |
| string:strip(''string'' [,''option'', ''char'']) | Erlang |
| ''string''.strip or ''string''.lstrip or ''string''.rstrip | Ruby |
| trim(''string'') | PHP, Raku |
| [''string'' stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] | Objective-C/Cocoa |
| ''string'' withBlanksTrimmed ''string'' withoutSpaces ''string'' withoutSeparators | Smalltalk |
| string trim ''$string'' | Tcl |
| TRIM(''string'') or TRIM(ADJUSTL(''string'')) | Fortran |
| TRIM(''string'') | SQL |
| String.trim ''string'' | OCaml 4+ |
Note: This is an abbreviated list from Wikipedia. [Full table](https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(string_functions)#trim)
The standard library includes a variety of methods which perform similar operations:
- Firstly, there are `dropFirst(Int)` and `dropLast(Int)`. These return slices but do not support user-defined predicates.
If the collection's `count` is less than the number of elements to drop, they return an empty slice.
- Secondly, there is `drop(while:)`, which also returns a slice and is equivalent to a 'left-trim' (trimming from the head but not the tail).
If the entire collection is dropped, this method returns an empty slice.
- Thirdly, there are `removeFirst(Int)` and `removeLast(Int)` which do not return slices and actually mutate the collection.
If the collection's `count` is less than the number of elements to remove, this method triggers a runtime error.
- Lastly, there are the `popFirst()` and `popLast()` methods, which work like `removeFirst()` and `removeLast()`,
except they do not trigger a runtime error for empty collections.
The closest neighbours to this function would be the `drop` family of methods. Unfortunately, unlike `dropFirst(Int)`,
the name `drop(while:)` does not specify which end(s) of the collection it operates on. Moreover, one could easily
mistake code such as:
```swift
let result = myString.drop(while: \.isWhitespace)
```
With a lazy filter that drops _all_ whitespace characters regardless of where they are in the string.
Besides that, the root `trim` leads to clearer, more conscise code, which is more aligned with other programming
languages:
```swift
// Does `result` contain the input, trimmed of certain elements?
// Or does this code mutate `input` in-place and return the elements which were dropped?
let result = input.dropFromBothEnds(where: { ... })
// No such ambiguity here.
let result = input.trimming(where: { ... })
```
+1
View File
@@ -32,6 +32,7 @@ Read more about the package, and the intent behind it, in the [announcement on s
- [`chunked(by:)`, `chunked(on:)`](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.
- [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements.
- [`trimming(where:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start and end.
## Adding Swift Algorithms as a Dependency
+291
View File
@@ -0,0 +1,291 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
public struct SubSequenceFinder<Base: Collection, Other: Collection>
where Base.Element == Other.Element, Base.Element: Equatable
{
internal var base: Base
internal var other: Other
internal var firstRange: Range<Base.Index>?
internal var areEquivalent: (Base.Element, Base.Element) -> Bool
internal init(
base: Base,
other: Other,
by areEquivalent: @escaping (Base.Element, Base.Element) -> Bool)
{
self.base = base
self.other = other
self.areEquivalent = areEquivalent
self.firstRange = base.firstRange(of: other, by: areEquivalent)
}
}
extension SubSequenceFinder: Collection {
public struct Index: Comparable {
internal enum Representation: Comparable {
case match(Range<Base.Index>)
case end
public static func < (lhs: Representation, rhs: Representation) -> Bool {
switch (lhs, rhs) {
case (.match, .end):
return true
case (.end, _):
return false
case (.match(let lhs), .match(let rhs)):
return lhs.lowerBound < rhs.lowerBound
}
}
}
internal var base: Representation
internal static var end: Index {
Index(base: .end)
}
private init(base: Representation) {
self.base = base
}
internal init(_ range: Range<Base.Index>) {
self.base = .match(range)
}
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.base < rhs.base
}
}
public var startIndex: Index {
firstRange.map { Index($0) } ?? .end
}
public var endIndex: Index {
.end
}
public func index(after i: Index) -> Index {
guard case .match(let range) = i.base else {
preconditionFailure("Can't advance past endIndex")
}
let startingPoint = base.index(after: range.lowerBound)
return base[startingPoint...]
.firstRange(of: other)
.map { Index($0) } ?? .end
}
public subscript(position: Index) -> Range<Base.Index> {
guard case .match(let range) = position.base else {
preconditionFailure("Can't subscript with endIndex")
}
return range
}
}
extension SubSequenceFinder: BidirectionalCollection
where Base: BidirectionalCollection, Other: BidirectionalCollection
{
public func index(before i: Index) -> Index {
let endingPoint: Base.Index
switch i.base {
case .match(let range):
precondition(range != firstRange, "Can't move before startIndex")
endingPoint = base.index(before: range.upperBound)
case .end:
endingPoint = base.endIndex
}
return Index(base[..<endingPoint].lastRange(of: other)!)
}
}
// MARK: allRanges(of:by:) / allRanges(of:)
extension Collection {
public func allRanges<Other: Collection>(
of other: Other,
by areEquivalent: @escaping (Element, Element) -> Bool
)
-> SubSequenceFinder<Self, Other>
{
SubSequenceFinder(base: self, other: other, by: areEquivalent)
}
}
extension Collection where Element: Equatable {
public func allRanges<Other: Collection>(of other: Other) -> SubSequenceFinder<Self, Other>
where Element == Other.Element
{
allRanges(of: other, by: ==)
}
}
// MARK: - firstRange(of:by:) / firstRange(of:)
extension Collection {
public func firstRange<Other: Collection>(
of other: Other,
by areEquivalent: (Element, Element) throws -> Bool
) rethrows -> Range<Index>?
where Other.Element == Element
{
var searchStart = startIndex
guard let needleFirst = other.first else { return nil }
while let matchStart = try self[searchStart...]
.firstIndex(where: { try areEquivalent($0, needleFirst) })
{
var selfPos = index(after: matchStart)
var otherPos = other.index(after: other.startIndex)
while true {
if otherPos == other.endIndex {
return matchStart..<selfPos
}
if selfPos == self.endIndex {
return nil
}
if try !areEquivalent(self[selfPos], other[otherPos]) {
break
}
self.formIndex(after: &selfPos)
other.formIndex(after: &otherPos)
}
searchStart = self.index(after: matchStart)
}
return nil
}
}
extension Collection where Element: Equatable {
public func firstRange<Other: Collection>(of other: Other) -> Range<Index>?
where Element == Other.Element
{
firstRange(of: other, by: ==)
}
}
// MARK: - lastRange(of:by:) / lastRange(of:)
extension BidirectionalCollection where Element: Equatable {
public func lastRange<Other: BidirectionalCollection>(of other: Other) -> Range<Index>?
where Other.Element == Element
{
var searchEnd = endIndex
guard let needleLast = other.last else { return nil }
let otherLastIndex = other.index(before: other.endIndex)
while let matchEnd = self[..<searchEnd].lastIndex(of: needleLast) {
var selfPos = matchEnd
var otherPos = otherLastIndex
while true {
if otherPos == other.startIndex {
return selfPos..<index(after: matchEnd)
}
if selfPos == self.startIndex {
return nil
}
self.formIndex(before: &selfPos)
other.formIndex(before: &otherPos)
if self[selfPos] != other[otherPos] {
break
}
}
searchEnd = matchEnd
}
return nil
}
}
public struct SubSequenceFinderFromEnd<Base: BidirectionalCollection, Other: BidirectionalCollection>
where Base.Element == Other.Element, Base.Element: Equatable
{
internal var base: Base
internal var other: Other
internal var lastRange: Range<Base.Index>?
internal init(base: Base, other: Other, allowingOverlaps: Bool) {
self.base = base
self.other = other
self.lastRange = base.lastRange(of: other)
}
}
extension SubSequenceFinderFromEnd: Collection {
public struct Index: Comparable {
internal enum Representation: Comparable {
case match(Range<Base.Index>)
case end
public static func < (lhs: Representation, rhs: Representation) -> Bool {
switch (lhs, rhs) {
case (.match, .end):
return true
case (.end, _):
return false
case (.match(let lhs), .match(let rhs)):
return lhs.lowerBound > rhs.lowerBound
}
}
}
internal var base: Representation
internal static var end: Index {
Index(base: .end)
}
private init(base: Representation) {
self.base = base
}
internal init(_ range: Range<Base.Index>) {
self.base = .match(range)
}
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.base < rhs.base
}
}
public var startIndex: Index {
lastRange.map { Index($0) } ?? .end
}
public var endIndex: Index {
.end
}
public func index(after i: Index) -> Index {
guard case .match(let range) = i.base else {
preconditionFailure("Can't advance past endIndex")
}
return base[..<range.lowerBound]
.lastRange(of: other)
.map { Index($0) } ?? .end
}
public subscript(position: Index) -> Range<Base.Index> {
guard case .match(let range) = position.base else {
preconditionFailure("Can't subscript with endIndex")
}
return range
}
}
+112
View File
@@ -0,0 +1,112 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// slidingWindows(ofCount:)
//===----------------------------------------------------------------------===//
extension Collection {
/// A collection for all contiguous windows of length size, the
/// windows overlap.
///
/// - Complexity: O(*1*) if the collection conforms to
/// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`.
/// Access to the next window is O(*1*).
///
/// - Parameter count: The number of elements in each window subsequence.
///
/// - Returns: If the collection is shorter than `size` the resulting
/// SlidingWindows collection will be empty.
public func slidingWindows(ofCount count: Int) -> SlidingWindows<Self> {
SlidingWindows(base: self, size: count)
}
}
public struct SlidingWindows<Base: Collection> {
public let base: Base
public let size: Int
private var firstUpperBound: Base.Index?
init(base: Base, size: Int) {
precondition(size > 0, "SlidingWindows size must be greater than zero")
self.base = base
self.size = size
self.firstUpperBound = base.index(base.startIndex, offsetBy: size, limitedBy: base.endIndex)
}
}
extension SlidingWindows: Collection {
public struct Index: Comparable {
internal var lowerBound: Base.Index
internal var upperBound: Base.Index
public static func == (lhs: Index, rhs: Index) -> Bool {
lhs.lowerBound == rhs.lowerBound
}
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.lowerBound < rhs.lowerBound
}
}
public var startIndex: Index {
if let upperBound = firstUpperBound {
return Index(lowerBound: base.startIndex, upperBound: upperBound)
} else {
return endIndex
}
}
public var endIndex: Index {
Index(lowerBound: base.endIndex, upperBound: base.endIndex)
}
public subscript(index: Index) -> Base.SubSequence {
precondition(index.lowerBound != index.upperBound, "SlidingWindows index is out of range")
return base[index.lowerBound..<index.upperBound]
}
public func index(after index: Index) -> Index {
precondition(index < endIndex, "Advancing past end index")
guard index.upperBound < base.endIndex else { return endIndex }
return Index(
lowerBound: base.index(after: index.lowerBound),
upperBound: base.index(after: index.upperBound)
)
}
// TODO: Implement distance(from:to:), index(_:offsetBy:) and
// index(_:offsetBy:limitedBy:)
}
extension SlidingWindows: BidirectionalCollection where Base: BidirectionalCollection {
public func index(before index: Index) -> Index {
precondition(index > startIndex, "Incrementing past start index")
if index == endIndex {
return Index(
lowerBound: base.index(index.lowerBound, offsetBy: -size),
upperBound: index.upperBound
)
} else {
return Index(
lowerBound: base.index(before: index.lowerBound),
upperBound: base.index(before: index.upperBound)
)
}
}
}
extension SlidingWindows: RandomAccessCollection where Base: RandomAccessCollection {}
extension SlidingWindows: Equatable where Base: Equatable {}
extension SlidingWindows: Hashable where Base: Hashable, Base.Index: Hashable {}
extension SlidingWindows.Index: Hashable where Base.Index: Hashable {}
+50
View File
@@ -0,0 +1,50 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension BidirectionalCollection {
/// Returns a `SubSequence` formed by discarding all elements at the start and end of the collection
/// which satisfy the given predicate.
///
/// This example uses `trimming(where:)` to get a substring without the white space at the
/// beginning and end of the string:
///
/// ```
/// let myString = " hello, world "
/// print(myString.trimming(where: \.isWhitespace)) // "hello, world"
/// ```
///
/// - parameters:
/// - predicate: A closure which determines if the element should be omitted from the
/// resulting slice.
///
/// - complexity: `O(n)`, where `n` is the length of this collection.
///
@inlinable
public func trimming(
where predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
// Consume elements from the front.
let sliceStart = try firstIndex { try predicate($0) == false } ?? endIndex
// sliceEnd is the index _after_ the last index to match the predicate.
var sliceEnd = endIndex
while sliceStart != sliceEnd {
let idxBeforeSliceEnd = index(before: sliceEnd)
guard try predicate(self[idxBeforeSliceEnd]) else {
return self[sliceStart..<sliceEnd]
}
sliceEnd = idxBeforeSliceEnd
}
// Trimmed everything.
return self[Range(uncheckedBounds: (sliceStart, sliceStart))]
}
}
+29 -2
View File
@@ -15,7 +15,16 @@
extension Sequence where Element: Hashable {
/// Returns an array with only the unique elements of this sequence, in the
/// order of the first occurence of each unique element.
/// order of the first occurrence of each unique element.
///
/// let animals = ["dog", "pig", "cat", "ox", "dog", "cat"]
/// let uniqued = animals.uniqued()
/// print(uniqued)
/// // Prints '["dog", "pig", "cat", "ox"]'
///
/// - Returns: An array with only the unique elements of this sequence.
/// .
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func uniqued() -> [Element] {
uniqued(on: { $0 })
@@ -24,8 +33,26 @@ extension Sequence where Element: Hashable {
extension Sequence {
/// Returns an array with the unique elements of this sequence (as determined
/// by the given projection), in the order of the first occurence of each
/// by the given projection), in the order of the first occurrence of each
/// unique element.
///
/// This example finds the elements of the `animals` array with unique
/// first characters:
///
/// let animals = ["dog", "pig", "cat", "ox", "cow", "owl"]
/// let uniqued = animals.uniqued(on: {$0.first})
/// print(uniqued)
/// // Prints '["dog", "pig", "cat", "ox"]'
///
/// - Parameter projection: A closure that transforms an element into the
/// value to use for uniqueness. If `projection` returns the same value
/// for two different elements, the second element will be excluded
/// from the resulting array.
///
/// - Returns: An array with only the unique elements of this sequence, as
/// determined by the result of `projection` for each element.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func uniqued<Subject: Hashable>(
on projection: (Element) throws -> Subject
+11 -79
View File
@@ -13,14 +13,6 @@ import XCTest
@testable import Algorithms
final class ChainTests: XCTestCase {
// intentionally does not depend on `Chain.index(_:offsetBy:)` in order to
// avoid making assumptions about the code being tested
func index<A, B>(atOffset offset: Int, in chain: Chain2<A, B>) -> Chain2<A, B>.Index {
offset < chain.base1.count
? .init(first: chain.base1.index(chain.base1.startIndex, offsetBy: offset))
: .init(second: chain.base2.index(chain.base2.startIndex, offsetBy: offset - chain.base1.count))
}
func testChainSequences() {
let run = chain((1...).prefix(10), 20...)
XCTAssertEqualSequences(run.prefix(20), Array(1...10) + (20..<30))
@@ -43,62 +35,17 @@ final class ChainTests: XCTestCase {
XCTAssertEqualSequences(chain(s1.reversed(), s2), "JIHGFEDCBAklmnopqrstuv")
}
func testChainIndexOffsetBy() {
let s1 = "abcde"
let s2 = "VWXYZ"
let c = chain(s1, s2)
for (startOffset, endOffset) in product(0...c.count, 0...c.count) {
let start = index(atOffset: startOffset, in: c)
let end = index(atOffset: endOffset, in: c)
let distance = endOffset - startOffset
XCTAssertEqual(c.index(start, offsetBy: distance), end)
}
}
func testChainIndexOffsetByLimitedBy() {
let s1 = "abcd"
let s2 = "XYZ"
let c = chain(s1, s2)
for (startOffset, limitOffset) in product(0...c.count, 0...c.count) {
let start = index(atOffset: startOffset, in: c)
let limit = index(atOffset: limitOffset, in: c)
// verifies that the target index corresponding to each offset in `range`
// can or cannot be reached from `start` using
// `c.index(start, offsetBy: _, limitedBy: limit)`, depending on the
// value of `beyondLimit`
func checkTargetRange(_ range: ClosedRange<Int>, beyondLimit: Bool) {
for targetOffset in range {
let distance = targetOffset - startOffset
XCTAssertEqual(
c.index(start, offsetBy: distance, limitedBy: limit),
beyondLimit ? nil : index(atOffset: targetOffset, in: c))
}
}
// forward
if limit >= start {
// the limit has an effect
checkTargetRange(startOffset...limitOffset, beyondLimit: false)
checkTargetRange((limitOffset + 1)...(c.count + 1), beyondLimit: true)
} else {
// the limit has no effect
checkTargetRange(startOffset...c.count, beyondLimit: false)
}
// backward
if limit <= start {
// the limit has an effect
checkTargetRange(limitOffset...startOffset, beyondLimit: false)
checkTargetRange(-1...(limitOffset - 1), beyondLimit: true)
} else {
// the limit has no effect
checkTargetRange(0...startOffset, beyondLimit: false)
}
}
func testChainIndexTraversals() {
validateIndexTraversals(
chain("abcd", "XYZ"),
chain("abcd", ""),
chain("", "XYZ"),
chain("", ""),
indices: { chain in
chain.base1.indices.map { .init(first: $0) }
+ chain.base2.indices.map { .init(second: $0) }
+ [.init(second: chain.base2.endIndex)]
})
}
func testChainIndexOffsetAcrossBoundary() {
@@ -121,19 +68,4 @@ final class ChainTests: XCTestCase {
XCTAssertNil(j)
}
}
func testChainDistanceFromTo() {
let s1 = "abcde"
let s2 = "VWXYZ"
let c = chain(s1, s2)
XCTAssertEqual(c.count, s1.count + s2.count)
for (startOffset, endOffset) in product(0...c.count, 0...c.count) {
let start = index(atOffset: startOffset, in: c)
let end = index(atOffset: endOffset, in: c)
let distance = endOffset - startOffset
XCTAssertEqual(c.distance(from: start, to: end), distance)
}
}
}
@@ -0,0 +1,84 @@
//===----------------------------------------------------------------------===//
//
// 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
extension Collection {
fileprivate func range(at offsets: Range<Int>) -> Range<Index> {
let low = index(startIndex, offsetBy: offsets.lowerBound)
let high = index(low, offsetBy: offsets.count)
return low..<high
}
}
fileprivate let input = "abababaabaaba"
final class FindTests: XCTestCase {
func testFirstRangeOf() {
XCTAssertNil("".firstRange(of: "input"))
XCTAssertNil("".firstRange(of: ""))
XCTAssertNil(input.firstRange(of: ""))
XCTAssertEqual(input.firstRange(of: "ababa"), input.range(at: 0..<5))
XCTAssertEqual(input.firstRange(of: "baba"), input.range(at: 1..<5))
XCTAssertEqual(input.firstRange(of: "abaa"), input.range(at: 4..<8))
XCTAssertEqual(input.firstRange(of: "aabaaba"), input.range(at: 6..<13))
XCTAssertEqual(input.firstRange(of: input), input.range(at: 0..<13))
XCTAssertNil(input.firstRange(of: "aabaabaa"))
XCTAssertNil(input.firstRange(of: "abababab"))
XCTAssertEqual(input.dropFirst().firstRange(of: "ababa"), input.range(at: 2..<7))
XCTAssertEqual(input.dropFirst(5).firstRange(of: "abaa"), input.range(at: 7..<11))
XCTAssertNil(input.dropFirst(7).firstRange(of: "aabaaba"))
}
func testLastRangeOf() {
XCTAssertNil("".lastRange(of: "a"))
XCTAssertNil("".lastRange(of: ""))
XCTAssertNil(input.lastRange(of: ""))
XCTAssertEqual(input.lastRange(of: "ababa"), input.range(at: 2..<7))
XCTAssertEqual(input.lastRange(of: "baba"), input.range(at: 3..<7))
XCTAssertEqual(input.lastRange(of: "abaa"), input.range(at: 7..<11))
XCTAssertEqual(input.lastRange(of: "aabaaba"), input.range(at: 6..<13))
XCTAssertEqual(input.lastRange(of: input), input.range(at: 0..<13))
XCTAssertNil(input.lastRange(of: "aabaabaa"))
XCTAssertNil(input.lastRange(of: "abababab"))
XCTAssertEqual(input.dropLast(7).lastRange(of: "ababa"), input.range(at: 0..<5))
XCTAssertEqual(input.dropLast(3).lastRange(of: "abaa"), input.range(at: 4..<8))
XCTAssertNil(input.dropLast(6).lastRange(of: "abababaa"))
}
func testAllRangesOf() {
XCTAssertEqual("".allRanges(of: "abc").count, 0)
XCTAssertEqual("".allRanges(of: "").count, 0)
XCTAssertEqual(input.allRanges(of: "abc").count, 0)
XCTAssertEqual(input.allRanges(of: "").count, 0)
XCTAssertEqual(input.allRanges(of: "ab").count, 5)
XCTAssertEqual(input.allRanges(of: "ba").count, 5)
XCTAssertEqual(input.allRanges(of: "aba").count, 5)
XCTAssertEqualSequences(
input.allRanges(of: "ababa"),
[input.range(at: 0..<5), input.range(at: 2..<7)])
XCTAssertEqualSequences(
input.allRanges(of: "aaba"),
[input.range(at: 6..<10), input.range(at: 9..<13)])
XCTAssertEqualSequences(
input.allRanges(of: "aaba").reversed(),
[input.range(at: 9..<13), input.range(at: 6..<10)])
print(input.allRanges(of: "aaba").prefix(2))
}
}
+16 -1
View File
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
import XCTest
import Algorithms
@testable import Algorithms
final class ProductTests: XCTestCase {
func testProduct() {
@@ -37,4 +37,19 @@ final class ProductTests: XCTestCase {
let p = product([1, 2], "abc")
XCTAssertEqual(p.distance(from: p.startIndex, to: p.endIndex), 6)
}
func testProductIndexTraversals() {
validateIndexTraversals(
product([1, 2, 3, 4], "abc"),
product([1, 2, 3, 4], ""),
product([], "abc"),
product([], ""),
indices: { product in
product.base1.indices.flatMap { i1 in
product.base2.indices.map { i2 in
.init(i1: i1, i2: i2)
}
} + [.init(i1: product.base1.endIndex, i2: product.base2.startIndex)]
})
}
}
@@ -26,11 +26,11 @@ func validateRandomSamples<S: Sequence>(
}
}
let n = 100
let k = 12
let iterations = 10_000
let c = 0..<n
let s = sequence(first: 0, next: { $0 == n - 1 ? nil : $0 + 1 })
private let n = 100
private let k = 12
private let iterations = 10_000
private let c = 0..<n
private let s = sequence(first: 0, next: { $0 == n - 1 ? nil : $0 + 1 })
final class RandomSampleTests: XCTestCase {
func testRandomStableSampleCollection() {
@@ -0,0 +1,91 @@
//===----------------------------------------------------------------------===//
//
// 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 SlidingWindowsTests: XCTestCase {
func testWindowsOfString() {
let s = "swift"
let w = s.slidingWindows(ofCount: 2)
var i = w.startIndex
XCTAssertEqualSequences(w[i], "sw")
w.formIndex(after: &i)
XCTAssertEqualSequences(w[i], "wi")
w.formIndex(after: &i)
XCTAssertEqualSequences(w[i], "if")
w.formIndex(after: &i)
XCTAssertEqualSequences(w[i], "ft")
// w.index(after: w.endIndex) // ← Precondition failed: SlidingWindows index is out of range
// w.index(before: w.startIndex) // ← Precondition failed: SlidingWindows index is out of range
// w.formIndex(after: &i); w[i] // ← Precondition failed: SlidingWindows index is out of range
}
func testWindowsOfRange() {
let a = 0...100
XCTAssertTrue(a.slidingWindows(ofCount: 200).isEmpty)
let w = a.slidingWindows(ofCount: 10)
XCTAssertEqualSequences(w.first!, 0..<10)
XCTAssertEqualSequences(w.last!, 91..<101)
}
func testWindowsOfInt() {
let a = [ 0, 1, 0, 1 ].slidingWindows(ofCount: 2)
XCTAssertEqual(a.count, 3)
XCTAssertEqual(a.map { $0.reduce(0, +) }, [1, 1, 1])
let a2 = [0, 1, 2, 3, 4, 5, 6].slidingWindows(ofCount: 3).map {
$0.reduce(0, +)
}.reduce(0, +)
XCTAssertEqual(a2, 3 + 6 + 9 + 12 + 15)
}
func testWindowsCount() {
let a = [0, 1, 2, 3, 4, 5]
XCTAssertEqual(a.slidingWindows(ofCount: 3).count, 4)
let a2 = [0, 1, 2, 3, 4]
XCTAssertEqual(a2.slidingWindows(ofCount: 6).count, 0)
let a3 = [Int]()
XCTAssertEqual(a3.slidingWindows(ofCount: 2).count, 0)
}
func testWindowsSecondAndLast() {
let a = [0, 1, 2, 3, 4, 5]
let w = a.slidingWindows(ofCount: 4)
let snd = w[w.index(after: w.startIndex)]
XCTAssertEqualSequences(snd, [1, 2, 3, 4])
let w2 = a.slidingWindows(ofCount: 3)
XCTAssertEqualSequences(w2.last!, [3, 4, 5])
}
func testWindowsIndexAfterAndBefore() {
let a = [0, 1, 2, 3, 4, 5].slidingWindows(ofCount: 2)
var i = a.startIndex
a.formIndex(after: &i)
a.formIndex(after: &i)
a.formIndex(before: &i)
XCTAssertEqualSequences(a[i], [1, 2])
}
}
+210 -2
View File
@@ -49,10 +49,28 @@ struct SplitMix64: RandomNumberGenerator {
func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1,
_ expression2: @autoclosure () throws -> S2,
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
try XCTAssert(expression1().elementsEqual(expression2()), message(), file: file, line: line)
var iterator1 = try expression1().makeIterator()
var iterator2 = try expression2().makeIterator()
var offset = 0
while true {
guard let element1 = iterator1.next() else {
if iterator2.next() != nil {
XCTFail("First sequence had fewer elements than the second", file: file, line: line)
}
return
}
guard let element2 = iterator2.next() else {
XCTFail("First sequence had more elements than the second", file: file, line: line)
return
}
XCTAssertEqual(element1, element2, "Elements not equal at offset \(offset)", file: file, line: line)
offset += 1
}
}
func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
@@ -66,3 +84,193 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
}
func XCTAssertLazy<S: LazySequenceProtocol>(_: S) {}
/// Tests that all index traversal methods behave as expected.
///
/// Verifies the correctness of the implementations of `startIndex`, `endIndex`,
/// `indices`, `count`, `isEmpty`, `index(before:)`, `index(after:)`,
/// `index(_:offsetBy:)`, `index(_:offsetBy:limitedBy:)`, and
/// `distance(from:to:)` by calling them with just about all possible input
/// combinations. When provided, the `indices` function is used to to test the
/// collection methods against.
///
/// - Parameters:
/// - collections: The collections to be validated.
/// - indices: A closure that returns the expected indices of the given
/// collection, including its `endIndex`, in ascending order. Only use this
/// parameter if you are able to compute the indices of the collection
/// independently of the `Collection` conformance, e.g. by using the
/// contents of the collection directly.
///
/// - Complexity: O(*n*^3) for each collection, where *n* is the length of the
/// collection.
func validateIndexTraversals<C>(
_ collections: C...,
indices: ((C) -> [C.Index])? = nil,
file: StaticString = #file, line: UInt = #line
) where C: BidirectionalCollection {
for c in collections {
let indicesIncludingEnd = indices?(c) ?? (c.indices + [c.endIndex])
let count = indicesIncludingEnd.count - 1
XCTAssertEqual(
c.count, count,
"Count mismatch",
file: file, line: line)
XCTAssertEqual(
c.isEmpty, count == 0,
"Emptiness mismatch",
file: file, line: line)
XCTAssertEqual(
c.startIndex, indicesIncludingEnd.first,
"`startIndex` does not equal the first index",
file: file, line: line)
XCTAssertEqual(
c.endIndex, indicesIncludingEnd.last,
"`endIndex` does not equal the last index",
file: file, line: line)
// `index(after:)`
do {
var index = c.startIndex
for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() {
c.formIndex(after: &index)
XCTAssertEqual(
index, expected,
"""
`startIndex` incremented \(offset) times does not equal index at \
offset \(offset)
""",
file: file, line: line)
}
}
// `index(before:)`
do {
var index = c.endIndex
for (offset, expected) in indicesIncludingEnd.enumerated().dropLast().reversed() {
c.formIndex(before: &index)
XCTAssertEqual(
index, expected,
"""
`endIndex` decremented \(count - offset) times does not equal index \
at offset \(offset)
""",
file: file, line: line)
}
}
// `indices`
XCTAssertEqual(c.indices.count, count)
for (offset, index) in c.indices.enumerated() {
XCTAssertEqual(
index, indicesIncludingEnd[offset],
"Index mismatch at offset \(offset) in `indices`",
file: file, line: line)
}
// index comparison
for (offsetA, a) in indicesIncludingEnd.enumerated() {
XCTAssertEqual(
a, a,
"Index at offset \(offsetA) does not equal itself",
file: file, line: line)
XCTAssertFalse(
a < a,
"Index at offset \(offsetA) is less than itself",
file: file, line: line)
for (offsetB, b) in indicesIncludingEnd[..<offsetA].enumerated() {
XCTAssertNotEqual(
a, b,
"Index at offset \(offsetA) equals index at offset \(offsetB)",
file: file, line: line)
XCTAssertLessThan(
b, a,
"""
Index at offset \(offsetB) is not less than index at offset \(offsetA)
""",
file: file, line: line)
}
}
// `index(_:offsetBy:)` and `distance(from:to:)`
for (startOffset, start) in indicesIncludingEnd.enumerated() {
for (endOffset, end) in indicesIncludingEnd.enumerated() {
let distance = endOffset - startOffset
XCTAssertEqual(
c.index(start, offsetBy: distance), end,
"""
Index at offset \(startOffset) offset by \(distance) does not equal \
index at offset \(endOffset)
""",
file: file, line: line)
XCTAssertEqual(
c.distance(from: start, to: end), distance,
"""
Distance from index at offset \(startOffset) to index at offset \
\(endOffset) does not equal \(distance)
""",
file: file, line: line)
}
}
// `index(_:offsetBy:limitedBy:)`
for (startOffset, start) in indicesIncludingEnd.enumerated() {
for (limitOffset, limit) in indicesIncludingEnd.enumerated() {
// verifies that the target index corresponding to each offset in
// `range` can or cannot be reached from `start` using
// `chain.index(start, offsetBy: _, limitedBy: limit)`, depending on the
// value of `pastLimit`
func checkTargetRange(_ range: ClosedRange<Int>, pastLimit: Bool) {
for targetOffset in range {
let distance = targetOffset - startOffset
let end = c.index(start, offsetBy: distance, limitedBy: limit)
if pastLimit {
XCTAssertNil(
end,
"""
Index at offset \(startOffset) offset by \(distance) limited \
by index at offset \(limitOffset) does not equal `nil`
""",
file: file, line: line)
} else {
XCTAssertEqual(
end, indicesIncludingEnd[targetOffset],
"""
Index at offset \(startOffset) offset by \(distance) limited \
by index at offset \(limitOffset) does not equal index at \
offset \(targetOffset)
""",
file: file, line: line)
}
}
}
// forward offsets
if limit >= start {
// the limit has an effect
checkTargetRange(startOffset...limitOffset, pastLimit: false)
checkTargetRange((limitOffset + 1)...(count + 1), pastLimit: true)
} else {
// the limit has no effect
checkTargetRange(startOffset...count, pastLimit: false)
}
// backward offsets
if limit <= start {
// the limit has an effect
checkTargetRange(limitOffset...startOffset, pastLimit: false)
checkTargetRange(-1...(limitOffset - 1), pastLimit: true)
} else {
// the limit has no effect
checkTargetRange(0...startOffset, pastLimit: false)
}
}
}
}
}
@@ -0,0 +1,59 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import Algorithms
import XCTest
final class TrimTests: XCTestCase {
func testEmpty() {
let results_empty = ([] as [Int]).trimming { $0.isMultiple(of: 2) }
XCTAssertEqual(results_empty, [])
}
func testNoMatch() {
// No match (nothing trimmed).
let results_nomatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming {
$0.isMultiple(of: 2)
}
XCTAssertEqual(results_nomatch, [1, 3, 5, 7, 9, 11, 13, 15])
}
func testNoTailMatch() {
// No tail match (only trim head).
let results_notailmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0 < 10 }
XCTAssertEqual(results_notailmatch, [11, 13, 15])
}
func testNoHeadMatch() {
// No head match (only trim tail).
let results_noheadmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0 > 10 }
XCTAssertEqual(results_noheadmatch, [1, 3, 5, 7, 9])
}
func testBothEndsMatch() {
// Both ends match, some string of >1 elements do not (return that string).
let results = [2, 10, 11, 15, 20, 21, 100].trimming { $0.isMultiple(of: 2) }
XCTAssertEqual(results, [11, 15, 20, 21])
}
func testEverythingMatches() {
// Everything matches (trim everything).
let results_allmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { _ in true }
XCTAssertEqual(results_allmatch, [])
}
func testEverythingButOneMatches() {
// Both ends match, one element does not (trim all except that element).
let results_one = [2, 10, 12, 15, 20, 100].trimming { $0.isMultiple(of: 2) }
XCTAssertEqual(results_one, [15])
}
}