Skip to content

Add random-access methods to SlidingWindows #42

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
197 changes: 195 additions & 2 deletions Sources/Algorithms/SlidingWindows.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,202 @@ extension SlidingWindows: Collection {
)
}

// TODO: Implement distance(from:to:), index(_:offsetBy:) and
// index(_:offsetBy:limitedBy:)
public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i }

return distance > 0
? offsetForward(i, by: distance)
: offsetBackward(i, by: -distance)
}

public func index(
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
guard distance != 0 else { return i }
guard limit != i else { return nil }

if distance > 0 {
return limit > i
? offsetForward(i, by: distance, limitedBy: limit)
: offsetForward(i, by: distance)
} else {
return limit < i
? offsetBackward(i, by: -distance, limitedBy: limit)
: offsetBackward(i, by: -distance)
}
}

private func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") }
return index
}

private func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") }
return index
}

private func offsetForward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance > 0)
assert(limit > i)

// `endIndex` and the index before it both have `base.endIndex` as their
// upper bound, so we first advance to the base index _before_ the upper
// bound of the output, in order to avoid advancing past the end of `base`
// when advancing to `endIndex`.
//
// Advancing by 4:
//
// input: [x|x x x x x|x x x x] [x x|x x x x x|x x x]
// |> > >|>| or |> > >|
// output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👏 This is excellent and a massive help when reviewing this code


if distance >= size {
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the lower
// bound of the output is greater than or equal to the upper bound of the
// input.

// input: [x|x x x x|x x x x x x x]
// |> >|> > >|>|
// output: [x x x x x x x|x x x x|x]

guard limit.lowerBound >= i.upperBound,
let lowerBound = base.index(
i.upperBound,
offsetBy: distance - size,
limitedBy: limit.lowerBound),
let indexBeforeUpperBound = base.index(
lowerBound,
offsetBy: size - 1,
limitedBy: limit.upperBound)
else { return nil }

// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
// `endIndex`.
guard indexBeforeUpperBound != base.endIndex else { return endIndex }

return Index(
lowerBound: lowerBound,
upperBound: base.index(after: indexBeforeUpperBound))
} else {
// input: [x|x x x x x x|x x x x x]
// |> > > >| |> > >|>|
// output: [x x x x x|x x x x x x|x]

guard let indexBeforeUpperBound = base.index(
i.upperBound,
offsetBy: distance - 1,
limitedBy: limit.upperBound)
else { return nil }

// If `indexBeforeUpperBound` equals the limit, the upper bound itself
// exceeds it.
guard indexBeforeUpperBound != limit.upperBound || limit == endIndex
else { return nil }

// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
// `endIndex`.
guard indexBeforeUpperBound != base.endIndex else { return endIndex }

return Index(
lowerBound: base.index(i.lowerBound, offsetBy: distance),
upperBound: base.index(after: indexBeforeUpperBound))
}
}

private func offsetBackward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance > 0)
assert(limit < i)

if i == endIndex {
// Advance `base.endIndex` by `distance - 1`, because the index before
// `endIndex` also has `base.endIndex` as its upper bound.
//
// Advancing by 4:
//
// input: [x x x x x x x x x x] (`endIndex`)
// |< < < < <|< < <|
// output: [x x|x x x x x|x x x]

guard let upperBound = base.index(
base.endIndex,
offsetBy: -(distance - 1),
limitedBy: limit.upperBound)
else { return nil }

return Index(
lowerBound: base.index(upperBound, offsetBy: -size),
upperBound: upperBound)
} else if distance >= size {
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the upper
// bound of the output is less than or equal to the lower bound of the
// input.
//
// input: [x x x x x x x|x x x x|x]
// |< < < <|< <|
// output: [x|x x x x|x x x x x x x]

guard limit.upperBound <= i.lowerBound,
let upperBound = base.index(
i.lowerBound,
offsetBy: -(distance - size),
limitedBy: limit.upperBound)
else { return nil }

return Index(
lowerBound: base.index(upperBound, offsetBy: -size),
upperBound: upperBound)
} else {
// input: [x x x x x|x x x x x x|x]
// |< < < <| |< < < <|
// output: [x|x x x x x x|x x x x x]

guard let lowerBound = base.index(
i.lowerBound,
offsetBy: -distance,
limitedBy: limit.lowerBound)
else { return nil }

return Index(
lowerBound: lowerBound,
upperBound: base.index(i.lowerBound, offsetBy: -distance))
}
}

public func distance(from start: Index, to end: Index) -> Int {
guard start <= end else { return -distance(from: end, to: start) }
guard start != end else { return 0 }
guard end < endIndex else {
// We add 1 here because the index before `endIndex` also has
// `base.endIndex` as its upper bound.
return base[start.upperBound...].count + 1
}

if start.upperBound <= end.lowerBound {
// The distance between `start.lowerBound` and `start.upperBound` is
// already known.
//
// start: [x|x x x x|x x x x x x x]
// |- - - -|> >|
// end: [x x x x x x x|x x x x|x]

return size + base[start.upperBound..<end.lowerBound].count
} else {
// start: [x|x x x x x x|x x x x x]
// |> > > >|
// end: [x x x x x|x x x x x x|x]

return base[start.lowerBound..<end.lowerBound].count
}
}
}

extension SlidingWindows: BidirectionalCollection where Base: BidirectionalCollection {
Expand Down
20 changes: 19 additions & 1 deletion Tests/SwiftAlgorithmsTests/SlidingWindowsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//

import XCTest
import Algorithms
@testable import Algorithms

final class SlidingWindowsTests: XCTestCase {

Expand Down Expand Up @@ -88,4 +88,22 @@ final class SlidingWindowsTests: XCTestCase {
XCTAssertEqualSequences(a[i], [1, 2])
}

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),
indices: { windows in
let endIndex = windows.base.endIndex
let indices = windows.base.indices + [endIndex]
return zip(indices, indices.dropFirst(windows.size))
.map { .init(lowerBound: $0, upperBound: $1) }
+ [.init(lowerBound: endIndex, upperBound: endIndex)]
})
}
}