Files
swift-algorithms/Guides/SlidingWindows.md
T
Daniel Tull 93c8724c72 Add conformances to LazySequenceProtocol and LazyCollectionProtocol (#47)
* Conform Intersperse to LazySequenceProtocol when the base sequence does

* Add conformance to LazyCollectionProtocol

* Conform Indexed to LazyCollectionProtocol when Base conforms

* Rename XCTAssertLazy to XCTAssertLazySequence

* Add XCTAssertLazyCollection

* Add lazy test for Intersperse

* Update Indexed guide

* Add lazy conformances to SlidingWindows

* Update SlidingWindows guide
2020-12-01 15:47:13 -06:00

2.2 KiB

SlidingWindows

[Source | Tests]

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.

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

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.

[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 has std::slice::Windows which is a method available on slices. It has the same semantics as described here.