diff --git a/Guides/SlidingWindows.md b/Guides/SlidingWindows.md deleted file mode 100644 index d1f1250..0000000 --- a/Guides/SlidingWindows.md +++ /dev/null @@ -1,64 +0,0 @@ -# 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 { - 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`, `RandomAccessCollection`, and -`LazyCollectionProtocol` 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. diff --git a/Guides/Windows.md b/Guides/Windows.md new file mode 100644 index 0000000..6b2d1fd --- /dev/null +++ b/Guides/Windows.md @@ -0,0 +1,55 @@ +# Windows + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Windows.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/WindowsTests.swift)] + +Break a collection into overlapping subsequences where +elements are slices from the original collection. + +The `windows(ofCount:)` method takes a size as a parameter and returns a collection of subsequences. Each element of the returned collection is a successive overlapping slice of the given size. + +```swift +let swift = "swift" + +let windowed = swift.windows(ofCount: 2) +// Array(windowed) == [ "sw", "wi", "if", "ft" ] +``` + +## Detailed Design + +The `windows(ofCount:)` method is added as an extension `Collection` method: + +```swift +extension Collection { + public func windows(ofCount count: Int) -> Windows +} +``` + +If a size larger than the collection's length is specified, the returned collection is empty. + +```swift +[1, 2, 3].windows(ofCount: 5).isEmpty // true +``` + +The resulting `Windows` type is a collection, with conditional conformance to the +`BidirectionalCollection`, `RandomAccessCollection`, and +`LazyCollectionProtocol` protocols when the base collection conforms. + +### Complexity + +The call to `windows(ofCount: k)` is O(1) if the collection conforms to +`RandomAccessCollection`, otherwise O(_k_). Access to each successive window is O(1). + +### Naming + +The method and type name take their names from the sliding windows algorithm. + +The `ofCount` parameter label was chosen to create a consistent feel with other +APIs in the `Algorithms` package, specifically with `combinations(ofCount:)` +and `permutations(ofCount:)`. + +### 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. diff --git a/README.md b/README.md index 714a7d6..b1fd944 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Read more about the package, and the intent behind it, in the [announcement on s - [`chunked(by:)`, `chunked(on:)`, `chunks(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chunked.md): Eager and lazy operations that break a collection into chunks based on either a binary predicate or when the result of a projection changes or chunks of a given count. - [`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. -- [`slidingWindows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/SlidingWindows.md): Breaks a collection into overlapping contiguous window subsequences where elements are slices from the original collection. +- [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/SlidingWindows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection. - [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection. ## Adding Swift Algorithms as a Dependency diff --git a/Sources/Algorithms/SlidingWindows.swift b/Sources/Algorithms/Windows.swift similarity index 83% rename from Sources/Algorithms/SlidingWindows.swift rename to Sources/Algorithms/Windows.swift index 24ef09d..6dd0aa4 100644 --- a/Sources/Algorithms/SlidingWindows.swift +++ b/Sources/Algorithms/Windows.swift @@ -10,44 +10,58 @@ //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// -// slidingWindows(ofCount:) +// windows(ofCount:) //===----------------------------------------------------------------------===// extension Collection { - /// A collection for all contiguous windows of length size, the - /// windows overlap. + /// Returns a collection of all the overlapping slices of a given size. /// - /// - Complexity: O(*1*) if the collection conforms to - /// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`. - /// Access to the next window is O(*1*). + /// Use this method to iterate over overlapping subsequences of this + /// collection. This example prints every five character substring of `str`: + /// + /// let str = "Hello, world!" + /// for substring in str.windows(ofCount: 5) { + /// print(substring) + /// } + /// // "Hello" + /// // "ello," + /// // "llo, " + /// // "lo, W" + /// // ... + /// // "orld!" /// /// - Parameter count: The number of elements in each window subsequence. + /// - Returns: A collection of subsequences of this collection, each with + /// length `count`. If this collection is shorter than `count`, the + /// resulting collection is empty. /// - /// - Returns: If the collection is shorter than `size` the resulting - /// SlidingWindows collection will be empty. - public func slidingWindows(ofCount count: Int) -> SlidingWindows { - SlidingWindows(base: self, size: count) + /// - Complexity: O(1) if the collection conforms to + /// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`. + /// Access to successive windows is O(1). + public func windows(ofCount count: Int) -> Windows { + Windows(base: self, size: count) } } /// A collection wrapper that presents a sliding window over the elements of /// a collection. -public struct SlidingWindows { +public struct Windows { public let base: Base public let size: Int internal var firstUpperBound: Base.Index? internal init(base: Base, size: Int) { - precondition(size > 0, "SlidingWindows size must be greater than zero") + precondition(size > 0, "Windows size must be greater than zero") self.base = base self.size = size - self.firstUpperBound = base.index(base.startIndex, offsetBy: size, limitedBy: base.endIndex) + self.firstUpperBound = + base.index(base.startIndex, offsetBy: size, limitedBy: base.endIndex) } } -extension SlidingWindows: Collection { - /// A position in a `SlidingWindows` collection. +extension Windows: Collection { + /// A position in a `Windows` collection. public struct Index: Comparable { internal var lowerBound: Base.Index internal var upperBound: Base.Index @@ -74,7 +88,9 @@ extension SlidingWindows: Collection { } public subscript(index: Index) -> Base.SubSequence { - precondition(index.lowerBound != index.upperBound, "SlidingWindows index is out of range") + precondition( + index.lowerBound != index.upperBound, + "Windows index is out of range") return base[index.lowerBound.. Index { precondition(index > startIndex, "Incrementing past start index") if index == endIndex { @@ -302,9 +318,9 @@ extension SlidingWindows: BidirectionalCollection where Base: BidirectionalColle } } -extension SlidingWindows: LazySequenceProtocol where Base: LazySequenceProtocol {} -extension SlidingWindows: LazyCollectionProtocol where Base: LazyCollectionProtocol {} -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 {} +extension Windows: LazySequenceProtocol where Base: LazySequenceProtocol {} +extension Windows: LazyCollectionProtocol where Base: LazyCollectionProtocol {} +extension Windows: RandomAccessCollection where Base: RandomAccessCollection {} +extension Windows: Equatable where Base: Equatable {} +extension Windows: Hashable where Base: Hashable, Base.Index: Hashable {} +extension Windows.Index: Hashable where Base.Index: Hashable {} diff --git a/Tests/SwiftAlgorithmsTests/SlidingWindowsTests.swift b/Tests/SwiftAlgorithmsTests/WindowsTests.swift similarity index 64% rename from Tests/SwiftAlgorithmsTests/SlidingWindowsTests.swift rename to Tests/SwiftAlgorithmsTests/WindowsTests.swift index 428a619..51ce285 100644 --- a/Tests/SwiftAlgorithmsTests/SlidingWindowsTests.swift +++ b/Tests/SwiftAlgorithmsTests/WindowsTests.swift @@ -12,12 +12,11 @@ import XCTest @testable import Algorithms -final class SlidingWindowsTests: XCTestCase { +final class windowsTests: XCTestCase { func testWindowsOfString() { - let s = "swift" - let w = s.slidingWindows(ofCount: 2) + let w = s.windows(ofCount: 2) var i = w.startIndex XCTAssertEqualSequences(w[i], "sw") @@ -28,30 +27,29 @@ final class SlidingWindowsTests: XCTestCase { 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 +// w.index(after: w.endIndex) // ← Precondition failed: windows index is out of range +// w.index(before: w.startIndex) // ← Precondition failed: windows index is out of range +// w.formIndex(after: &i); w[i] // ← Precondition failed: windows index is out of range } func testWindowsOfRange() { let a = 0...100 - XCTAssertTrue(a.slidingWindows(ofCount: 200).isEmpty) + XCTAssertTrue(a.windows(ofCount: 200).isEmpty) - let w = a.slidingWindows(ofCount: 10) + let w = a.windows(ofCount: 10) XCTAssertEqualSequences(w.first!, 0..<10) XCTAssertEqualSequences(w.last!, 91..<101) } func testWindowsOfInt() { - - let a = [ 0, 1, 0, 1 ].slidingWindows(ofCount: 2) + let a = [ 0, 1, 0, 1 ].windows(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 { + let a2 = [0, 1, 2, 3, 4, 5, 6].windows(ofCount: 3).map { $0.reduce(0, +) }.reduce(0, +) @@ -60,27 +58,27 @@ final class SlidingWindowsTests: XCTestCase { func testWindowsCount() { let a = [0, 1, 2, 3, 4, 5] - XCTAssertEqual(a.slidingWindows(ofCount: 3).count, 4) + XCTAssertEqual(a.windows(ofCount: 3).count, 4) let a2 = [0, 1, 2, 3, 4] - XCTAssertEqual(a2.slidingWindows(ofCount: 6).count, 0) + XCTAssertEqual(a2.windows(ofCount: 6).count, 0) let a3 = [Int]() - XCTAssertEqual(a3.slidingWindows(ofCount: 2).count, 0) + XCTAssertEqual(a3.windows(ofCount: 2).count, 0) } func testWindowsSecondAndLast() { let a = [0, 1, 2, 3, 4, 5] - let w = a.slidingWindows(ofCount: 4) + let w = a.windows(ofCount: 4) let snd = w[w.index(after: w.startIndex)] XCTAssertEqualSequences(snd, [1, 2, 3, 4]) - let w2 = a.slidingWindows(ofCount: 3) + let w2 = a.windows(ofCount: 3) XCTAssertEqualSequences(w2.last!, [3, 4, 5]) } func testWindowsIndexAfterAndBefore() { - let a = [0, 1, 2, 3, 4, 5].slidingWindows(ofCount: 2) + let a = [0, 1, 2, 3, 4, 5].windows(ofCount: 2) var i = a.startIndex a.formIndex(after: &i) a.formIndex(after: &i) @@ -90,14 +88,14 @@ final class SlidingWindowsTests: XCTestCase { func testWindowsIndexTraversals() { validateIndexTraversals( - "".slidingWindows(ofCount: 1), - "a".slidingWindows(ofCount: 1), - "ab".slidingWindows(ofCount: 1), - "abc".slidingWindows(ofCount: 1), - "".slidingWindows(ofCount: 3), - "a".slidingWindows(ofCount: 3), - "abc".slidingWindows(ofCount: 3), - "abcdefgh".slidingWindows(ofCount: 3), + "".windows(ofCount: 1), + "a".windows(ofCount: 1), + "ab".windows(ofCount: 1), + "abc".windows(ofCount: 1), + "".windows(ofCount: 3), + "a".windows(ofCount: 3), + "abc".windows(ofCount: 3), + "abcdefgh".windows(ofCount: 3), indices: { windows in let endIndex = windows.base.endIndex let indices = windows.base.indices + [endIndex] @@ -108,6 +106,6 @@ final class SlidingWindowsTests: XCTestCase { } func testWindowsLazy() { - XCTAssertLazyCollection([0, 1, 2, 3].lazy.slidingWindows(ofCount: 2)) + XCTAssertLazyCollection([0, 1, 2, 3].lazy.windows(ofCount: 2)) } }