mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-25 04:27:47 +00:00
Implement distance(from:to:) for Chain (#3)
* Add Chain.distance(from:to:) * Add test
This commit is contained in:
1 parent
546c8bf7ba
commit
c67dd3419c
2 files changed
+39
-3
No files matched your search
@@ -209,7 +209,20 @@ extension Chain: Collection where Base1: Collection, Base2: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Add distance(from:to:)
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (start.position, end.position) {
|
||||
case let (.first(i), .first(j)):
|
||||
return base1.distance(from: i, to: j)
|
||||
case let (.second(i), .second(j)):
|
||||
return base2.distance(from: i, to: j)
|
||||
case let (.first(i), .second(j)):
|
||||
return base1.distance(from: i, to: base1.endIndex)
|
||||
+ base2.distance(from: base2.startIndex, to: j)
|
||||
case let (.second(i), .first(j)):
|
||||
return base2.distance(from: i, to: base2.startIndex)
|
||||
+ base1.distance(from: base1.endIndex, to: j)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Chain: BidirectionalCollection
|
||||
|
||||
@@ -10,9 +10,17 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
@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: Chain<A, B>) -> Chain<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 = (1...).prefix(10).chained(with: 20...)
|
||||
XCTAssertEqualSequences(run.prefix(20), Array(1...10) + (20..<30))
|
||||
@@ -35,5 +43,20 @@ final class ChainTests: XCTestCase {
|
||||
XCTAssertEqualSequences(s1.reversed().chained(with: s2), "JIHGFEDCBAklmnopqrstuv")
|
||||
}
|
||||
|
||||
// TODO: Add tests that check distance and index(offsetBy:)
|
||||
// TODO: Add tests that check index(offsetBy:)
|
||||
|
||||
func testChainDistanceFromTo() {
|
||||
let s1 = "abcde"
|
||||
let s2 = "VWXYZ"
|
||||
let chain = s1.chained(with: s2)
|
||||
|
||||
XCTAssertEqual(chain.count, s1.count + s2.count)
|
||||
|
||||
for (startOffset, endOffset) in product(0...chain.count, 0...chain.count) {
|
||||
let start = index(atOffset: startOffset, in: chain)
|
||||
let end = index(atOffset: endOffset, in: chain)
|
||||
let distance = endOffset - startOffset
|
||||
XCTAssertEqual(chain.distance(from: start, to: end), distance)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user