From 17cb07e38f9ce0dc00e4170ad5731e6b6da7ffa5 Mon Sep 17 00:00:00 2001 From: Oliver Atkinson Date: Mon, 12 Oct 2020 19:49:07 +0100 Subject: [PATCH 01/11] Add Stride for Collection --- Guides/Stride.md | 63 ++++++++ Sources/Algorithms/Stride.swift | 161 +++++++++++++++++++ Tests/SwiftAlgorithmsTests/StrideTests.swift | 160 ++++++++++++++++++ 3 files changed, 384 insertions(+) create mode 100644 Guides/Stride.md create mode 100644 Sources/Algorithms/Stride.swift create mode 100644 Tests/SwiftAlgorithmsTests/StrideTests.swift diff --git a/Guides/Stride.md b/Guides/Stride.md new file mode 100644 index 0000000..874e742 --- /dev/null +++ b/Guides/Stride.md @@ -0,0 +1,63 @@ +# Stride + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Stride.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/StrideTests.swift)] + +A type that steps over a collection’s elements by the specified amount. + +This is available through the `striding(by:)` method on any `Collection`. + +```swift +(0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10] +``` + +If the stride is larger than the collection count, the resulting wrapper only contains the +first element. + +The stride amount must be a positive value. + +## Detailed Design + +The `striding(by:)` method is declared as a `Collection` extension, and returns a +`Stride` type: + +```swift +extension Collection { + public func striding(by step: Int) -> Stride +} +``` + +A custom `Index` type is defined so that it's not possible to get confused when trying +to access an index of the stride collection. + +```swift +[0, 1, 2, 3, 4].striding(by: 2)[1] // == 1 +[0, 1, 2, 3, 4].striding(by: 2).map { $0 }[1] // == 2 +``` + +A careful thought was given to the composition of these strides by giving a custom +implementation to `index(_:offsetBy:limitedBy)` which multiplies the offset by the +stride amount. + +```swift +base.index(i.base, offsetBy: distance * stride, limitedBy: base.endIndex) +``` + +The following two lines of code are equivalent, including performance: + +```swift +(0...10).striding(by: 6) +(0...10).striding(by: 2).stride(by: 3) +``` + +### Complexity + +The call to `striding(by: k)` is always O(_1_) and access to the next value in the stride +is O(_1_) if the collection conforms to `RandomAccessCollection`, otherwise O(_k_). + +### Comparison with other languages + +[rust has `Strided`](https://docs.rs/strided/0.2.9/strided/) available in a crate. +[c++ has std::slice::stride](http://www.cplusplus.com/reference/valarray/slice/stride/) + +The semantics of `striding` described in this documentation are equivalent. diff --git a/Sources/Algorithms/Stride.swift b/Sources/Algorithms/Stride.swift new file mode 100644 index 0000000..33b7700 --- /dev/null +++ b/Sources/Algorithms/Stride.swift @@ -0,0 +1,161 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +//===----------------------------------------------------------------------===// +// striding(by:) +//===----------------------------------------------------------------------===// + +extension Collection { + /// Returns a collection stepping through the elements every `step` starting + /// at the first value. Any remainders of the stride will be trimmed. + /// + /// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10] + /// (0...10).striding(by: 3) // == [0, 3, 6, 9] + /// + /// - Complexity: O(1). Access to successive values is O(1) if the + /// collection conforms to `RandomAccessCollection`; otherwise, + /// O(_k_), where _k_ is the striding `step`. + /// + /// - Parameter step: The amount to step with each iteration. + /// - Returns: Returns a collection stepping through the elements by the + /// specified amount. + public func striding(by step: Int) -> Stride { + Stride(base: self, stride: step) + } +} + +public struct Stride { + + public let base: Base + public let stride: Int + + init(base: Base, stride: Int) { + precondition(stride > 0, "striding must be greater than zero") + self.base = base + self.stride = stride + } +} + +extension Stride { + public func striding(by step: Int) -> Self { + Stride(base: base, stride: stride * step) + } +} + +extension Stride: Collection { + + public struct Index: Comparable { + + let base: Base.Index + + init(_ base: Base.Index) { + self.base = base + } + + public static func < (lhs: Index, rhs: Index) -> Bool { + lhs.base < rhs.base + } + } + + public var startIndex: Index { + Index(base.startIndex) + } + + public var endIndex: Index { + Index(base.endIndex) + } + + public subscript(i: Index) -> Base.Element { + base[i.base] + } + + public func index(after i: Index) -> Index { + precondition(i.base < base.endIndex, "Advancing past end index") + return base.index(i.base, offsetBy: stride, limitedBy: base.endIndex) + .map(Index.init) ?? endIndex + } + + public func index( + _ i: Index, + offsetBy distance: Int, + limitedBy limit: Index + ) -> Index? { + base.index(i.base, offsetBy: distance * stride, limitedBy: limit.base) + .map(Index.init) + } + + public var count: Int { + let limit = base.count - 1 + return limit / stride + (limit < 0 ? 0 : 1) + } + + public func distance(from start: Index, to end: Index) -> Int { + let distance = base.distance(from: start.base, to: end.base) + return distance / stride + (distance % stride > 0 ? 1 : 0) + } + + public func index(_ i: Index, offsetBy distance: Int) -> Index { + precondition(distance <= 0 || i.base < base.endIndex, "Advancing past end index") + precondition(distance >= 0 || i.base > base.startIndex, "Incrementing past start index") + return Index(base.index(i.base, offsetBy: distance * stride)) + } +} + +extension Stride: BidirectionalCollection + where Base: RandomAccessCollection { + + public func index(before i: Index) -> Index { + precondition(i.base > base.startIndex, "Incrementing past start index") + if i == endIndex { + let count = base.count + precondition(count > 0, "Can't move before the starting index") + return Index( + base.index(base.endIndex, offsetBy: -((count - 1) % stride + 1)) + ) + } else { + guard let step = base.index( + i.base, + offsetBy: -stride, + limitedBy: startIndex.base + ) else { + fatalError("Incrementing past start index") + } + return Index(step) + } + } +} + +extension Stride: RandomAccessCollection + where Base: RandomAccessCollection {} + +extension Stride: Equatable + where Base.Element: Equatable { + + public static func == (lhs: Stride, rhs: Stride) -> Bool { + lhs.elementsEqual(rhs, by: ==) + } + +} + +extension Stride: Hashable + where Base.Element: Hashable { + + public func hash(into hasher: inout Hasher) { + hasher.combine(stride) + for element in self { + hasher.combine(element) + } + } + +} + +extension Stride.Index: Hashable + where Base.Index: Hashable {} diff --git a/Tests/SwiftAlgorithmsTests/StrideTests.swift b/Tests/SwiftAlgorithmsTests/StrideTests.swift new file mode 100644 index 0000000..5623bfe --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/StrideTests.swift @@ -0,0 +1,160 @@ +//===----------------------------------------------------------------------===// +// +// 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 StridingTests: XCTestCase { + + func testStride() { + let a = (0...10) + XCTAssertEqualSequences(a.striding(by: 1), (0...10)) + XCTAssertEqualSequences(a.striding(by: 2), [0, 2, 4, 6, 8, 10]) + XCTAssertEqualSequences(a.striding(by: 3), [0, 3, 6, 9]) + XCTAssertEqualSequences(a.striding(by: 4), [0, 4, 8]) + XCTAssertEqualSequences(a.striding(by: 5), [0, 5, 10]) + XCTAssertEqualSequences(a.striding(by: 10), [0, 10]) + XCTAssertEqualSequences(a.striding(by: 11), [0]) + } + + func testStrideString() { + let s = "swift" + XCTAssertEqualSequences(s.striding(by: 2), ["s", "i", "t"]) + } + + func testStrideReversed() { + let a = [0, 1, 2, 3, 4, 5] + XCTAssertEqualSequences(a.striding(by: 3).reversed(), [3, 0]) + XCTAssertEqualSequences(a.reversed().striding(by: 2), [5, 3, 1]) + } + + func testStrideIndexes() { + let a = [0, 1, 2, 3, 4, 5].striding(by: 2) + var i = a.startIndex + XCTAssertEqual(a[i], 0) + a.formIndex(after: &i) + XCTAssertEqual(a[i], 2) + a.formIndex(after: &i) + XCTAssertEqual(a[i], 4) + a.formIndex(before: &i) + XCTAssertEqual(a[i], 2) + a.formIndex(before: &i) + XCTAssertEqual(a[i], 0) +// a.formIndex(before: &i) // Precondition failed: Advancing past start index +// a.index(after: a.endIndex) // Precondition failed: Advancing past end index + } + + func testStrideCompositionEquivalence() { + let a = (0...10) + XCTAssertEqualSequences(a.striding(by: 6), a.striding(by: 2).striding(by: 3)) + XCTAssertTrue(a.striding(by: 6) == a.striding(by: 2).striding(by: 3)) + XCTAssert(type(of: a.striding(by: 2).striding(by: 3)) == Stride>.self) + } + + func testEquality() { + let a = [1, 2, 3, 4, 5].striding(by: 2) + let b = [1, 0, 3, 0, 5].striding(by: 2) + XCTAssertEqual(a, b) + } + + func testStrideLast() { + XCTAssertEqual((1...10).striding(by: 2).last, 9) // 1, 3, 5, 7, 9 + XCTAssertEqual((1...10).striding(by: 3).last, 10) // 1, 4, 7, 10 + XCTAssertEqual((1...10).striding(by: 4).last, 9) // 1, 5, 9 + XCTAssertEqual((1...10).striding(by: 5).last, 6) // 1, 6 + XCTAssertEqual((1...100).striding(by: 50).last, 51) // 1, 51 + XCTAssertEqual((1...5).striding(by: 2).last, 5) // 1, 3, 5 + XCTAssertEqual([Int]().striding(by: 2).last, nil) // empty + } + + func testCount() { + let empty = [Int]().striding(by: 2) + XCTAssertEqual(empty.count, 0) + let a = (0...10) + XCTAssertEqual(a.striding(by: 1).count, (0...10).count) + XCTAssertEqual(a.striding(by: 2).count, [0, 2, 4, 6, 8, 10].count) + XCTAssertEqual(a.striding(by: 3).count, [0, 3, 6, 9].count) + XCTAssertEqual(a.striding(by: 4).count, [0, 4, 8].count) + XCTAssertEqual(a.striding(by: 5).count, [0, 5, 10].count) + XCTAssertEqual(a.striding(by: 10).count, [0, 10].count) + XCTAssertEqual(a.striding(by: 11).count, [0].count) + } + + func testIndexTraversals() { + validateIndexTraversals( + (0...100).striding(by: 10) +// (0...100).striding(by: 11) +// (0...100).striding(by: 101) + ) + } + + func testDistance() { + + do { + let a = (0...100).striding(by: 11) + XCTAssertEqual(a.distance(from: a.startIndex, to: a.endIndex), a.count) + for (i, index) in a.indices.enumerated() { + XCTAssertEqual(a.distance(from: a.startIndex, to: index), i) + } + + var i = a.startIndex + a.formIndex(&i, offsetBy: 3) + XCTAssertEqual(a.distance(from: a.startIndex, to: i), 3) + XCTAssertEqual(a[i], 33) + } + + do { + + let a = (0...100).striding(by: 10) + XCTAssertEqual(a.distance(from: a.startIndex, to: a.endIndex), a.count) + + for (i, index) in a.indices.enumerated() { + XCTAssertEqual(a.distance(from: a.startIndex, to: index), i) + } + + var i = a.startIndex + a.formIndex(&i, offsetBy: 3) + XCTAssertEqual(a.distance(from: a.startIndex, to: i), 3) + XCTAssertEqual(a[i], 30) + } + + do { + + let a = (0...100).striding(by: 101) + XCTAssertEqual(a.distance(from: a.startIndex, to: a.endIndex), a.count) + + for (i, index) in a.indices.enumerated() { + XCTAssertEqual(a.distance(from: a.startIndex, to: index), i) + } + + var i = a.startIndex + a.formIndex(&i, offsetBy: 1) + XCTAssertEqual(a.distance(from: a.startIndex, to: i), a.count) + XCTAssertEqual(i, a.endIndex) +// a[i] // == Fatal error: Index out of range + } + } + + func testOffsetBy() { + let a = (0...100).striding(by: 22) + let b = [0, 22, 44, 66, 88] + for i in 0.. Date: Sun, 1 Nov 2020 20:27:52 +0000 Subject: [PATCH 02/11] Refactor to index(_:offsetBy:limitedBy:) and utilise the new test utilities for validateIndexTraversals --- Sources/Algorithms/Stride.swift | 60 ++++++++++-------- Tests/SwiftAlgorithmsTests/StrideTests.swift | 65 +++++--------------- 2 files changed, 51 insertions(+), 74 deletions(-) diff --git a/Sources/Algorithms/Stride.swift b/Sources/Algorithms/Stride.swift index 33b7700..e93ed86 100644 --- a/Sources/Algorithms/Stride.swift +++ b/Sources/Algorithms/Stride.swift @@ -60,6 +60,11 @@ extension Stride: Collection { self.base = base } + init?(_ base: Base.Index?) { + guard let base = base else { return nil } + self.base = base + } + public static func < (lhs: Index, rhs: Index) -> Bool { lhs.base < rhs.base } @@ -79,17 +84,34 @@ extension Stride: Collection { public func index(after i: Index) -> Index { precondition(i.base < base.endIndex, "Advancing past end index") - return base.index(i.base, offsetBy: stride, limitedBy: base.endIndex) - .map(Index.init) ?? endIndex + return index(i, offsetBy: 1, limitedBy: endIndex) ?? endIndex } - + public func index( _ i: Index, - offsetBy distance: Int, + offsetBy n: Int, limitedBy limit: Index ) -> Index? { - base.index(i.base, offsetBy: distance * stride, limitedBy: limit.base) - .map(Index.init) + guard n != 0 else { return i } + guard limit != i else { return nil } + switch (i, n) { + case (endIndex, ..<0): + let baseEnd = base.index(base.endIndex, offsetBy: -((base.count - 1) % stride + 1)) + return Index(base.index(baseEnd, offsetBy: (n - n.signum()) * stride, limitedBy: limit.base)) + case (_, 1...): + let max = limit < i ? endIndex.base : limit.base + let idx = base.index(i.base, offsetBy: n * stride, limitedBy: max) + if let idx = idx { + return idx > max ? endIndex : Index(idx) + } + guard i >= limit || limit == endIndex else { + return nil + } + let isToEnd = distance(from: i, to: endIndex) == n + return isToEnd ? endIndex : nil + case _: + return Index(base.index(i.base, offsetBy: n * stride, limitedBy: limit.base)) + } } public var count: Int { @@ -99,37 +121,25 @@ extension Stride: Collection { public func distance(from start: Index, to end: Index) -> Int { let distance = base.distance(from: start.base, to: end.base) - return distance / stride + (distance % stride > 0 ? 1 : 0) + return distance / stride + (abs(distance % stride) > 0 ? distance.signum() : 0) } public func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(distance <= 0 || i.base < base.endIndex, "Advancing past end index") precondition(distance >= 0 || i.base > base.startIndex, "Incrementing past start index") - return Index(base.index(i.base, offsetBy: distance * stride)) + let limit = distance > 0 ? endIndex : startIndex + let idx = index(i, offsetBy: distance, limitedBy: limit) + precondition(idx != nil, "The distance \(distance) is not valid for this collection") + return idx! } } extension Stride: BidirectionalCollection where Base: RandomAccessCollection { - + public func index(before i: Index) -> Index { precondition(i.base > base.startIndex, "Incrementing past start index") - if i == endIndex { - let count = base.count - precondition(count > 0, "Can't move before the starting index") - return Index( - base.index(base.endIndex, offsetBy: -((count - 1) % stride + 1)) - ) - } else { - guard let step = base.index( - i.base, - offsetBy: -stride, - limitedBy: startIndex.base - ) else { - fatalError("Incrementing past start index") - } - return Index(step) - } + return index(i, offsetBy: -1) } } diff --git a/Tests/SwiftAlgorithmsTests/StrideTests.swift b/Tests/SwiftAlgorithmsTests/StrideTests.swift index 5623bfe..da4fe56 100644 --- a/Tests/SwiftAlgorithmsTests/StrideTests.swift +++ b/Tests/SwiftAlgorithmsTests/StrideTests.swift @@ -89,59 +89,26 @@ final class StridingTests: XCTestCase { } func testIndexTraversals() { + let zero_to_one_hundered_range = 0...100 validateIndexTraversals( - (0...100).striding(by: 10) -// (0...100).striding(by: 11) -// (0...100).striding(by: 101) + zero_to_one_hundered_range.striding(by: 10), + zero_to_one_hundered_range.striding(by: 11), + zero_to_one_hundered_range.striding(by: 101) + ) + let zero_to_one_hundered_array = zero_to_one_hundered_range.map{ $0 } + validateIndexTraversals( + zero_to_one_hundered_array.striding(by: 10), + zero_to_one_hundered_array.striding(by: 11), + zero_to_one_hundered_array.striding(by: 101) + ) + let string = "swift rocks".map(String.init) + validateIndexTraversals( + string.striding(by: 1), + string.striding(by: 2), + string.striding(by: 10) ) } - - func testDistance() { - do { - let a = (0...100).striding(by: 11) - XCTAssertEqual(a.distance(from: a.startIndex, to: a.endIndex), a.count) - for (i, index) in a.indices.enumerated() { - XCTAssertEqual(a.distance(from: a.startIndex, to: index), i) - } - - var i = a.startIndex - a.formIndex(&i, offsetBy: 3) - XCTAssertEqual(a.distance(from: a.startIndex, to: i), 3) - XCTAssertEqual(a[i], 33) - } - - do { - - let a = (0...100).striding(by: 10) - XCTAssertEqual(a.distance(from: a.startIndex, to: a.endIndex), a.count) - - for (i, index) in a.indices.enumerated() { - XCTAssertEqual(a.distance(from: a.startIndex, to: index), i) - } - - var i = a.startIndex - a.formIndex(&i, offsetBy: 3) - XCTAssertEqual(a.distance(from: a.startIndex, to: i), 3) - XCTAssertEqual(a[i], 30) - } - - do { - - let a = (0...100).striding(by: 101) - XCTAssertEqual(a.distance(from: a.startIndex, to: a.endIndex), a.count) - - for (i, index) in a.indices.enumerated() { - XCTAssertEqual(a.distance(from: a.startIndex, to: index), i) - } - - var i = a.startIndex - a.formIndex(&i, offsetBy: 1) - XCTAssertEqual(a.distance(from: a.startIndex, to: i), a.count) - XCTAssertEqual(i, a.endIndex) -// a[i] // == Fatal error: Index out of range - } - } func testOffsetBy() { let a = (0...100).striding(by: 22) From 4a194ca811ed874293a96ea79a76e91921f48ed1 Mon Sep 17 00:00:00 2001 From: Oliver Atkinson Date: Sun, 1 Nov 2020 20:39:18 +0000 Subject: [PATCH 03/11] remove redundant limit --- Sources/Algorithms/Stride.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/Algorithms/Stride.swift b/Sources/Algorithms/Stride.swift index e93ed86..d8fc05e 100644 --- a/Sources/Algorithms/Stride.swift +++ b/Sources/Algorithms/Stride.swift @@ -84,7 +84,7 @@ extension Stride: Collection { public func index(after i: Index) -> Index { precondition(i.base < base.endIndex, "Advancing past end index") - return index(i, offsetBy: 1, limitedBy: endIndex) ?? endIndex + return index(i, offsetBy: 1) } public func index( From dcdef508c0abc1839008ae14b7d6d6e960164735 Mon Sep 17 00:00:00 2001 From: Oliver Atkinson Date: Mon, 2 Nov 2020 10:02:17 +0000 Subject: [PATCH 04/11] make base and stride internal --- Sources/Algorithms/Stride.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/Algorithms/Stride.swift b/Sources/Algorithms/Stride.swift index d8fc05e..480b468 100644 --- a/Sources/Algorithms/Stride.swift +++ b/Sources/Algorithms/Stride.swift @@ -34,8 +34,8 @@ extension Collection { public struct Stride { - public let base: Base - public let stride: Int + let base: Base + let stride: Int init(base: Base, stride: Int) { precondition(stride > 0, "striding must be greater than zero") From 6f7148d9668bf7a3cbe199b2e18c9acff59fc74a Mon Sep 17 00:00:00 2001 From: Oliver Atkinson Date: Fri, 6 Nov 2020 09:46:06 +0000 Subject: [PATCH 05/11] Implementation of feedback from @timvermeulen --- Sources/Algorithms/Stride.swift | 73 ++++++++++++++------ Tests/SwiftAlgorithmsTests/StrideTests.swift | 9 ++- 2 files changed, 59 insertions(+), 23 deletions(-) diff --git a/Sources/Algorithms/Stride.swift b/Sources/Algorithms/Stride.swift index 480b468..1dbd2ae 100644 --- a/Sources/Algorithms/Stride.swift +++ b/Sources/Algorithms/Stride.swift @@ -86,7 +86,7 @@ extension Stride: Collection { precondition(i.base < base.endIndex, "Advancing past end index") return index(i, offsetBy: 1) } - + public func index( _ i: Index, offsetBy n: Int, @@ -94,34 +94,65 @@ extension Stride: Collection { ) -> Index? { guard n != 0 else { return i } guard limit != i else { return nil } - switch (i, n) { - case (endIndex, ..<0): - let baseEnd = base.index(base.endIndex, offsetBy: -((base.count - 1) % stride + 1)) - return Index(base.index(baseEnd, offsetBy: (n - n.signum()) * stride, limitedBy: limit.base)) - case (_, 1...): - let max = limit < i ? endIndex.base : limit.base - let idx = base.index(i.base, offsetBy: n * stride, limitedBy: max) - if let idx = idx { - return idx > max ? endIndex : Index(idx) + + return n > 0 + ? offsetForward(i, offsetBy: n, limitedBy: limit) + : offsetBackward(i, offsetBy: n, limitedBy: limit) + } + + private func offsetForward( + _ i: Index, + offsetBy n: Int, + limitedBy limit: Index + ) -> Index? { + if limit < i { + if let idx = base.index( + i.base, + offsetBy: n * stride, + limitedBy: base.endIndex + ) { + return Index(idx) + } else { + assert(distance(from: i, to: endIndex) == n, "Advancing past end index") + return endIndex } - guard i >= limit || limit == endIndex else { - return nil - } - let isToEnd = distance(from: i, to: endIndex) == n - return isToEnd ? endIndex : nil - case _: - return Index(base.index(i.base, offsetBy: n * stride, limitedBy: limit.base)) + } else if let idx = base.index( + i.base, + offsetBy: n * stride, + limitedBy: limit.base + ) { + return Index(idx) + } else { + return distance(from: i, to: limit) == n + ? endIndex + : nil } } - + + private func offsetBackward( + _ i: Index, + offsetBy n: Int, + limitedBy limit: Index + ) -> Index? { + let distance = i == endIndex + ? -((base.count - 1) % stride + 1) + (n + 1) * stride + : n * stride + return Index( + base.index( + i.base, + offsetBy: distance, + limitedBy: limit.base + ) + ) + } + public var count: Int { - let limit = base.count - 1 - return limit / stride + (limit < 0 ? 0 : 1) + base.isEmpty ? 0 : (base.count - 1) / stride + 1 } public func distance(from start: Index, to end: Index) -> Int { let distance = base.distance(from: start.base, to: end.base) - return distance / stride + (abs(distance % stride) > 0 ? distance.signum() : 0) + return distance / stride + (distance % stride).signum() } public func index(_ i: Index, offsetBy distance: Int) -> Index { diff --git a/Tests/SwiftAlgorithmsTests/StrideTests.swift b/Tests/SwiftAlgorithmsTests/StrideTests.swift index da4fe56..3a54233 100644 --- a/Tests/SwiftAlgorithmsTests/StrideTests.swift +++ b/Tests/SwiftAlgorithmsTests/StrideTests.swift @@ -89,13 +89,18 @@ final class StridingTests: XCTestCase { } func testIndexTraversals() { + let empty = [Int]() + validateIndexTraversals( + empty.striding(by: 1), + empty.striding(by: 2) + ) let zero_to_one_hundered_range = 0...100 validateIndexTraversals( zero_to_one_hundered_range.striding(by: 10), zero_to_one_hundered_range.striding(by: 11), zero_to_one_hundered_range.striding(by: 101) ) - let zero_to_one_hundered_array = zero_to_one_hundered_range.map{ $0 } + let zero_to_one_hundered_array = Array(zero_to_one_hundered_range) validateIndexTraversals( zero_to_one_hundered_array.striding(by: 10), zero_to_one_hundered_array.striding(by: 11), @@ -113,7 +118,7 @@ final class StridingTests: XCTestCase { func testOffsetBy() { let a = (0...100).striding(by: 22) let b = [0, 22, 44, 66, 88] - for i in 0.. Date: Fri, 6 Nov 2020 10:13:29 +0000 Subject: [PATCH 06/11] Add implementation for Sequence iterator --- Guides/Stride.md | 6 ++--- Sources/Algorithms/Stride.swift | 28 +++++++++++++++++--- Tests/SwiftAlgorithmsTests/StrideTests.swift | 4 +-- 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/Guides/Stride.md b/Guides/Stride.md index 874e742..0c46ecc 100644 --- a/Guides/Stride.md +++ b/Guides/Stride.md @@ -5,7 +5,7 @@ A type that steps over a collection’s elements by the specified amount. -This is available through the `striding(by:)` method on any `Collection`. +This is available through the `striding(by:)` method on any `Sequence`. ```swift (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10] @@ -18,11 +18,11 @@ The stride amount must be a positive value. ## Detailed Design -The `striding(by:)` method is declared as a `Collection` extension, and returns a +The `striding(by:)` method is declared as a `Sequence` extension, and returns a `Stride` type: ```swift -extension Collection { +extension Sequence { public func striding(by step: Int) -> Stride } ``` diff --git a/Sources/Algorithms/Stride.swift b/Sources/Algorithms/Stride.swift index 1dbd2ae..ee8a5ab 100644 --- a/Sources/Algorithms/Stride.swift +++ b/Sources/Algorithms/Stride.swift @@ -13,7 +13,7 @@ // striding(by:) //===----------------------------------------------------------------------===// -extension Collection { +extension Sequence { /// Returns a collection stepping through the elements every `step` starting /// at the first value. Any remainders of the stride will be trimmed. /// @@ -32,7 +32,7 @@ extension Collection { } } -public struct Stride { +public struct Stride { let base: Base let stride: Int @@ -50,7 +50,29 @@ extension Stride { } } -extension Stride: Collection { +extension Stride: Sequence { + + public struct Iterator: IteratorProtocol { + + var iterator: Base.Iterator + let stride: Int + + public mutating func next() -> Base.Element? { + defer { + for _ in 0..<(stride - 1) { + guard iterator.next() != nil else { break } + } + } + return iterator.next() + } + } + + public func makeIterator() -> Stride.Iterator { + Iterator(iterator: base.makeIterator(), stride: stride) + } +} + +extension Stride: Collection where Base: Collection { public struct Index: Comparable { diff --git a/Tests/SwiftAlgorithmsTests/StrideTests.swift b/Tests/SwiftAlgorithmsTests/StrideTests.swift index 3a54233..6d53c1d 100644 --- a/Tests/SwiftAlgorithmsTests/StrideTests.swift +++ b/Tests/SwiftAlgorithmsTests/StrideTests.swift @@ -15,7 +15,7 @@ import Algorithms final class StridingTests: XCTestCase { func testStride() { - let a = (0...10) + let a = 0...10 XCTAssertEqualSequences(a.striding(by: 1), (0...10)) XCTAssertEqualSequences(a.striding(by: 2), [0, 2, 4, 6, 8, 10]) XCTAssertEqualSequences(a.striding(by: 3), [0, 3, 6, 9]) @@ -48,7 +48,7 @@ final class StridingTests: XCTestCase { XCTAssertEqual(a[i], 2) a.formIndex(before: &i) XCTAssertEqual(a[i], 0) -// a.formIndex(before: &i) // Precondition failed: Advancing past start index +// a.formIndex(before: &i) // Precondition failed: Incrementing past start index // a.index(after: a.endIndex) // Precondition failed: Advancing past end index } From 377bb72f0aa39d94fdacff01a747de4db1d2dc35 Mon Sep 17 00:00:00 2001 From: Oliver Atkinson Date: Fri, 6 Nov 2020 10:31:40 +0000 Subject: [PATCH 07/11] small documentation tweek collection -> sequence --- Guides/Stride.md | 4 ++-- Sources/Algorithms/Stride.swift | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Guides/Stride.md b/Guides/Stride.md index 0c46ecc..a309f25 100644 --- a/Guides/Stride.md +++ b/Guides/Stride.md @@ -3,7 +3,7 @@ [[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Stride.swift) | [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/StrideTests.swift)] -A type that steps over a collection’s elements by the specified amount. +A type that steps over sequence elements by the specified amount. This is available through the `striding(by:)` method on any `Sequence`. @@ -11,7 +11,7 @@ This is available through the `striding(by:)` method on any `Sequence`. (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10] ``` -If the stride is larger than the collection count, the resulting wrapper only contains the +If the stride is larger than the count, the resulting wrapper only contains the first element. The stride amount must be a positive value. diff --git a/Sources/Algorithms/Stride.swift b/Sources/Algorithms/Stride.swift index ee8a5ab..19ca012 100644 --- a/Sources/Algorithms/Stride.swift +++ b/Sources/Algorithms/Stride.swift @@ -14,7 +14,7 @@ //===----------------------------------------------------------------------===// extension Sequence { - /// Returns a collection stepping through the elements every `step` starting + /// Returns a sequence stepping through the elements every `step` starting /// at the first value. Any remainders of the stride will be trimmed. /// /// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10] @@ -25,8 +25,8 @@ extension Sequence { /// O(_k_), where _k_ is the striding `step`. /// /// - Parameter step: The amount to step with each iteration. - /// - Returns: Returns a collection stepping through the elements by the - /// specified amount. + /// - Returns: Returns a sequence or collection for stepping through the + /// elements by the specified amount. public func striding(by step: Int) -> Stride { Stride(base: self, stride: step) } From 92b284634572828d3d7a39f271be39f5bf568ea4 Mon Sep 17 00:00:00 2001 From: Oliver Atkinson Date: Fri, 6 Nov 2020 10:42:38 +0000 Subject: [PATCH 08/11] Add unbounded striding tests to check empty and sequence implementation --- Tests/SwiftAlgorithmsTests/StrideTests.swift | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Tests/SwiftAlgorithmsTests/StrideTests.swift b/Tests/SwiftAlgorithmsTests/StrideTests.swift index 6d53c1d..536dbb1 100644 --- a/Tests/SwiftAlgorithmsTests/StrideTests.swift +++ b/Tests/SwiftAlgorithmsTests/StrideTests.swift @@ -23,6 +23,18 @@ final class StridingTests: XCTestCase { XCTAssertEqualSequences(a.striding(by: 5), [0, 5, 10]) XCTAssertEqualSequences(a.striding(by: 10), [0, 10]) XCTAssertEqualSequences(a.striding(by: 11), [0]) + + let s = (0...).prefix(11) + XCTAssertEqualSequences(s.striding(by: 1), (0...10)) + XCTAssertEqualSequences(s.striding(by: 2), [0, 2, 4, 6, 8, 10]) + XCTAssertEqualSequences(s.striding(by: 3), [0, 3, 6, 9]) + XCTAssertEqualSequences(s.striding(by: 4), [0, 4, 8]) + XCTAssertEqualSequences(s.striding(by: 5), [0, 5, 10]) + XCTAssertEqualSequences(s.striding(by: 10), [0, 10]) + XCTAssertEqualSequences(s.striding(by: 11), [0]) + + let empty = (0...).prefix(0) + XCTAssertEqualSequences(empty.striding(by: 2), []) } func testStrideString() { From 0a6bcc3c6828b490924490a42104f83f126e231d Mon Sep 17 00:00:00 2001 From: Oliver Atkinson Date: Fri, 6 Nov 2020 15:25:34 +0000 Subject: [PATCH 09/11] compute the stride only when the next element is requested --- Sources/Algorithms/Stride.swift | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Sources/Algorithms/Stride.swift b/Sources/Algorithms/Stride.swift index 19ca012..4f4ef53 100644 --- a/Sources/Algorithms/Stride.swift +++ b/Sources/Algorithms/Stride.swift @@ -56,12 +56,15 @@ extension Stride: Sequence { var iterator: Base.Iterator let stride: Int + var striding: Bool = false public mutating func next() -> Base.Element? { - defer { - for _ in 0..<(stride - 1) { - guard iterator.next() != nil else { break } - } + guard striding else { + striding = true + return iterator.next() + } + for _ in 0.. Date: Fri, 6 Nov 2020 15:33:03 +0000 Subject: [PATCH 10/11] offsetBackward n is positive and remove init? from Index --- Sources/Algorithms/Stride.swift | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/Sources/Algorithms/Stride.swift b/Sources/Algorithms/Stride.swift index 4f4ef53..4e35ebd 100644 --- a/Sources/Algorithms/Stride.swift +++ b/Sources/Algorithms/Stride.swift @@ -85,11 +85,6 @@ extension Stride: Collection where Base: Collection { self.base = base } - init?(_ base: Base.Index?) { - guard let base = base else { return nil } - self.base = base - } - public static func < (lhs: Index, rhs: Index) -> Bool { lhs.base < rhs.base } @@ -122,7 +117,7 @@ extension Stride: Collection where Base: Collection { return n > 0 ? offsetForward(i, offsetBy: n, limitedBy: limit) - : offsetBackward(i, offsetBy: n, limitedBy: limit) + : offsetBackward(i, offsetBy: -n, limitedBy: limit) } private func offsetForward( @@ -160,15 +155,13 @@ extension Stride: Collection where Base: Collection { limitedBy limit: Index ) -> Index? { let distance = i == endIndex - ? -((base.count - 1) % stride + 1) + (n + 1) * stride - : n * stride - return Index( - base.index( + ? -((base.count - 1) % stride + 1) + (1 - n) * stride + : n * -stride + return base.index( i.base, offsetBy: distance, limitedBy: limit.base - ) - ) + ).map(Index.init) } public var count: Int { From dfcc611e1de2271b22acaedf6596c3be0bfa4d24 Mon Sep 17 00:00:00 2001 From: Oliver Atkinson Date: Fri, 6 Nov 2020 15:52:42 +0000 Subject: [PATCH 11/11] consistant negative stride --- Sources/Algorithms/Stride.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/Algorithms/Stride.swift b/Sources/Algorithms/Stride.swift index 4e35ebd..a922895 100644 --- a/Sources/Algorithms/Stride.swift +++ b/Sources/Algorithms/Stride.swift @@ -155,7 +155,7 @@ extension Stride: Collection where Base: Collection { limitedBy limit: Index ) -> Index? { let distance = i == endIndex - ? -((base.count - 1) % stride + 1) + (1 - n) * stride + ? -((base.count - 1) % stride + 1) + (n - 1) * -stride : n * -stride return base.index( i.base,