Compare commits

...
Author SHA1 Message Date
Nate Cook e6011cc5d0 Disrespect existing line breaks 2021-04-15 15:28:23 -05:00
Nate Cook 993b950250 Run swift-format with default settings 2021-04-15 15:04:29 -05:00
47 changed files with 1927 additions and 3218 deletions

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
{
"fileScopedDeclarationPrivacy" : {
"accessLevel" : "private"
},
"indentation" : {
"spaces" : 2
},
"indentConditionalCompilationBlocks" : true,
"indentSwitchCaseLabels" : false,
"lineBreakAroundMultilineExpressionChainComponents" : false,
"lineBreakBeforeControlFlowKeywords" : false,
"lineBreakBeforeEachArgument" : false,
"lineBreakBeforeEachGenericRequirement" : false,
"lineLength" : 100,
"maximumBlankLines" : 1,
"prioritizeKeepingFunctionOutputTogether" : false,
"respectsExistingLineBreaks" : false,
"rules" : {
"AllPublicDeclarationsHaveDocumentation" : false,
"AlwaysUseLowerCamelCase" : true,
"AmbiguousTrailingClosureOverload" : true,
"BeginDocumentationCommentWithOneLineSummary" : true,
"DoNotUseSemicolons" : true,
"DontRepeatTypeInStaticProperties" : true,
"FileScopedDeclarationPrivacy" : true,
"FullyIndirectEnum" : true,
"GroupNumericLiterals" : true,
"IdentifiersMustBeASCII" : true,
"NeverForceUnwrap" : false,
"NeverUseForceTry" : false,
"NeverUseImplicitlyUnwrappedOptionals" : false,
"NoAccessLevelOnExtensionDeclaration" : true,
"NoBlockComments" : true,
"NoCasesWithOnlyFallthrough" : true,
"NoEmptyTrailingClosureParentheses" : true,
"NoLabelsInCasePatterns" : true,
"NoLeadingUnderscores" : false,
"NoParensAroundConditions" : true,
"NoVoidReturnOnFunctionSignature" : true,
"OneCasePerLine" : true,
"OneVariableDeclarationPerLine" : true,
"OnlyOneTrailingClosureArgument" : true,
"OrderedImports" : true,
"ReturnVoidInsteadOfEmptyTuple" : true,
"UseLetInEveryBoundCaseVariable" : true,
"UseShorthandTypeNames" : true,
"UseSingleLinePropertyGetter" : true,
"UseSynthesizedInitializer" : true,
"UseTripleSlashForDocumentationComments" : true,
"ValidateDocumentationComments" : false
},
"tabWidth" : 8,
"version" : 1
}
+7 -20
View File
@@ -13,23 +13,10 @@
import PackageDescription import PackageDescription
let package = Package( let package = Package(
name: "swift-algorithms", name: "swift-algorithms", products: [.library(name: "Algorithms", targets: ["Algorithms"])],
products: [ dependencies: [.package(url: "https://github.com/apple/swift-numerics", from: "0.0.1")],
.library( targets: [
name: "Algorithms", .target(
targets: ["Algorithms"]), name: "Algorithms", dependencies: [.product(name: "RealModule", package: "swift-numerics")]),
], .testTarget(name: "SwiftAlgorithmsTests", dependencies: ["Algorithms"]),
dependencies: [ ])
.package(url: "https://github.com/apple/swift-numerics", from: "0.0.1"),
],
targets: [
.target(
name: "Algorithms",
dependencies: [
.product(name: "RealModule", package: "swift-numerics"),
]),
.testTarget(
name: "SwiftAlgorithmsTests",
dependencies: ["Algorithms"]),
]
)
+86 -147
View File
@@ -10,19 +10,14 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
/// A concatenation of two sequences with the same element type. /// A concatenation of two sequences with the same element type.
public struct Chain2<Base1: Sequence, Base2: Sequence> public struct Chain2<Base1: Sequence, Base2: Sequence> where Base1.Element == Base2.Element {
where Base1.Element == Base2.Element
{
/// The first sequence in this chain. /// The first sequence in this chain.
@usableFromInline @usableFromInline internal let base1: Base1
internal let base1: Base1
/// The second sequence in this chain.
@usableFromInline
internal let base2: Base2
@inlinable /// The second sequence in this chain.
internal init(base1: Base1, base2: Base2) { @usableFromInline internal let base2: Base2
@inlinable internal init(base1: Base1, base2: Base2) {
self.base1 = base1 self.base1 = base1
self.base2 = base2 self.base2 = base2
} }
@@ -31,28 +26,21 @@ public struct Chain2<Base1: Sequence, Base2: Sequence>
extension Chain2: Sequence { extension Chain2: Sequence {
/// The iterator for a `Chain2` sequence. /// The iterator for a `Chain2` sequence.
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline internal var iterator1: Base1.Iterator
internal var iterator1: Base1.Iterator
@usableFromInline internal var iterator2: Base2.Iterator
@usableFromInline
internal var iterator2: Base2.Iterator @inlinable internal init(_ concatenation: Chain2) {
@inlinable
internal init(_ concatenation: Chain2) {
iterator1 = concatenation.base1.makeIterator() iterator1 = concatenation.base1.makeIterator()
iterator2 = concatenation.base2.makeIterator() iterator2 = concatenation.base2.makeIterator()
} }
@inlinable @inlinable public mutating func next() -> Base1.Element? {
public mutating func next() -> Base1.Element? {
return iterator1.next() ?? iterator2.next() return iterator1.next() ?? iterator2.next()
} }
} }
@inlinable @inlinable public func makeIterator() -> Iterator { Iterator(self) }
public func makeIterator() -> Iterator {
Iterator(self)
}
} }
extension Chain2: Collection where Base1: Collection, Base2: Collection { extension Chain2: Collection where Base1: Collection, Base2: Collection {
@@ -63,134 +51,100 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
// is not to be used as a value - iterating over indices should go straight // is not to be used as a value - iterating over indices should go straight
// from the penultimate index of the first collection to the start of the // from the penultimate index of the first collection to the start of the
// second. // second.
@usableFromInline @usableFromInline internal enum Representation: Equatable {
internal enum Representation : Equatable {
case first(Base1.Index) case first(Base1.Index)
case second(Base2.Index) case second(Base2.Index)
} }
@usableFromInline @usableFromInline internal let position: Representation
internal let position: Representation
/// Creates a new index into the first underlying collection. /// Creates a new index into the first underlying collection.
@inlinable @inlinable internal init(first i: Base1.Index) { position = .first(i) }
internal init(first i: Base1.Index) {
position = .first(i)
}
/// Creates a new index into the second underlying collection. /// Creates a new index into the second underlying collection.
@inlinable @inlinable internal init(second i: Base2.Index) { position = .second(i) }
internal init(second i: Base2.Index) {
position = .second(i)
}
@inlinable @inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
public static func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs.position, rhs.position) { switch (lhs.position, rhs.position) {
case (.first, .second): case (.first, .second): return true
return true case (.second, .first): return false
case (.second, .first): case let (.first(l), .first(r)): return l < r
return false case let (.second(l), .second(r)): return l < r
case let (.first(l), .first(r)):
return l < r
case let (.second(l), .second(r)):
return l < r
} }
} }
} }
/// Converts an index of `Base1` to the corresponding `Index` by mapping /// Converts an index of `Base1` to the corresponding `Index` by mapping
/// `base1.endIndex` to `base2.startIndex`. /// `base1.endIndex` to `base2.startIndex`.
@inlinable @inlinable internal func normalizeIndex(_ i: Base1.Index) -> Index {
internal func normalizeIndex(_ i: Base1.Index) -> Index {
i == base1.endIndex ? Index(second: base2.startIndex) : Index(first: i) i == base1.endIndex ? Index(second: base2.startIndex) : Index(first: i)
} }
@inlinable @inlinable public var startIndex: Index {
public var startIndex: Index {
// if `base1` is empty, this will return `base2.startIndex` - if `base2` is // if `base1` is empty, this will return `base2.startIndex` - if `base2` is
// also empty, this will correctly equal `base2.endIndex` // also empty, this will correctly equal `base2.endIndex`
normalizeIndex(base1.startIndex) normalizeIndex(base1.startIndex)
} }
@inlinable @inlinable public var endIndex: Index { return Index(second: base2.endIndex) }
public var endIndex: Index {
return Index(second: base2.endIndex)
}
@inlinable @inlinable public subscript(i: Index) -> Base1.Element {
public subscript(i: Index) -> Base1.Element {
switch i.position { switch i.position {
case let .first(i): case let .first(i): return base1[i]
return base1[i] case let .second(i): return base2[i]
case let .second(i):
return base2[i]
} }
} }
@inlinable @inlinable public func index(after i: Index) -> Index {
public func index(after i: Index) -> Index {
switch i.position { switch i.position {
case let .first(i): case let .first(i):
assert(i != base1.endIndex) assert(i != base1.endIndex)
return normalizeIndex(base1.index(after: i)) return normalizeIndex(base1.index(after: i))
case let .second(i): case let .second(i): return Index(second: base2.index(after: i))
return Index(second: base2.index(after: i))
} }
} }
@inlinable @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i } guard distance != 0 else { return i }
return distance > 0 return distance > 0 ? offsetForward(i, by: distance) : offsetBackward(i, by: -distance)
? offsetForward(i, by: distance)
: offsetBackward(i, by: -distance)
} }
@inlinable @inlinable public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index?
public func index( {
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
if distance >= 0 { if distance >= 0 {
return limit >= i return limit >= i
? offsetForward(i, by: distance, limitedBy: limit) ? offsetForward(i, by: distance, limitedBy: limit) : offsetForward(i, by: distance)
: offsetForward(i, by: distance)
} else { } else {
return limit <= i return limit <= i
? offsetBackward(i, by: -distance, limitedBy: limit) ? offsetBackward(i, by: -distance, limitedBy: limit) : offsetBackward(i, by: -distance)
: offsetBackward(i, by: -distance)
} }
} }
@inlinable @inlinable internal func offsetForward(_ i: Index, by distance: Int) -> Index {
internal func offsetForward(_ i: Index, by distance: Int) -> Index { guard let index = offsetForward(i, by: distance, limitedBy: endIndex) else {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex) fatalError("Index is out of bounds")
else { fatalError("Index is out of bounds") } }
return index
}
@inlinable
internal 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 return index
} }
@inlinable @inlinable internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
internal func offsetForward( guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) else {
_ i: Index, by distance: Int, limitedBy limit: Index fatalError("Index is out of bounds")
) -> Index? { }
return index
}
@inlinable internal func offsetForward(_ i: Index, by distance: Int, limitedBy limit: Index)
-> Index?
{
assert(distance >= 0) assert(distance >= 0)
assert(limit >= i) assert(limit >= i)
switch (i.position, limit.position) { switch (i.position, limit.position) {
case let (.first(i), .first(limit)): case let (.first(i), .first(limit)):
return base1.index(i, offsetBy: distance, limitedBy: limit) return base1.index(i, offsetBy: distance, limitedBy: limit).map(Index.init(first:))
.map(Index.init(first:))
case let (.first(i), .second(limit)): case let (.first(i), .second(limit)):
if let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) { if let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) {
// the offset stays within the bounds of `base1` // the offset stays within the bounds of `base1`
@@ -198,36 +152,33 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
} else { } else {
// the offset overflows the bounds of `base1` by `n - d` // the offset overflows the bounds of `base1` by `n - d`
let d = base1.distance(from: i, to: base1.endIndex) let d = base1.distance(from: i, to: base1.endIndex)
return base2.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit) return base2.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit).map(
.map(Index.init(second:)) Index.init(second:))
} }
case (.second, .first): case (.second, .first):
// impossible because `limit >= i` // impossible because `limit >= i`
fatalError() fatalError()
case let (.second(i), .second(limit)): case let (.second(i), .second(limit)):
return base2.index(i, offsetBy: distance, limitedBy: limit) return base2.index(i, offsetBy: distance, limitedBy: limit).map(Index.init(second:))
.map(Index.init(second:))
} }
} }
@inlinable @inlinable internal func offsetBackward(_ i: Index, by distance: Int, limitedBy limit: Index)
internal func offsetBackward( -> Index?
_ i: Index, by distance: Int, limitedBy limit: Index {
) -> Index? {
assert(distance >= 0) assert(distance >= 0)
assert(limit <= i) assert(limit <= i)
switch (i.position, limit.position) { switch (i.position, limit.position) {
case let (.first(i), .first(limit)): case let (.first(i), .first(limit)):
return base1.index(i, offsetBy: -distance, limitedBy: limit) return base1.index(i, offsetBy: -distance, limitedBy: limit).map(Index.init(first:))
.map(Index.init(first:))
case (.first, .second): case (.first, .second):
// impossible because `limit <= i` // impossible because `limit <= i`
fatalError() fatalError()
case let (.second(i), .first(limit)): case let (.second(i), .first(limit)):
if let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex) { if let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex) {
// the offset stays within the bounds of `base2` // the offset stays within the bounds of `base2`
@@ -235,24 +186,20 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
} else { } else {
// the offset overflows the bounds of `base2` by `n - d` // the offset overflows the bounds of `base2` by `n - d`
let d = base2.distance(from: base2.startIndex, to: i) let d = base2.distance(from: base2.startIndex, to: i)
return base1.index(base1.endIndex, offsetBy: -(distance - d), limitedBy: limit) return base1.index(base1.endIndex, offsetBy: -(distance - d), limitedBy: limit).map(
.map(Index.init(first:)) Index.init(first:))
} }
case let (.second(i), .second(limit)): case let (.second(i), .second(limit)):
// `limit` is relevant, so `base1` cannot be reached // `limit` is relevant, so `base1` cannot be reached
return base2.index(i, offsetBy: -distance, limitedBy: limit) return base2.index(i, offsetBy: -distance, limitedBy: limit).map(Index.init(second:))
.map(Index.init(second:))
} }
} }
@inlinable @inlinable public func distance(from start: Index, to end: Index) -> Int {
public func distance(from start: Index, to end: Index) -> Int {
switch (start.position, end.position) { switch (start.position, end.position) {
case let (.first(i), .first(j)): case let (.first(i), .first(j)): return base1.distance(from: i, to: j)
return base1.distance(from: i, to: j) case let (.second(i), .second(j)): return base2.distance(from: i, to: j)
case let (.second(i), .second(j)):
return base2.distance(from: i, to: j)
case let (.first(i), .second(j)): case let (.first(i), .second(j)):
return base1.distance(from: i, to: base1.endIndex) return base1.distance(from: i, to: base1.endIndex)
+ base2.distance(from: base2.startIndex, to: j) + base2.distance(from: base2.startIndex, to: j)
@@ -264,24 +211,20 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
} }
extension Chain2: BidirectionalCollection extension Chain2: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
{ @inlinable public func index(before i: Index) -> Index {
@inlinable
public func index(before i: Index) -> Index {
assert(i != startIndex, "Can't advance before startIndex") assert(i != startIndex, "Can't advance before startIndex")
switch i.position { switch i.position {
case let .first(i): case let .first(i): return Index(first: base1.index(before: i))
return Index(first: base1.index(before: i))
case let .second(i): case let .second(i):
return i == base2.startIndex return i == base2.startIndex
? Index(first: base1.index(before: base1.endIndex)) ? Index(first: base1.index(before: base1.endIndex)) : Index(second: base2.index(before: i))
: Index(second: base2.index(before: i))
} }
} }
} }
extension Chain2: RandomAccessCollection extension Chain2: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {} where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// chain(_:_:) // chain(_:_:)
@@ -313,21 +256,17 @@ extension Chain2: RandomAccessCollection
/// then over the elements of `s2`. /// then over the elements of `s2`.
/// ///
/// - Complexity: O(1) /// - Complexity: O(1)
@inlinable @inlinable public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2<S1, S2> {
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2<S1, S2> {
Chain2(base1: s1, base2: s2) Chain2(base1: s1, base2: s2)
} }
// MARK: - Deprecations // MARK: - Deprecations
@available(*, deprecated, renamed: "Chain2") @available(*, deprecated, renamed: "Chain2") public typealias Chain = Chain2
public typealias Chain = Chain2
extension Sequence { extension Sequence {
@available(*, deprecated, message: "Use the chain(_:_:) function, instead.") @available(*, deprecated, message: "Use the chain(_:_:) function, instead.")
public func chained<S: Sequence>(with other: S) -> Chain2<Self, S> public func chained<S: Sequence>(with other: S) -> Chain2<Self, S> where Element == S.Element {
where Element == S.Element
{
Chain2(base1: self, base2: other) Chain2(base1: self, base2: other)
} }
} }
+143 -252
View File
@@ -13,35 +13,27 @@
/// predicate or projection. /// predicate or projection.
public struct Chunked<Base: Collection, Subject> { public struct Chunked<Base: Collection, Subject> {
/// The collection that this instance provides a view onto. /// The collection that this instance provides a view onto.
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
/// The projection function. /// The projection function.
@usableFromInline @usableFromInline internal let projection: (Base.Element) -> Subject
internal let projection: (Base.Element) -> Subject
/// The predicate. /// The predicate.
@usableFromInline @usableFromInline internal let belongInSameGroup: (Subject, Subject) -> Bool
internal let belongInSameGroup: (Subject, Subject) -> Bool
/// The upper bound of the first chunk. /// The upper bound of the first chunk.
@usableFromInline @usableFromInline internal var firstUpperBound: Base.Index
internal var firstUpperBound: Base.Index
@inlinable internal init(
@inlinable base: Base, projection: @escaping (Base.Element) -> Subject,
internal init(
base: Base,
projection: @escaping (Base.Element) -> Subject,
belongInSameGroup: @escaping (Subject, Subject) -> Bool belongInSameGroup: @escaping (Subject, Subject) -> Bool
) { ) {
self.base = base self.base = base
self.projection = projection self.projection = projection
self.belongInSameGroup = belongInSameGroup self.belongInSameGroup = belongInSameGroup
self.firstUpperBound = base.startIndex self.firstUpperBound = base.startIndex
if !base.isEmpty { if !base.isEmpty { firstUpperBound = endOfChunk(startingAt: base.startIndex) }
firstUpperBound = endOfChunk(startingAt: base.startIndex)
}
} }
} }
@@ -49,23 +41,17 @@ extension Chunked: LazyCollectionProtocol {
/// A position in a chunked collection. /// A position in a chunked collection.
public struct Index: Comparable { public struct Index: Comparable {
/// The range corresponding to the chunk at this position. /// The range corresponding to the chunk at this position.
@usableFromInline @usableFromInline internal var baseRange: Range<Base.Index>
internal var baseRange: Range<Base.Index>
@inlinable internal init(_ baseRange: Range<Base.Index>) { self.baseRange = baseRange }
@inlinable
internal init(_ baseRange: Range<Base.Index>) { @inlinable public static func == (lhs: Index, rhs: Index) -> Bool {
self.baseRange = baseRange
}
@inlinable
public static func == (lhs: Index, rhs: Index) -> Bool {
// Since each index represents the range of a disparate chunk, no two // Since each index represents the range of a disparate chunk, no two
// unique indices will have the same lower bound. // unique indices will have the same lower bound.
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
} }
@inlinable @inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
public static func < (lhs: Index, rhs: Index) -> Bool {
// Only use the lower bound to test for ordering, as above. // Only use the lower bound to test for ordering, as above.
lhs.baseRange.lowerBound < rhs.baseRange.lowerBound lhs.baseRange.lowerBound < rhs.baseRange.lowerBound
} }
@@ -73,34 +59,26 @@ extension Chunked: LazyCollectionProtocol {
/// Returns the index in the base collection of the end of the chunk starting /// Returns the index in the base collection of the end of the chunk starting
/// at the given index. /// at the given index.
@inlinable @inlinable internal func endOfChunk(startingAt start: Base.Index) -> Base.Index {
internal func endOfChunk(startingAt start: Base.Index) -> Base.Index {
let subject = projection(base[start]) let subject = projection(base[start])
return base[base.index(after: start)...] return base[base.index(after: start)...].endOfPrefix(while: {
.endOfPrefix(while: { belongInSameGroup(subject, projection($0)) }) belongInSameGroup(subject, projection($0))
})
} }
@inlinable @inlinable public var startIndex: Index { Index(base.startIndex..<firstUpperBound) }
public var startIndex: Index {
Index(base.startIndex..<firstUpperBound) @inlinable public var endIndex: Index { Index(base.endIndex..<base.endIndex) }
}
@inlinable public func index(after i: Index) -> Index {
@inlinable
public var endIndex: Index {
Index(base.endIndex..<base.endIndex)
}
@inlinable
public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance past endIndex") precondition(i != endIndex, "Can't advance past endIndex")
let upperBound = i.baseRange.upperBound let upperBound = i.baseRange.upperBound
guard upperBound != base.endIndex else { return endIndex } guard upperBound != base.endIndex else { return endIndex }
let end = endOfChunk(startingAt: upperBound) let end = endOfChunk(startingAt: upperBound)
return Index(upperBound..<end) return Index(upperBound..<end)
} }
@inlinable @inlinable public subscript(position: Index) -> Base.SubSequence {
public subscript(position: Index) -> Base.SubSequence {
precondition(position != endIndex, "Can't subscript using endIndex") precondition(position != endIndex, "Can't subscript using endIndex")
return base[position.baseRange] return base[position.baseRange]
} }
@@ -108,31 +86,29 @@ extension Chunked: LazyCollectionProtocol {
extension Chunked.Index: Hashable where Base.Index: Hashable {} extension Chunked.Index: Hashable where Base.Index: Hashable {}
extension Chunked: BidirectionalCollection extension Chunked: BidirectionalCollection where Base: BidirectionalCollection {
where Base: BidirectionalCollection
{
/// Returns the index in the base collection of the start of the chunk ending /// Returns the index in the base collection of the start of the chunk ending
/// at the given index. /// at the given index.
@inlinable @inlinable internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
let indexBeforeEnd = base.index(before: end) let indexBeforeEnd = base.index(before: end)
// Get the projected value of the last element in the range ending at `end`. // Get the projected value of the last element in the range ending at `end`.
let subject = projection(base[indexBeforeEnd]) let subject = projection(base[indexBeforeEnd])
return base[..<indexBeforeEnd] return base[..<indexBeforeEnd].startOfSuffix(while: {
.startOfSuffix(while: { belongInSameGroup(projection($0), subject) }) belongInSameGroup(projection($0), subject)
})
} }
@inlinable @inlinable public func index(before i: Index) -> Index {
public func index(before i: Index) -> Index {
precondition(i != startIndex, "Can't advance before startIndex") precondition(i != startIndex, "Can't advance before startIndex")
let start = startOfChunk(endingAt: i.baseRange.lowerBound) let start = startOfChunk(endingAt: i.baseRange.lowerBound)
return Index(start..<i.baseRange.lowerBound) return Index(start..<i.baseRange.lowerBound)
} }
} }
@available(*, deprecated, renamed: "Chunked") @available(*, deprecated, renamed: "Chunked") public typealias LazyChunked<
public typealias LazyChunked<Base: Collection, Subject> = Chunked<Base, Subject> Base: Collection, Subject
> = Chunked<Base, Subject>
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// lazy.chunked(by:) // lazy.chunked(by:)
@@ -143,29 +119,17 @@ extension LazyCollectionProtocol {
/// the given predicate. /// the given predicate.
/// ///
/// - Complexity: O(*n*), because the start index is pre-computed. /// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable @inlinable public func chunked(by belongInSameGroup: @escaping (Element, Element) -> Bool)
public func chunked( -> Chunked<Elements, Element>
by belongInSameGroup: @escaping (Element, Element) -> Bool { Chunked(base: elements, projection: { $0 }, belongInSameGroup: belongInSameGroup) }
) -> Chunked<Elements, Element> {
Chunked(
base: elements,
projection: { $0 },
belongInSameGroup: belongInSameGroup)
}
/// Returns a lazy collection of subsequences of this collection, chunked by /// Returns a lazy collection of subsequences of this collection, chunked by
/// grouping elements that project to the same value. /// grouping elements that project to the same value.
/// ///
/// - Complexity: O(*n*), because the start index is pre-computed. /// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable @inlinable public func chunked<Subject: Equatable>(on projection: @escaping (Element) -> Subject)
public func chunked<Subject: Equatable>( -> Chunked<Elements, Subject>
on projection: @escaping (Element) -> Subject { Chunked(base: elements, projection: projection, belongInSameGroup: ==) }
) -> Chunked<Elements, Subject> {
Chunked(
base: elements,
projection: projection,
belongInSameGroup: ==)
}
} }
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
@@ -178,17 +142,16 @@ extension Collection {
/// predicate. /// predicate.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable @inlinable internal func chunked<Subject>(
internal func chunked<Subject>(
on projection: (Element) throws -> Subject, on projection: (Element) throws -> Subject,
by belongInSameGroup: (Subject, Subject) throws -> Bool by belongInSameGroup: (Subject, Subject) throws -> Bool
) rethrows -> [SubSequence] { ) rethrows -> [SubSequence] {
guard !isEmpty else { return [] } guard !isEmpty else { return [] }
var result: [SubSequence] = [] var result: [SubSequence] = []
var start = startIndex var start = startIndex
var subject = try projection(self[start]) var subject = try projection(self[start])
for (index, element) in indexed().dropFirst() { for (index, element) in indexed().dropFirst() {
let nextSubject = try projection(element) let nextSubject = try projection(element)
if try !belongInSameGroup(subject, nextSubject) { if try !belongInSameGroup(subject, nextSubject) {
@@ -197,35 +160,27 @@ extension Collection {
subject = nextSubject subject = nextSubject
} }
} }
if start != endIndex { if start != endIndex { result.append(self[start..<endIndex]) }
result.append(self[start..<endIndex])
}
return result return result
} }
/// Returns a collection of subsequences of this collection, chunked by /// Returns a collection of subsequences of this collection, chunked by
/// the given predicate. /// the given predicate.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable @inlinable public func chunked(by belongInSameGroup: (Element, Element) throws -> Bool) rethrows
public func chunked( -> [SubSequence]
by belongInSameGroup: (Element, Element) throws -> Bool { try chunked(on: { $0 }, by: belongInSameGroup) }
) rethrows -> [SubSequence] {
try chunked(on: { $0 }, by: belongInSameGroup)
}
/// Returns a collection of subsequences of this collection, chunked by /// Returns a collection of subsequences of this collection, chunked by
/// grouping elements that project to the same value. /// grouping elements that project to the same value.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable @inlinable public func chunked<Subject: Equatable>(on projection: (Element) throws -> Subject)
public func chunked<Subject: Equatable>( rethrows -> [SubSequence]
on projection: (Element) throws -> Subject { try chunked(on: projection, by: ==) }
) rethrows -> [SubSequence] {
try chunked(on: projection, by: ==)
}
} }
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
@@ -242,181 +197,133 @@ extension Collection {
/// * `c.chunks(ofCount: 3).map(f)` maps eagerly and returns a new array /// * `c.chunks(ofCount: 3).map(f)` maps eagerly and returns a new array
/// * `c.lazy.chunks(ofCount: 3).map(f)` maps lazily and returns a `LazyMapCollection` /// * `c.lazy.chunks(ofCount: 3).map(f)` maps lazily and returns a `LazyMapCollection`
public struct ChunkedByCount<Base: Collection> { public struct ChunkedByCount<Base: Collection> {
public typealias Element = Base.SubSequence public typealias Element = Base.SubSequence
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline internal let chunkCount: Int
@usableFromInline
internal let chunkCount: Int @usableFromInline internal var startUpperBound: Base.Index
@usableFromInline
internal var startUpperBound: Base.Index
/// Creates a view instance that presents the elements of `base` /// Creates a view instance that presents the elements of `base`
/// in `SubSequence` chunks of the given count. /// in `SubSequence` chunks of the given count.
/// ///
/// - Complexity: O(*n*), because the start index is pre-computed. /// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable @inlinable internal init(_base: Base, _chunkCount: Int) {
internal init(_base: Base, _chunkCount: Int) {
self.base = _base self.base = _base
self.chunkCount = _chunkCount self.chunkCount = _chunkCount
// Compute the start index upfront in order to make // Compute the start index upfront in order to make
// start index a O(1) lookup. // start index a O(1) lookup.
self.startUpperBound = _base.index( self.startUpperBound =
_base.startIndex, offsetBy: _chunkCount, _base.index(_base.startIndex, offsetBy: _chunkCount, limitedBy: _base.endIndex)
limitedBy: _base.endIndex ?? _base.endIndex
) ?? _base.endIndex
} }
} }
extension ChunkedByCount: Collection { extension ChunkedByCount: Collection {
public struct Index { public struct Index {
@usableFromInline @usableFromInline internal let baseRange: Range<Base.Index>
internal let baseRange: Range<Base.Index>
@inlinable internal init(_baseRange: Range<Base.Index>) { self.baseRange = _baseRange }
@inlinable
internal init(_baseRange: Range<Base.Index>) {
self.baseRange = _baseRange
}
} }
/// - Complexity: O(1) /// - Complexity: O(1)
@inlinable @inlinable public var startIndex: Index { Index(_baseRange: base.startIndex..<startUpperBound) }
public var startIndex: Index { @inlinable public var endIndex: Index { Index(_baseRange: base.endIndex..<base.endIndex) }
Index(_baseRange: base.startIndex..<startUpperBound)
}
@inlinable
public var endIndex: Index {
Index(_baseRange: base.endIndex..<base.endIndex)
}
/// - Complexity: O(1) /// - Complexity: O(1)
@inlinable @inlinable public subscript(i: Index) -> Element {
public subscript(i: Index) -> Element {
precondition(i < endIndex, "Index out of range") precondition(i < endIndex, "Index out of range")
return base[i.baseRange] return base[i.baseRange]
} }
@inlinable @inlinable public func index(after i: Index) -> Index {
public func index(after i: Index) -> Index {
precondition(i < endIndex, "Advancing past end index") precondition(i < endIndex, "Advancing past end index")
let baseIdx = base.index( let baseIdx =
i.baseRange.upperBound, offsetBy: chunkCount, base.index(i.baseRange.upperBound, offsetBy: chunkCount, limitedBy: base.endIndex)
limitedBy: base.endIndex ?? base.endIndex
) ?? base.endIndex
return Index(_baseRange: i.baseRange.upperBound..<baseIdx) return Index(_baseRange: i.baseRange.upperBound..<baseIdx)
} }
} }
extension ChunkedByCount.Index: Comparable { extension ChunkedByCount.Index: Comparable {
@inlinable @inlinable public static func == (lhs: ChunkedByCount.Index, rhs: ChunkedByCount.Index) -> Bool {
public static func == (lhs: ChunkedByCount.Index,
rhs: ChunkedByCount.Index) -> Bool {
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
} }
@inlinable @inlinable public static func < (lhs: ChunkedByCount.Index, rhs: ChunkedByCount.Index) -> Bool {
public static func < (lhs: ChunkedByCount.Index,
rhs: ChunkedByCount.Index) -> Bool {
lhs.baseRange.lowerBound < rhs.baseRange.lowerBound lhs.baseRange.lowerBound < rhs.baseRange.lowerBound
} }
} }
extension ChunkedByCount: extension ChunkedByCount: BidirectionalCollection, RandomAccessCollection
BidirectionalCollection, RandomAccessCollection
where Base: RandomAccessCollection { where Base: RandomAccessCollection {
@inlinable @inlinable public func index(before i: Index) -> Index {
public func index(before i: Index) -> Index {
precondition(i > startIndex, "Advancing past start index") precondition(i > startIndex, "Advancing past start index")
var offset = chunkCount var offset = chunkCount
if i.baseRange.lowerBound == base.endIndex { if i.baseRange.lowerBound == base.endIndex {
let remainder = base.count%chunkCount let remainder = base.count % chunkCount
if remainder != 0 { if remainder != 0 { offset = remainder }
offset = remainder
}
} }
let baseIdx = base.index( let baseIdx =
i.baseRange.lowerBound, offsetBy: -offset, base.index(i.baseRange.lowerBound, offsetBy: -offset, limitedBy: base.startIndex)
limitedBy: base.startIndex ?? base.startIndex
) ?? base.startIndex
return Index(_baseRange: baseIdx..<i.baseRange.lowerBound) return Index(_baseRange: baseIdx..<i.baseRange.lowerBound)
} }
} }
extension ChunkedByCount { extension ChunkedByCount {
@inlinable @inlinable public func distance(from start: Index, to end: Index) -> Int {
public func distance(from start: Index, to end: Index) -> Int { let distance = base.distance(from: start.baseRange.lowerBound, to: end.baseRange.lowerBound)
let distance = let (quotient, remainder) = distance.quotientAndRemainder(dividingBy: chunkCount)
base.distance(from: start.baseRange.lowerBound,
to: end.baseRange.lowerBound)
let (quotient, remainder) =
distance.quotientAndRemainder(dividingBy: chunkCount)
return quotient + remainder.signum() return quotient + remainder.signum()
} }
@inlinable @inlinable public var count: Int {
public var count: Int { let (quotient, remainder) = base.count.quotientAndRemainder(dividingBy: chunkCount)
let (quotient, remainder) =
base.count.quotientAndRemainder(dividingBy: chunkCount)
return quotient + remainder.signum() return quotient + remainder.signum()
} }
@inlinable @inlinable public func index(_ i: Index, offsetBy offset: Int, limitedBy limit: Index) -> Index? {
public func index(
_ i: Index, offsetBy offset: Int, limitedBy limit: Index
) -> Index? {
guard offset != 0 else { return i } guard offset != 0 else { return i }
guard limit != i else { return nil } guard limit != i else { return nil }
if offset > 0 { if offset > 0 {
return limit > i return limit > i
? offsetForward(i, offsetBy: offset, limit: limit) ? offsetForward(i, offsetBy: offset, limit: limit) : offsetForward(i, offsetBy: offset)
: offsetForward(i, offsetBy: offset)
} else { } else {
return limit < i return limit < i
? offsetBackward(i, offsetBy: offset, limit: limit) ? offsetBackward(i, offsetBy: offset, limit: limit) : offsetBackward(i, offsetBy: offset)
: offsetBackward(i, offsetBy: offset)
} }
} }
@inlinable @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i } guard distance != 0 else { return i }
let idx = distance > 0 let idx =
? offsetForward(i, offsetBy: distance) distance > 0 ? offsetForward(i, offsetBy: distance) : offsetBackward(i, offsetBy: distance)
: offsetBackward(i, offsetBy: distance) guard let index = idx else { fatalError("Out of bounds") }
guard let index = idx else {
fatalError("Out of bounds")
}
return index return index
} }
@inlinable @inlinable internal func offsetForward(_ i: Index, offsetBy distance: Int, limit: Index? = nil)
internal func offsetForward( -> Index?
_ i: Index, offsetBy distance: Int, limit: Index? = nil {
) -> Index? {
assert(distance > 0) assert(distance > 0)
return makeOffsetIndex( return makeOffsetIndex(
from: i, baseBound: base.endIndex, from: i, baseBound: base.endIndex, distance: distance, baseDistance: distance * chunkCount,
distance: distance, baseDistance: distance * chunkCount, limit: limit, by: >)
limit: limit, by: >
)
} }
// Convenience to compute offset backward base distance. // Convenience to compute offset backward base distance.
@inlinable @inlinable internal func computeOffsetBackwardBaseDistance(_ i: Index, _ distance: Int) -> Int {
internal func computeOffsetBackwardBaseDistance(
_ i: Index, _ distance: Int
) -> Int {
if i == endIndex { if i == endIndex {
let remainder = base.count%chunkCount let remainder = base.count % chunkCount
// We have to take it into account when calculating offsets. // We have to take it into account when calculating offsets.
if remainder != 0 { if remainder != 0 {
// Distance "minus" one(at this point distance is negative) // Distance "minus" one(at this point distance is negative)
@@ -427,32 +334,24 @@ extension ChunkedByCount {
} }
return distance * chunkCount return distance * chunkCount
} }
@inlinable @inlinable internal func offsetBackward(_ i: Index, offsetBy distance: Int, limit: Index? = nil)
internal func offsetBackward( -> Index?
_ i: Index, offsetBy distance: Int, limit: Index? = nil {
) -> Index? {
assert(distance < 0) assert(distance < 0)
let baseDistance = let baseDistance = computeOffsetBackwardBaseDistance(i, distance)
computeOffsetBackwardBaseDistance(i, distance)
return makeOffsetIndex( return makeOffsetIndex(
from: i, baseBound: base.startIndex, from: i, baseBound: base.startIndex, distance: distance, baseDistance: baseDistance,
distance: distance, baseDistance: baseDistance, limit: limit, by: <)
limit: limit, by: <
)
} }
// Helper to compute index(offsetBy:) index. // Helper to compute index(offsetBy:) index.
@inlinable @inlinable internal func makeOffsetIndex(
internal func makeOffsetIndex( from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int, limit: Index?,
from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int, by limitFn: (Base.Index, Base.Index) -> Bool
limit: Index?, by limitFn: (Base.Index, Base.Index) -> Bool
) -> Index? { ) -> Index? {
let baseIdx = base.index( let baseIdx = base.index(i.baseRange.lowerBound, offsetBy: baseDistance, limitedBy: baseBound)
i.baseRange.lowerBound, offsetBy: baseDistance,
limitedBy: baseBound
)
if let limit = limit { if let limit = limit {
if baseIdx == nil { if baseIdx == nil {
// If we past the bounds while advancing forward and the // If we past the bounds while advancing forward and the
@@ -464,9 +363,7 @@ extension ChunkedByCount {
// non-random access collection base) to compute the base // non-random access collection base) to compute the base
// distance taking remainder into account. // distance taking remainder into account.
if baseDistance > 0 && limit == endIndex { if baseDistance > 0 && limit == endIndex {
if self.distance(from: i, to: limit) < distance { if self.distance(from: i, to: limit) < distance { return nil }
return nil
}
} else { } else {
return nil return nil
} }
@@ -474,16 +371,13 @@ extension ChunkedByCount {
// Checks for the limit. // Checks for the limit.
let baseStartIdx = baseIdx ?? baseBound let baseStartIdx = baseIdx ?? baseBound
if limitFn(baseStartIdx, limit.baseRange.lowerBound) { if limitFn(baseStartIdx, limit.baseRange.lowerBound) { return nil }
return nil
}
} }
let baseStartIdx = baseIdx ?? baseBound let baseStartIdx = baseIdx ?? baseBound
let baseEndIdx = base.index( let baseEndIdx =
baseStartIdx, offsetBy: chunkCount, limitedBy: base.endIndex base.index(baseStartIdx, offsetBy: chunkCount, limitedBy: base.endIndex) ?? base.endIndex
) ?? base.endIndex
return Index(_baseRange: baseStartIdx..<baseEndIdx) return Index(_baseRange: baseStartIdx..<baseEndIdx)
} }
} }
@@ -505,8 +399,7 @@ extension Collection {
/// // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] /// // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
/// ///
/// - Complexity: O(*n*), because the start index is pre-computed. /// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable @inlinable public func chunks(ofCount count: Int) -> ChunkedByCount<Self> {
public func chunks(ofCount count: Int) -> ChunkedByCount<Self> {
precondition(count > 0, "Cannot chunk with count <= 0!") precondition(count > 0, "Cannot chunk with count <= 0!")
return ChunkedByCount(_base: self, _chunkCount: count) return ChunkedByCount(_base: self, _chunkCount: count)
} }
@@ -515,7 +408,5 @@ extension Collection {
extension ChunkedByCount.Index: Hashable where Base.Index: Hashable {} extension ChunkedByCount.Index: Hashable where Base.Index: Hashable {}
// Lazy conditional conformance. // Lazy conditional conformance.
extension ChunkedByCount: LazySequenceProtocol extension ChunkedByCount: LazySequenceProtocol where Base: LazySequenceProtocol {}
where Base: LazySequenceProtocol {} extension ChunkedByCount: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
extension ChunkedByCount: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
+41 -75
View File
@@ -12,55 +12,41 @@
/// A collection wrapper that generates combinations of a base collection. /// A collection wrapper that generates combinations of a base collection.
public struct Combinations<Base: Collection> { public struct Combinations<Base: Collection> {
/// The collection to iterate over for combinations. /// The collection to iterate over for combinations.
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline internal let baseCount: Int
@usableFromInline
internal let baseCount: Int
/// The range of accepted sizes of combinations. /// The range of accepted sizes of combinations.
/// - Note: This may be `nil` if the attempted range entirely exceeds the /// - Note: This may be `nil` if the attempted range entirely exceeds the
/// upper bounds of the size of the `base` collection. /// upper bounds of the size of the `base` collection.
@usableFromInline @usableFromInline internal let kRange: Range<Int>?
internal let kRange: Range<Int>?
/// Initializes a `Combinations` for all combinations of `base` of size `k`. /// Initializes a `Combinations` for all combinations of `base` of size `k`.
/// - Parameters: /// - Parameters:
/// - base: The collection to iterate over for combinations. /// - base: The collection to iterate over for combinations.
/// - k: The expected size of each combination. /// - k: The expected size of each combination.
@inlinable @inlinable internal init(_ base: Base, k: Int) { self.init(base, kRange: k...k) }
internal init(_ base: Base, k: Int) {
self.init(base, kRange: k...k)
}
/// Initializes a `Combinations` for all combinations of `base` of sizes /// Initializes a `Combinations` for all combinations of `base` of sizes
/// within a given range. /// within a given range.
/// - Parameters: /// - Parameters:
/// - base: The collection to iterate over for combinations. /// - base: The collection to iterate over for combinations.
/// - kRange: The range of accepted sizes of combinations. /// - kRange: The range of accepted sizes of combinations.
@inlinable @inlinable internal init<R: RangeExpression>(_ base: Base, kRange: R) where R.Bound == Int {
internal init<R: RangeExpression>(
_ base: Base, kRange: R
) where R.Bound == Int {
let range = kRange.relative(to: 0 ..< .max) let range = kRange.relative(to: 0 ..< .max)
self.base = base self.base = base
let baseCount = base.count let baseCount = base.count
self.baseCount = baseCount self.baseCount = baseCount
let upperBound = baseCount + 1 let upperBound = baseCount + 1
self.kRange = range.lowerBound < upperBound self.kRange = range.lowerBound < upperBound ? range.clamped(to: 0..<upperBound) : nil
? range.clamped(to: 0 ..< upperBound)
: nil
} }
/// The total number of combinations. /// The total number of combinations.
@inlinable @inlinable public var count: Int {
public var count: Int {
guard let k = self.kRange else { return 0 } guard let k = self.kRange else { return 0 }
let n = baseCount let n = baseCount
if k == 0 ..< (n + 1) { if k == 0..<(n + 1) { return 1 << n }
return 1 << n
}
func binomial(n: Int, k: Int) -> Int { func binomial(n: Int, k: Int) -> Int {
switch k { switch k {
case n, 0: return 1 case n, 0: return 1
@@ -69,42 +55,33 @@ public struct Combinations<Base: Collection> {
default: return n * binomial(n: n - 1, k: k - 1) / k default: return n * binomial(n: n - 1, k: k - 1) / k
} }
} }
return k.map { return k.map { binomial(n: n, k: $0) }.reduce(0, +)
binomial(n: n, k: $0)
}.reduce(0, +)
} }
} }
extension Combinations: Sequence { extension Combinations: Sequence {
/// The iterator for a `Combinations` instance. /// The iterator for a `Combinations` instance.
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
/// The current range of accepted sizes of combinations. /// The current range of accepted sizes of combinations.
/// - Note: The range is contracted until empty while iterating over /// - Note: The range is contracted until empty while iterating over
/// combinations of different sizes. When the range is empty, iteration is /// combinations of different sizes. When the range is empty, iteration is
/// finished. /// finished.
@usableFromInline @usableFromInline internal var kRange: Range<Int>
internal var kRange: Range<Int>
/// Whether or not iteration is finished (`kRange` is empty) /// Whether or not iteration is finished (`kRange` is empty)
@inlinable @inlinable internal var isFinished: Bool { return kRange.isEmpty }
internal var isFinished: Bool {
return kRange.isEmpty @usableFromInline internal var indexes: [Base.Index]
}
@inlinable internal init(_ combinations: Combinations) {
@usableFromInline
internal var indexes: [Base.Index]
@inlinable
internal init(_ combinations: Combinations) {
self.base = combinations.base self.base = combinations.base
self.kRange = combinations.kRange ?? 0..<0 self.kRange = combinations.kRange ?? 0..<0
self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound)) self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound))
} }
/// Advances the current indices to the next set of combinations. If /// Advances the current indices to the next set of combinations. If
/// `indexes.count == 3` and `base.count == 5`, the indices advance like /// `indexes.count == 3` and `base.count == 5`, the indices advance like
/// this: /// this:
@@ -123,19 +100,18 @@ extension Combinations: Sequence {
/// [2, 3, 4] * /// [2, 3, 4] *
/// // Can't advance without needing to go past `base.endIndex`, /// // Can't advance without needing to go past `base.endIndex`,
/// // so the iteration is finished. /// // so the iteration is finished.
@inlinable @inlinable internal mutating func advance() {
internal mutating func advance() {
/// Advances `kRange` by incrementing its `lowerBound` until the range is /// Advances `kRange` by incrementing its `lowerBound` until the range is
/// empty, when iteration is finished. /// empty, when iteration is finished.
func advanceKRange() { func advanceKRange() {
if kRange.lowerBound < kRange.upperBound { if kRange.lowerBound < kRange.upperBound {
let advancedLowerBound = kRange.lowerBound + 1 let advancedLowerBound = kRange.lowerBound + 1
kRange = advancedLowerBound ..< kRange.upperBound kRange = advancedLowerBound..<kRange.upperBound
indexes.removeAll(keepingCapacity: true) indexes.removeAll(keepingCapacity: true)
indexes.append(contentsOf: base.indices.prefix(kRange.lowerBound)) indexes.append(contentsOf: base.indices.prefix(kRange.lowerBound))
} }
} }
guard !indexes.isEmpty else { guard !indexes.isEmpty else {
// Initial state for combinations of 0 elements is an empty array with // Initial state for combinations of 0 elements is an empty array with
// `finished == false`. Even though no indexes are involved, advancing // `finished == false`. Even though no indexes are involved, advancing
@@ -143,11 +119,11 @@ extension Combinations: Sequence {
advanceKRange() advanceKRange()
return return
} }
let i = indexes.count - 1 let i = indexes.count - 1
base.formIndex(after: &indexes[i]) base.formIndex(after: &indexes[i])
if indexes[i] != base.endIndex { return } if indexes[i] != base.endIndex { return }
var j = i var j = i
while indexes[i] == base.endIndex { while indexes[i] == base.endIndex {
j -= 1 j -= 1
@@ -156,28 +132,23 @@ extension Combinations: Sequence {
advanceKRange() advanceKRange()
return return
} }
base.formIndex(after: &indexes[j]) base.formIndex(after: &indexes[j])
for k in indexes.indices[(j + 1)...] { for k in indexes.indices[(j + 1)...] {
indexes[k] = base.index(after: indexes[k - 1]) indexes[k] = base.index(after: indexes[k - 1])
if indexes[k] == base.endIndex { if indexes[k] == base.endIndex { break }
break
}
} }
} }
} }
@inlinable @inlinable public mutating func next() -> [Base.Element]? {
public mutating func next() -> [Base.Element]? {
guard !isFinished else { return nil } guard !isFinished else { return nil }
defer { advance() } defer { advance() }
return indexes.map { i in base[i] } return indexes.map { i in base[i] }
} }
} }
public func makeIterator() -> Iterator { public func makeIterator() -> Iterator { Iterator(self) }
Iterator(self)
}
} }
extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {} extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {}
@@ -248,13 +219,9 @@ extension Collection {
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n* /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Combinations` /// is the number of elements in the base collection, since `Combinations`
/// accesses the `count` of the base collection. /// accesses the `count` of the base collection.
@inlinable @inlinable public func combinations<R: RangeExpression>(ofCount kRange: R) -> Combinations<Self>
public func combinations<R: RangeExpression>( where R.Bound == Int { return Combinations(self, kRange: kRange) }
ofCount kRange: R
) -> Combinations<Self> where R.Bound == Int {
return Combinations(self, kRange: kRange)
}
/// Returns a collection of combinations of this collection's elements, with /// Returns a collection of combinations of this collection's elements, with
/// each combination having the specified number of elements. /// each combination having the specified number of elements.
/// ///
@@ -284,8 +251,7 @@ extension Collection {
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n* /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Combinations` /// is the number of elements in the base collection, since `Combinations`
/// accesses the `count` of the base collection. /// accesses the `count` of the base collection.
@inlinable @inlinable public func combinations(ofCount k: Int) -> Combinations<Self> {
public func combinations(ofCount k: Int) -> Combinations<Self> {
precondition(k >= 0, "Can't have combinations with a negative number of elements.") precondition(k >= 0, "Can't have combinations with a negative number of elements.")
return Combinations(self, k: k) return Combinations(self, k: k)
} }
+45 -85
View File
@@ -10,28 +10,18 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
/// A `Sequence` that iterates over every non-nil element from the original `Sequence`. /// A `Sequence` that iterates over every non-nil element from the original `Sequence`.
public struct CompactedSequence<Base: Sequence, Element>: Sequence public struct CompactedSequence<Base: Sequence, Element>: Sequence where Base.Element == Element? {
where Base.Element == Element? {
@usableFromInline @usableFromInline let base: Base
let base: Base
@inlinable init(base: Base) { self.base = base }
@inlinable
init(base: Base) {
self.base = base
}
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline var base: Base.Iterator
var base: Base.Iterator
@inlinable init(base: Base.Iterator) { self.base = base }
@inlinable
init(base: Base.Iterator) { @inlinable public mutating func next() -> Element? {
self.base = base
}
@inlinable
public mutating func next() -> Element? {
while let wrapped = base.next() { while let wrapped = base.next() {
guard let some = wrapped else { continue } guard let some = wrapped else { continue }
return some return some
@@ -40,10 +30,7 @@ public struct CompactedSequence<Base: Sequence, Element>: Sequence
} }
} }
@inlinable @inlinable public func makeIterator() -> Iterator { return Iterator(base: base.makeIterator()) }
public func makeIterator() -> Iterator {
return Iterator(base: base.makeIterator())
}
} }
extension Sequence { extension Sequence {
@@ -64,83 +51,62 @@ extension Sequence {
/// `Sequence`. /// `Sequence`.
/// ///
/// Complexity: O(1) /// Complexity: O(1)
@inlinable @inlinable public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped> where Element == Unwrapped? { CompactedSequence(base: self) }
where Element == Unwrapped? {
CompactedSequence(base: self)
}
} }
/// A `Collection` that iterates over every non-nil element from the original `Collection`. /// A `Collection` that iterates over every non-nil element from the original `Collection`.
public struct CompactedCollection<Base: Collection, Element>: Collection public struct CompactedCollection<Base: Collection, Element>: Collection
where Base.Element == Element? { where Base.Element == Element? {
@usableFromInline @usableFromInline let base: Base
let base: Base
@inlinable init(base: Base) {
@inlinable
init(base: Base) {
self.base = base self.base = base
let idx = base.firstIndex(where: { $0 != nil }) ?? base.endIndex let idx = base.firstIndex(where: { $0 != nil }) ?? base.endIndex
self.startIndex = Index(base: idx) self.startIndex = Index(base: idx)
} }
public struct Index { public struct Index {
@usableFromInline @usableFromInline let base: Base.Index
let base: Base.Index
@inlinable init(base: Base.Index) { self.base = base }
@inlinable
init(base: Base.Index) {
self.base = base
}
} }
public var startIndex: Index public var startIndex: Index
@inlinable @inlinable public var endIndex: Index { Index(base: base.endIndex) }
public var endIndex: Index { Index(base: base.endIndex) }
@inlinable public subscript(position: Index) -> Element { base[position.base]! }
@inlinable
public subscript(position: Index) -> Element { @inlinable public func index(after i: Index) -> Index {
base[position.base]!
}
@inlinable
public func index(after i: Index) -> Index {
precondition(i != endIndex, "Index out of bounds") precondition(i != endIndex, "Index out of bounds")
let baseIdx = base.index(after: i.base) let baseIdx = base.index(after: i.base)
guard let idx = base[baseIdx...].firstIndex(where: { $0 != nil }) guard let idx = base[baseIdx...].firstIndex(where: { $0 != nil }) else { return endIndex }
else { return endIndex }
return Index(base: idx) return Index(base: idx)
} }
} }
extension CompactedCollection: BidirectionalCollection extension CompactedCollection: BidirectionalCollection where Base: BidirectionalCollection {
where Base: BidirectionalCollection {
@inlinable @inlinable public func index(before i: Index) -> Index {
public func index(before i: Index) -> Index {
precondition(i != startIndex, "Index out of bounds") precondition(i != startIndex, "Index out of bounds")
guard let idx = guard let idx = base[startIndex.base..<i.base].lastIndex(where: { $0 != nil }) else {
base[startIndex.base..<i.base] fatalError("Index out of bounds")
.lastIndex(where: { $0 != nil }) }
else { fatalError("Index out of bounds") }
return Index(base: idx) return Index(base: idx)
} }
} }
extension CompactedCollection.Index: Comparable { extension CompactedCollection.Index: Comparable {
@inlinable @inlinable public static func < (lhs: CompactedCollection.Index, rhs: CompactedCollection.Index)
public static func < (lhs: CompactedCollection.Index, -> Bool
rhs: CompactedCollection.Index) -> Bool { { lhs.base < rhs.base }
lhs.base < rhs.base
}
} }
extension CompactedCollection.Index: Hashable extension CompactedCollection.Index: Hashable where Base.Index: Hashable {}
where Base.Index: Hashable {}
extension Collection { extension Collection {
/// Returns a new `Collection` that iterates over every non-nil element /// Returns a new `Collection` that iterates over every non-nil element
@@ -161,21 +127,15 @@ extension Collection {
/// ///
/// Complexity: O(*n*) where *n* is the number of elements in the /// Complexity: O(*n*) where *n* is the number of elements in the
/// original `Collection`. /// original `Collection`.
@inlinable @inlinable public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped> where Element == Unwrapped? { CompactedCollection(base: self) }
where Element == Unwrapped? {
CompactedCollection(base: self)
}
} }
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// Protocol Conformances // Protocol Conformances
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
extension CompactedSequence: LazySequenceProtocol extension CompactedSequence: LazySequenceProtocol where Base: LazySequenceProtocol {}
where Base: LazySequenceProtocol {}
extension CompactedCollection: LazySequenceProtocol extension CompactedCollection: LazySequenceProtocol where Base: LazySequenceProtocol {}
where Base: LazySequenceProtocol {} extension CompactedCollection: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
extension CompactedCollection: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
+41 -90
View File
@@ -12,67 +12,49 @@
/// A collection wrapper that repeats the elements of a base collection. /// A collection wrapper that repeats the elements of a base collection.
public struct Cycle<Base: Collection> { public struct Cycle<Base: Collection> {
/// The collection to repeat. /// The collection to repeat.
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@inlinable internal init(base: Base) { self.base = base }
@inlinable
internal init(base: Base) {
self.base = base
}
} }
extension Cycle: Sequence { extension Cycle: Sequence {
/// The iterator for a `Cycle` sequence. /// The iterator for a `Cycle` sequence.
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline internal var current: Base.Index
@usableFromInline
internal var current: Base.Index @inlinable internal init(base: Base) {
@inlinable
internal init(base: Base) {
self.base = base self.base = base
self.current = base.startIndex self.current = base.startIndex
} }
@inlinable @inlinable public mutating func next() -> Base.Element? {
public mutating func next() -> Base.Element? {
guard !base.isEmpty else { return nil } guard !base.isEmpty else { return nil }
if current == base.endIndex { if current == base.endIndex { current = base.startIndex }
current = base.startIndex
}
defer { base.formIndex(after: &current) } defer { base.formIndex(after: &current) }
return base[current] return base[current]
} }
} }
@inlinable @inlinable public func makeIterator() -> Iterator { Iterator(base: base) }
public func makeIterator() -> Iterator {
Iterator(base: base)
}
} }
extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {} extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {}
/// A collection wrapper that repeats the elements of a base collection for a /// A collection wrapper that repeats the elements of a base collection for a
/// finite number of times. /// finite number of times.
public struct FiniteCycle<Base: Collection> { public struct FiniteCycle<Base: Collection> {
/// A Product2 instance for iterating the Base collection. /// A Product2 instance for iterating the Base collection.
@usableFromInline @usableFromInline internal let product: Product2<Range<Int>, Base>
internal let product: Product2<Range<Int>, Base>
@inlinable @inlinable internal init(base: Base, times: Int) { self.product = Product2(0..<times, base) }
internal init(base: Base, times: Int) {
self.product = Product2(0..<times, base)
}
} }
extension FiniteCycle: LazySequenceProtocol, LazyCollectionProtocol extension FiniteCycle: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazyCollectionProtocol { } where Base: LazyCollectionProtocol {}
extension FiniteCycle: Collection { extension FiniteCycle: Collection {
@@ -80,88 +62,61 @@ extension FiniteCycle: Collection {
public struct Index: Comparable { public struct Index: Comparable {
/// The index corresponding to the Product2 index at this position. /// The index corresponding to the Product2 index at this position.
@usableFromInline @usableFromInline internal let productIndex: Product2<Range<Int>, Base>.Index
internal let productIndex: Product2<Range<Int>, Base>.Index
@inlinable @inlinable internal init(_ productIndex: Product2<Range<Int>, Base>.Index) {
internal init(_ productIndex: Product2<Range<Int>, Base>.Index) {
self.productIndex = productIndex self.productIndex = productIndex
} }
@inlinable @inlinable public static func == (lhs: Index, rhs: Index) -> Bool {
public static func == (lhs: Index, rhs: Index) -> Bool {
lhs.productIndex == rhs.productIndex lhs.productIndex == rhs.productIndex
} }
@inlinable @inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.productIndex < rhs.productIndex lhs.productIndex < rhs.productIndex
} }
} }
@inlinable @inlinable public var startIndex: Index { Index(product.startIndex) }
public var startIndex: Index {
Index(product.startIndex)
}
@inlinable @inlinable public var endIndex: Index { Index(product.endIndex) }
public var endIndex: Index {
Index(product.endIndex)
}
@inlinable @inlinable public subscript(_ index: Index) -> Element { product[index.productIndex].1 }
public subscript(_ index: Index) -> Element {
product[index.productIndex].1
}
@inlinable @inlinable public func index(after i: Index) -> Index {
public func index(after i: Index) -> Index {
let productIndex = product.index(after: i.productIndex) let productIndex = product.index(after: i.productIndex)
return Index(productIndex) return Index(productIndex)
} }
@inlinable @inlinable public func distance(from start: Index, to end: Index) -> Int {
public func distance(from start: Index, to end: Index) -> Int {
product.distance(from: start.productIndex, to: end.productIndex) product.distance(from: start.productIndex, to: end.productIndex)
} }
@inlinable @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
public func index(_ i: Index, offsetBy distance: Int) -> Index {
let productIndex = product.index(i.productIndex, offsetBy: distance) let productIndex = product.index(i.productIndex, offsetBy: distance)
return Index(productIndex) return Index(productIndex)
} }
@inlinable @inlinable public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index?
public func index( {
_ i: Index, guard
offsetBy distance: Int, let productIndex = product.index(
limitedBy limit: Index i.productIndex, offsetBy: distance, limitedBy: limit.productIndex)
) -> Index? { else { return nil }
guard let productIndex = product.index(i.productIndex,
offsetBy: distance,
limitedBy: limit.productIndex) else {
return nil
}
return Index(productIndex) return Index(productIndex)
} }
@inlinable @inlinable public var count: Int { product.count }
public var count: Int {
product.count
}
} }
extension FiniteCycle: BidirectionalCollection extension FiniteCycle: BidirectionalCollection where Base: BidirectionalCollection {
where Base: BidirectionalCollection { @inlinable public func index(before i: Index) -> Index {
@inlinable
public func index(before i: Index) -> Index {
let productIndex = product.index(before: i.productIndex) let productIndex = product.index(before: i.productIndex)
return Index(productIndex) return Index(productIndex)
} }
} }
extension FiniteCycle: RandomAccessCollection extension FiniteCycle: RandomAccessCollection where Base: RandomAccessCollection {}
where Base: RandomAccessCollection {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// cycled() // cycled()
@@ -193,11 +148,8 @@ extension Collection {
/// forever. /// forever.
/// ///
/// - Complexity: O(1) /// - Complexity: O(1)
@inlinable @inlinable public func cycled() -> Cycle<Self> { Cycle(base: self) }
public func cycled() -> Cycle<Self> {
Cycle(base: self)
}
/// Returns a sequence that repeats the elements of this collection the /// Returns a sequence that repeats the elements of this collection the
/// specified number of times. /// specified number of times.
/// ///
@@ -215,8 +167,7 @@ extension Collection {
/// times. /// times.
/// ///
/// - Complexity: O(1) /// - Complexity: O(1)
@inlinable @inlinable public func cycled(times: Int) -> FiniteCycle<Self> {
public func cycled(times: Int) -> FiniteCycle<Self> {
FiniteCycle(base: self, times: times) FiniteCycle(base: self, times: times)
} }
} }
+3 -9
View File
@@ -13,7 +13,7 @@
// firstNonNil(_:) // firstNonNil(_:)
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
public extension Sequence { extension Sequence {
/// Returns the first non-`nil` result obtained from applying the given /// Returns the first non-`nil` result obtained from applying the given
/// transformation to the elements of the sequence. /// transformation to the elements of the sequence.
/// ///
@@ -30,14 +30,8 @@ public extension Sequence {
/// ///
/// - Complexity: O(*n*), where *n* is the number of elements at the start of /// - Complexity: O(*n*), where *n* is the number of elements at the start of
/// the sequence that result in `nil` when applying the transformation. /// the sequence that result in `nil` when applying the transformation.
func firstNonNil<Result>( public func firstNonNil<Result>(_ transform: (Element) throws -> Result?) rethrows -> Result? {
_ transform: (Element) throws -> Result? for value in self { if let value = try transform(value) { return value } }
) rethrows -> Result? {
for value in self {
if let value = try transform(value) {
return value
}
}
return nil return nil
} }
} }
+21 -44
View File
@@ -14,59 +14,39 @@
public struct Indexed<Base: Collection> { public struct Indexed<Base: Collection> {
/// The element type for an `Indexed` collection. /// The element type for an `Indexed` collection.
public typealias Element = (index: Base.Index, element: Base.Element) public typealias Element = (index: Base.Index, element: Base.Element)
/// The base collection. /// The base collection.
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@inlinable internal init(base: Base) { self.base = base }
@inlinable
internal init(base: Base) {
self.base = base
}
} }
extension Indexed: Collection { extension Indexed: Collection {
@inlinable @inlinable public var startIndex: Base.Index { base.startIndex }
public var startIndex: Base.Index {
base.startIndex @inlinable public var endIndex: Base.Index { base.endIndex }
}
@inlinable public subscript(position: Base.Index) -> Element {
@inlinable
public var endIndex: Base.Index {
base.endIndex
}
@inlinable
public subscript(position: Base.Index) -> Element {
(index: position, element: base[position]) (index: position, element: base[position])
} }
@inlinable @inlinable public func index(after i: Base.Index) -> Base.Index { base.index(after: i) }
public func index(after i: Base.Index) -> Base.Index {
base.index(after: i) @inlinable public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index {
}
@inlinable
public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index {
base.index(i, offsetBy: distance) base.index(i, offsetBy: distance)
} }
@inlinable @inlinable public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index)
public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index) -> Base.Index? { -> Base.Index?
base.index(i, offsetBy: distance, limitedBy: limit) { base.index(i, offsetBy: distance, limitedBy: limit) }
}
@inlinable public func distance(from start: Base.Index, to end: Base.Index) -> Int {
@inlinable
public func distance(from start: Base.Index, to end: Base.Index) -> Int {
base.distance(from: start, to: end) base.distance(from: start, to: end)
} }
} }
extension Indexed: BidirectionalCollection where Base: BidirectionalCollection { extension Indexed: BidirectionalCollection where Base: BidirectionalCollection {
@inlinable @inlinable public func index(before i: Base.Index) -> Base.Index { base.index(before: i) }
public func index(before i: Base.Index) -> Base.Index {
base.index(before: i)
}
} }
extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {} extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {}
@@ -93,8 +73,5 @@ extension Collection {
/// } /// }
/// ///
/// Returns: A collection of paired indices and elements of this collection. /// Returns: A collection of paired indices and elements of this collection.
@inlinable @inlinable public func indexed() -> Indexed<Self> { Indexed(base: self) }
public func indexed() -> Indexed<Self> {
Indexed(base: self)
}
} }
+46 -87
View File
@@ -12,14 +12,11 @@
/// A sequence that presents the elements of a base sequence of elements /// A sequence that presents the elements of a base sequence of elements
/// with a separator between each of those elements. /// with a separator between each of those elements.
public struct Intersperse<Base: Sequence> { public struct Intersperse<Base: Sequence> {
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline internal let separator: Base.Element
@usableFromInline
internal let separator: Base.Element @inlinable internal init(base: Base, separator: Base.Element) {
@inlinable
internal init(base: Base, separator: Base.Element) {
self.base = base self.base = base
self.separator = separator self.separator = separator
} }
@@ -28,30 +25,24 @@ public struct Intersperse<Base: Sequence> {
extension Intersperse: Sequence { extension Intersperse: Sequence {
/// The iterator for an `Intersperse` sequence. /// The iterator for an `Intersperse` sequence.
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline internal var iterator: Base.Iterator
internal var iterator: Base.Iterator
@usableFromInline internal let separator: Base.Element
@usableFromInline
internal let separator: Base.Element @usableFromInline internal var state = State.start
@usableFromInline @inlinable internal init(iterator: Base.Iterator, separator: Base.Element) {
internal var state = State.start
@inlinable
internal init(iterator: Base.Iterator, separator: Base.Element) {
self.iterator = iterator self.iterator = iterator
self.separator = separator self.separator = separator
} }
@usableFromInline @usableFromInline enum State {
enum State {
case start case start
case element(Base.Element) case element(Base.Element)
case separator case separator
} }
@inlinable @inlinable public mutating func next() -> Base.Element? {
public mutating func next() -> Base.Element? {
// After the start, the state flips between element and separator. Before // After the start, the state flips between element and separator. Before
// returning a separator, a check is made for the next element as a // returning a separator, a check is made for the next element as a
// separator is only returned between two elements. The next element is // separator is only returned between two elements. The next element is
@@ -71,8 +62,7 @@ extension Intersperse: Sequence {
} }
} }
@inlinable @inlinable public func makeIterator() -> Intersperse<Base>.Iterator {
public func makeIterator() -> Intersperse<Base>.Iterator {
Iterator(iterator: base.makeIterator(), separator: separator) Iterator(iterator: base.makeIterator(), separator: separator)
} }
} }
@@ -80,77 +70,57 @@ extension Intersperse: Sequence {
extension Intersperse: Collection where Base: Collection { extension Intersperse: Collection where Base: Collection {
/// A position in an `Intersperse` collection. /// A position in an `Intersperse` collection.
public struct Index: Comparable { public struct Index: Comparable {
@usableFromInline @usableFromInline enum Representation: Equatable {
enum Representation: Equatable {
case element(Base.Index) case element(Base.Index)
case separator(next: Base.Index) case separator(next: Base.Index)
} }
@usableFromInline
internal let representation: Representation
@inlinable @usableFromInline internal let representation: Representation
init(representation: Representation) {
self.representation = representation
}
@inlinable @inlinable init(representation: Representation) { self.representation = representation }
public static func < (lhs: Index, rhs: Index) -> Bool {
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs.representation, rhs.representation) { switch (lhs.representation, rhs.representation) {
case let (.element(li), .element(ri)), case let (.element(li), .element(ri)), let (.separator(next: li), .separator(next: ri)),
let (.separator(next: li), .separator(next: ri)), let (.element(li), .separator(next: ri)):
let (.element(li), .separator(next: ri)):
return li < ri return li < ri
case let (.separator(next: li), .element(ri)): case let (.separator(next: li), .element(ri)): return li <= ri
return li <= ri
} }
} }
@inlinable @inlinable static func element(_ index: Base.Index) -> Self {
static func element(_ index: Base.Index) -> Self {
Self(representation: .element(index)) Self(representation: .element(index))
} }
@inlinable @inlinable static func separator(next: Base.Index) -> Self {
static func separator(next: Base.Index) -> Self {
Self(representation: .separator(next: next)) Self(representation: .separator(next: next))
} }
} }
@inlinable @inlinable public var startIndex: Index {
public var startIndex: Index {
base.startIndex == base.endIndex ? endIndex : .element(base.startIndex) base.startIndex == base.endIndex ? endIndex : .element(base.startIndex)
} }
@inlinable @inlinable public var endIndex: Index { .separator(next: base.endIndex) }
public var endIndex: Index {
.separator(next: base.endIndex)
}
@inlinable @inlinable public func index(after i: Index) -> Index {
public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance past endIndex") precondition(i != endIndex, "Can't advance past endIndex")
switch i.representation { switch i.representation {
case let .element(index): case let .element(index): return .separator(next: base.index(after: index))
return .separator(next: base.index(after: index)) case let .separator(next): return .element(next)
case let .separator(next):
return .element(next)
} }
} }
@inlinable @inlinable public subscript(position: Index) -> Element {
public subscript(position: Index) -> Element {
switch position.representation { switch position.representation {
case .element(let index): return base[index] case .element(let index): return base[index]
case .separator: return separator case .separator: return separator
} }
} }
@inlinable @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
public func index(_ i: Index, offsetBy distance: Int) -> Index {
switch (i.representation, distance.isMultiple(of: 2)) { switch (i.representation, distance.isMultiple(of: 2)) {
case (let .element(index), true): case (let .element(index), true): return .element(base.index(index, offsetBy: distance / 2))
return .element(base.index(index, offsetBy: distance / 2))
case (let .element(index), false): case (let .element(index), false):
return .separator(next: base.index(index, offsetBy: (distance + 1) / 2)) return .separator(next: base.index(index, offsetBy: (distance + 1) / 2))
case (let .separator(next: index), true): case (let .separator(next: index), true):
@@ -161,43 +131,33 @@ extension Intersperse: Collection where Base: Collection {
} }
// TODO: Implement index(_:offsetBy:limitedBy:) // TODO: Implement index(_:offsetBy:limitedBy:)
@inlinable @inlinable public func distance(from start: Index, to end: Index) -> Int {
public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) { switch (start.representation, end.representation) {
case let (.element(element), .separator(next: separator)): case let (.element(element), .separator(next: separator)):
return 2 * base.distance(from: element, to: separator) - 1 return 2 * base.distance(from: element, to: separator) - 1
case let (.separator(next: separator), .element(element)): case let (.separator(next: separator), .element(element)):
return 2 * base.distance(from: separator, to: element) + 1 return 2 * base.distance(from: separator, to: element) + 1
case let (.element(start), .element(end)), case let (.element(start), .element(end)), let (.separator(start), .separator(end)):
let (.separator(start), .separator(end)):
return 2 * base.distance(from: start, to: end) return 2 * base.distance(from: start, to: end)
} }
} }
} }
extension Intersperse: BidirectionalCollection extension Intersperse: BidirectionalCollection where Base: BidirectionalCollection {
where Base: BidirectionalCollection @inlinable public func index(before i: Index) -> Index {
{
@inlinable
public func index(before i: Index) -> Index {
precondition(i != startIndex, "Can't move before startIndex") precondition(i != startIndex, "Can't move before startIndex")
switch i.representation { switch i.representation {
case let .element(index): case let .element(index): return .separator(next: index)
return .separator(next: index) case let .separator(next): return .element(base.index(before: next))
case let .separator(next):
return .element(base.index(before: next))
} }
} }
} }
extension Intersperse: RandomAccessCollection extension Intersperse: RandomAccessCollection where Base: RandomAccessCollection {}
where Base: RandomAccessCollection {}
extension Intersperse: LazySequenceProtocol extension Intersperse: LazySequenceProtocol where Base: LazySequenceProtocol {}
where Base: LazySequenceProtocol {}
extension Intersperse: LazyCollectionProtocol extension Intersperse: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
where Base: LazyCollectionProtocol {}
extension Sequence { extension Sequence {
@@ -229,8 +189,7 @@ extension Sequence {
/// - Returns: The interspersed sequence of elements. /// - Returns: The interspersed sequence of elements.
/// ///
/// - Complexity: O(1) /// - Complexity: O(1)
@inlinable @inlinable public func interspersed(with separator: Element) -> Intersperse<Self> {
public func interspersed(with separator: Element) -> Intersperse<Self> {
Intersperse(base: self, separator: separator) Intersperse(base: self, separator: separator)
} }
} }
+67 -165
View File
@@ -22,23 +22,16 @@
/// ///
/// where `x` conforms to `LazySequenceProtocol`. /// where `x` conforms to `LazySequenceProtocol`.
public struct LazySplitSequence<Base: Sequence> { public struct LazySplitSequence<Base: Sequence> {
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline @usableFromInline internal let isSeparator: (Base.Element) -> Bool
internal let isSeparator: (Base.Element) -> Bool
@usableFromInline @usableFromInline internal let maxSplits: Int
internal let maxSplits: Int
@usableFromInline @usableFromInline internal let omittingEmptySubsequences: Bool
internal let omittingEmptySubsequences: Bool
@inlinable @inlinable internal init(
internal init( base: Base, isSeparator: @escaping (Base.Element) -> Bool, maxSplits: Int,
base: Base,
isSeparator: @escaping (Base.Element) -> Bool,
maxSplits: Int,
omittingEmptySubsequences: Bool omittingEmptySubsequences: Bool
) { ) {
self.base = base self.base = base
@@ -52,31 +45,22 @@ extension LazySplitSequence {
public struct Iterator { public struct Iterator {
public typealias Element = [Base.Element] public typealias Element = [Base.Element]
@usableFromInline @usableFromInline internal var base: Base.Iterator
internal var base: Base.Iterator
@usableFromInline @usableFromInline internal let isSeparator: (Base.Element) -> Bool
internal let isSeparator: (Base.Element) -> Bool
@usableFromInline @usableFromInline internal let maxSplits: Int
internal let maxSplits: Int
@usableFromInline @usableFromInline internal let omittingEmptySubsequences: Bool
internal let omittingEmptySubsequences: Bool
/// The number of splits performed. /// The number of splits performed.
@usableFromInline @usableFromInline internal var splitCount = 0
internal var splitCount = 0
/// The number of subsequences returned. /// The number of subsequences returned.
@usableFromInline @usableFromInline internal var sequenceLength = 0
internal var sequenceLength = 0
@inlinable @inlinable internal init(
internal init( base: Base.Iterator, whereSeparator: @escaping (Base.Element) -> Bool, maxSplits: Int,
base: Base.Iterator,
whereSeparator: @escaping (Base.Element) -> Bool,
maxSplits: Int,
omittingEmptySubsequences: Bool omittingEmptySubsequences: Bool
) { ) {
self.base = base self.base = base
@@ -88,8 +72,7 @@ extension LazySplitSequence {
} }
extension LazySplitSequence.Iterator: IteratorProtocol { extension LazySplitSequence.Iterator: IteratorProtocol {
@inlinable @inlinable public mutating func next() -> Element? {
public mutating func next() -> Element? {
var currentElement = base.next() var currentElement = base.next()
var subsequence: Element = [] var subsequence: Element = []
@@ -117,8 +100,7 @@ extension LazySplitSequence.Iterator: IteratorProtocol {
// than the number of separators), or the only subsequence left to return is // than the number of separators), or the only subsequence left to return is
// empty and we're omitting those. // empty and we're omitting those.
if currentElement == nil if currentElement == nil
&& (sequenceLength == splitCount + 1 && (sequenceLength == splitCount + 1 || omittingEmptySubsequences && subsequence.isEmpty)
|| omittingEmptySubsequences && subsequence.isEmpty)
{ {
return nil return nil
} else { } else {
@@ -129,14 +111,10 @@ extension LazySplitSequence.Iterator: IteratorProtocol {
} }
extension LazySplitSequence: LazySequenceProtocol { extension LazySplitSequence: LazySequenceProtocol {
@inlinable @inlinable public func makeIterator() -> Iterator {
public func makeIterator() -> Iterator {
return Iterator( return Iterator(
base: base.makeIterator(), base: base.makeIterator(), whereSeparator: self.isSeparator, maxSplits: self.maxSplits,
whereSeparator: self.isSeparator, omittingEmptySubsequences: self.omittingEmptySubsequences)
maxSplits: self.maxSplits,
omittingEmptySubsequences: self.omittingEmptySubsequences
)
} }
} }
@@ -225,20 +203,15 @@ extension LazySequenceProtocol {
/// elements. /// elements.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the sequence. /// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable @inlinable public func split(
public func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: @escaping (Element) -> Bool whereSeparator isSeparator: @escaping (Element) -> Bool
) -> LazySplitSequence<Elements> { ) -> LazySplitSequence<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits") precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitSequence( return LazySplitSequence(
base: elements, base: elements, isSeparator: isSeparator, maxSplits: maxSplits,
isSeparator: isSeparator, omittingEmptySubsequences: omittingEmptySubsequences)
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences
)
} }
} }
@@ -315,20 +288,14 @@ extension LazySequenceProtocol where Element: Equatable {
/// elements. /// elements.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the sequence. /// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable @inlinable public func split(
public func split( separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> LazySplitSequence<Elements> { ) -> LazySplitSequence<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits") precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitSequence( return LazySplitSequence(
base: elements, base: elements, isSeparator: { $0 == separator }, maxSplits: maxSplits,
isSeparator: { $0 == separator }, omittingEmptySubsequences: omittingEmptySubsequences)
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences
)
} }
} }
@@ -345,26 +312,18 @@ extension LazySequenceProtocol where Element: Equatable {
/// ///
/// where `x` conforms to `LazyCollectionProtocol`. /// where `x` conforms to `LazyCollectionProtocol`.
public struct LazySplitCollection<Base: Collection> { public struct LazySplitCollection<Base: Collection> {
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline @usableFromInline internal let isSeparator: (Base.Element) -> Bool
internal let isSeparator: (Base.Element) -> Bool
@usableFromInline @usableFromInline internal let maxSplits: Int
internal let maxSplits: Int
@usableFromInline @usableFromInline internal let omittingEmptySubsequences: Bool
internal let omittingEmptySubsequences: Bool
@usableFromInline @usableFromInline internal var _startIndex: Index
internal var _startIndex: Index
@inlinable @inlinable internal init(
internal init( base: Base, isSeparator: @escaping (Base.Element) -> Bool, maxSplits: Int,
base: Base,
isSeparator: @escaping (Base.Element) -> Bool,
maxSplits: Int,
omittingEmptySubsequences: Bool omittingEmptySubsequences: Bool
) { ) {
self.base = base self.base = base
@@ -376,10 +335,7 @@ public struct LazySplitCollection<Base: Collection> {
// 1. `base` is empty and we're _not_ omitting empty subsequences, in which // 1. `base` is empty and we're _not_ omitting empty subsequences, in which
// case the following index describes the sole element of this collection; // case the following index describes the sole element of this collection;
self._startIndex = Index( self._startIndex = Index(
baseRange: base.startIndex..<base.startIndex, baseRange: base.startIndex..<base.startIndex, sequenceLength: 1, splitCount: 0)
sequenceLength: 1,
splitCount: 0
)
if base.isEmpty { if base.isEmpty {
if omittingEmptySubsequences { if omittingEmptySubsequences {
// 2. `base` is empty and we _are_ omitting empty subsequences, so this // 2. `base` is empty and we _are_ omitting empty subsequences, so this
@@ -390,10 +346,7 @@ public struct LazySplitCollection<Base: Collection> {
// 3. `base` isn't empty, so we must iterate it to determine the start // 3. `base` isn't empty, so we must iterate it to determine the start
// index. // index.
_startIndex = indexForSubsequence( _startIndex = indexForSubsequence(
atOrAfter: base.startIndex, atOrAfter: base.startIndex, sequenceLength: 0, splitCount: 0)
sequenceLength: 0,
splitCount: 0
)
} }
} }
} }
@@ -402,50 +355,37 @@ extension LazySplitCollection: LazyCollectionProtocol {
/// Position of a subsequence in a split collection. /// Position of a subsequence in a split collection.
public struct Index: Comparable { public struct Index: Comparable {
/// The range corresponding to the subsequence at this position. /// The range corresponding to the subsequence at this position.
@usableFromInline @usableFromInline internal let baseRange: Range<Base.Index>
internal let baseRange: Range<Base.Index>
/// The number of subsequences up to and including this position in the /// The number of subsequences up to and including this position in the
/// collection. /// collection.
@usableFromInline @usableFromInline internal let sequenceLength: Int
internal let sequenceLength: Int
/// The number splits performed up to and including this position in the /// The number splits performed up to and including this position in the
/// collection. /// collection.
@usableFromInline @usableFromInline internal let splitCount: Int
internal let splitCount: Int
@inlinable @inlinable internal init(baseRange: Range<Base.Index>, sequenceLength: Int, splitCount: Int) {
internal init(
baseRange: Range<Base.Index>,
sequenceLength: Int,
splitCount: Int
) {
self.baseRange = baseRange self.baseRange = baseRange
self.sequenceLength = sequenceLength self.sequenceLength = sequenceLength
self.splitCount = splitCount self.splitCount = splitCount
} }
@inlinable @inlinable public static func == (lhs: Index, rhs: Index) -> Bool {
public static func == (lhs: Index, rhs: Index) -> Bool {
// `sequenceLength` is equivalent to the index's 1-based position in the // `sequenceLength` is equivalent to the index's 1-based position in the
// collection of indices. // collection of indices.
lhs.sequenceLength == rhs.sequenceLength lhs.sequenceLength == rhs.sequenceLength
} }
@inlinable @inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.sequenceLength < rhs.sequenceLength lhs.sequenceLength < rhs.sequenceLength
} }
} }
/// Returns the index of the subsequence starting at or after the given base /// Returns the index of the subsequence starting at or after the given base
/// collection index. /// collection index.
@inlinable @inlinable internal func indexForSubsequence(
internal func indexForSubsequence( atOrAfter lowerBound: Base.Index, sequenceLength: Int, splitCount: Int
atOrAfter lowerBound: Base.Index,
sequenceLength: Int,
splitCount: Int
) -> Index { ) -> Index {
var start = lowerBound var start = lowerBound
// If we don't have any more splits to do (which we'll determine shortly), // If we don't have any more splits to do (which we'll determine shortly),
@@ -455,16 +395,12 @@ extension LazySplitCollection: LazyCollectionProtocol {
if splitCount < maxSplits { if splitCount < maxSplits {
// The non-inclusive end of this subsequence is marked by the next // The non-inclusive end of this subsequence is marked by the next
// separator, or the end of the base collection. // separator, or the end of the base collection.
end = end = base[start...].firstIndex(where: isSeparator) ?? base.endIndex
base[start...].firstIndex(where: isSeparator)
?? base.endIndex
if base[start..<end].isEmpty { if base[start..<end].isEmpty {
if omittingEmptySubsequences { if omittingEmptySubsequences {
// Find the next subsequence of non-separators. // Find the next subsequence of non-separators.
start = start = base[end...].firstIndex(where: { !isSeparator($0) }) ?? base.endIndex
base[end...].firstIndex(where: { !isSeparator($0) })
?? base.endIndex
if start == base.endIndex { if start == base.endIndex {
// No non-separators left in the base collection. We're done. // No non-separators left in the base collection. We're done.
return endIndex return endIndex
@@ -483,28 +419,16 @@ extension LazySplitCollection: LazyCollectionProtocol {
} }
return Index( return Index(
baseRange: start..<end, baseRange: start..<end, sequenceLength: sequenceLength + 1, splitCount: updatedSplitCount)
sequenceLength: sequenceLength + 1,
splitCount: updatedSplitCount
)
} }
@inlinable @inlinable public var startIndex: Index { _startIndex }
public var startIndex: Index {
_startIndex @inlinable public var endIndex: Index {
Index(baseRange: base.endIndex..<base.endIndex, sequenceLength: Int.max, splitCount: Int.max)
} }
@inlinable @inlinable public func index(after i: Index) -> Index {
public var endIndex: Index {
Index(
baseRange: base.endIndex..<base.endIndex,
sequenceLength: Int.max,
splitCount: Int.max
)
}
@inlinable
public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance past endIndex") precondition(i != endIndex, "Can't advance past endIndex")
var subsequenceStart = i.baseRange.upperBound var subsequenceStart = i.baseRange.upperBound
@@ -516,41 +440,31 @@ extension LazySplitCollection: LazyCollectionProtocol {
} }
guard subsequenceStart != base.endIndex else { guard subsequenceStart != base.endIndex else {
if !omittingEmptySubsequences if !omittingEmptySubsequences && i.sequenceLength < i.splitCount + 1 {
&& i.sequenceLength < i.splitCount + 1
{
// The base collection ended with a separator, so we need to emit one // The base collection ended with a separator, so we need to emit one
// more empty subsequence. This one differs from `endIndex` in its // more empty subsequence. This one differs from `endIndex` in its
// `sequenceLength` (except in an extreme edge case!), which is the // `sequenceLength` (except in an extreme edge case!), which is the
// sole property tested for equality and comparison. // sole property tested for equality and comparison.
return Index( return Index(
baseRange: base.endIndex..<base.endIndex, baseRange: base.endIndex..<base.endIndex, sequenceLength: i.sequenceLength + 1,
sequenceLength: i.sequenceLength + 1, splitCount: i.splitCount)
splitCount: i.splitCount
)
} else { } else {
return endIndex return endIndex
} }
} }
return indexForSubsequence( return indexForSubsequence(
atOrAfter: subsequenceStart, atOrAfter: subsequenceStart, sequenceLength: i.sequenceLength, splitCount: i.splitCount)
sequenceLength: i.sequenceLength,
splitCount: i.splitCount
)
} }
@inlinable @inlinable public subscript(position: Index) -> Base.SubSequence {
public subscript(position: Index) -> Base.SubSequence {
precondition(position != endIndex, "Can't subscript using endIndex") precondition(position != endIndex, "Can't subscript using endIndex")
return base[position.baseRange] return base[position.baseRange]
} }
} }
extension LazySplitCollection.Index: Hashable { extension LazySplitCollection.Index: Hashable {
public func hash(into hasher: inout Hasher) { public func hash(into hasher: inout Hasher) { hasher.combine(sequenceLength) }
hasher.combine(sequenceLength)
}
} }
extension LazyCollectionProtocol { extension LazyCollectionProtocol {
@@ -636,25 +550,19 @@ extension LazyCollectionProtocol {
/// elements. /// elements.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable public func split(
public func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: @escaping (Element) -> Bool whereSeparator isSeparator: @escaping (Element) -> Bool
) -> LazySplitCollection<Elements> { ) -> LazySplitCollection<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits") precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitCollection( return LazySplitCollection(
base: elements, base: elements, isSeparator: isSeparator, maxSplits: maxSplits,
isSeparator: isSeparator, omittingEmptySubsequences: omittingEmptySubsequences)
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences
)
} }
} }
extension LazyCollectionProtocol extension LazyCollectionProtocol where Element: Equatable {
where Element: Equatable {
/// Lazily returns the longest possible subsequences of the collection, in /// Lazily returns the longest possible subsequences of the collection, in
/// order, around elements equal to the given element. /// order, around elements equal to the given element.
/// ///
@@ -732,19 +640,13 @@ where Element: Equatable {
/// elements. /// elements.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable public func split(
public func split( separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> LazySplitCollection<Elements> { ) -> LazySplitCollection<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits") precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitCollection( return LazySplitCollection(
base: elements, base: elements, isSeparator: { $0 == separator }, maxSplits: maxSplits,
isSeparator: { $0 == separator }, omittingEmptySubsequences: omittingEmptySubsequences)
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences
)
} }
} }
+49 -83
View File
@@ -11,26 +11,21 @@
extension Sequence { extension Sequence {
/// Implementation for min(count:areInIncreasingOrder:) /// Implementation for min(count:areInIncreasingOrder:)
@inlinable @inlinable internal func _minImplementation(
internal func _minImplementation( count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] { ) rethrows -> [Element] {
var iterator = makeIterator() var iterator = makeIterator()
var result: [Element] = [] var result: [Element] = []
result.reserveCapacity(count) result.reserveCapacity(count)
while result.count < count, let e = iterator.next() { while result.count < count, let e = iterator.next() { result.append(e) }
result.append(e)
}
try result.sort(by: areInIncreasingOrder) try result.sort(by: areInIncreasingOrder)
while let e = iterator.next() { while let e = iterator.next() {
// To be part of `result`, `e` must be strictly less than `result.last`. // To be part of `result`, `e` must be strictly less than `result.last`.
guard try areInIncreasingOrder(e, result.last!) else { continue } guard try areInIncreasingOrder(e, result.last!) else { continue }
let insertionIndex = let insertionIndex = try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
assert(insertionIndex != result.endIndex) assert(insertionIndex != result.endIndex)
result.removeLast() result.removeLast()
result.insert(e, at: insertionIndex) result.insert(e, at: insertionIndex)
@@ -38,27 +33,22 @@ extension Sequence {
return result return result
} }
/// Implementation for max(count:areInIncreasingOrder:) /// Implementation for max(count:areInIncreasingOrder:)
@inlinable @inlinable internal func _maxImplementation(
internal func _maxImplementation( count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] { ) rethrows -> [Element] {
var iterator = makeIterator() var iterator = makeIterator()
var result: [Element] = [] var result: [Element] = []
result.reserveCapacity(count) result.reserveCapacity(count)
while result.count < count, let e = iterator.next() { while result.count < count, let e = iterator.next() { result.append(e) }
result.append(e)
}
try result.sort(by: areInIncreasingOrder) try result.sort(by: areInIncreasingOrder)
while let e = iterator.next() { while let e = iterator.next() {
// To be part of `result`, `e` must be greater/equal to `result.first`. // To be part of `result`, `e` must be greater/equal to `result.first`.
guard try !areInIncreasingOrder(e, result.first!) else { continue } guard try !areInIncreasingOrder(e, result.first!) else { continue }
let insertionIndex = let insertionIndex = try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
assert(insertionIndex > 0) assert(insertionIndex > 0)
// Inserting `e` and then removing the first element (or vice versa) // Inserting `e` and then removing the first element (or vice versa)
@@ -71,10 +61,10 @@ extension Sequence {
} }
result[insertionIndex - 1] = e result[insertionIndex - 1] = e
} }
return result return result
} }
/// Returns the smallest elements of this sequence, as sorted by the given /// Returns the smallest elements of this sequence, as sorted by the given
/// predicate. /// predicate.
/// ///
@@ -102,20 +92,17 @@ extension Sequence {
/// ///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`. /// sequence and *k* is `count`.
@inlinable @inlinable public func min(
public func min( count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] { ) rethrows -> [Element] {
precondition(count >= 0, """ precondition(
Cannot find a minimum with a negative count of elements! count >= 0,
""" """
) Cannot find a minimum with a negative count of elements!
""")
// Do nothing if we're prefixing nothing. // Do nothing if we're prefixing nothing.
guard count > 0 else { guard count > 0 else { return [] }
return []
}
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder) return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
} }
@@ -147,20 +134,17 @@ extension Sequence {
/// ///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`. /// sequence and *k* is `count`.
@inlinable @inlinable public func max(
public func max( count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] { ) rethrows -> [Element] {
precondition(count >= 0, """ precondition(
Cannot find a maximum with a negative count of elements! count >= 0,
""" """
) Cannot find a maximum with a negative count of elements!
""")
// Do nothing if we're suffixing nothing. // Do nothing if we're suffixing nothing.
guard count > 0 else { guard count > 0 else { return [] }
return []
}
return try _maxImplementation(count: count, sortedBy: areInIncreasingOrder) return try _maxImplementation(count: count, sortedBy: areInIncreasingOrder)
} }
@@ -188,10 +172,7 @@ extension Sequence where Element: Comparable {
/// ///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`. /// sequence and *k* is `count`.
@inlinable @inlinable public func min(count: Int) -> [Element] { return min(count: count, sortedBy: <) }
public func min(count: Int) -> [Element] {
return min(count: count, sortedBy: <)
}
/// Returns the largest elements of this sequence. /// Returns the largest elements of this sequence.
/// ///
@@ -214,10 +195,7 @@ extension Sequence where Element: Comparable {
/// ///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`. /// sequence and *k* is `count`.
@inlinable @inlinable public func max(count: Int) -> [Element] { return max(count: count, sortedBy: <) }
public func max(count: Int) -> [Element] {
return max(count: count, sortedBy: <)
}
} }
extension Collection { extension Collection {
@@ -248,20 +226,17 @@ extension Collection {
/// ///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`. /// collection and *k* is `count`.
@inlinable @inlinable public func min(
public func min( count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] { ) rethrows -> [Element] {
precondition(count >= 0, """ precondition(
Cannot find a minimum with a negative count of elements! count >= 0,
""" """
) Cannot find a minimum with a negative count of elements!
""")
// Do nothing if we're prefixing nothing. // Do nothing if we're prefixing nothing.
guard count > 0 else { guard count > 0 else { return [] }
return []
}
// Make sure we are within bounds. // Make sure we are within bounds.
let prefixCount = Swift.min(count, self.count) let prefixCount = Swift.min(count, self.count)
@@ -271,7 +246,7 @@ extension Collection {
guard prefixCount < (self.count / 10) else { guard prefixCount < (self.count / 10) else {
return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount)) return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount))
} }
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder) return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
} }
@@ -302,20 +277,17 @@ extension Collection {
/// ///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`. /// collection and *k* is `count`.
@inlinable @inlinable public func max(
public func max( count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] { ) rethrows -> [Element] {
precondition(count >= 0, """ precondition(
Cannot find a maximum with a negative count of elements! count >= 0,
""" """
) Cannot find a maximum with a negative count of elements!
""")
// Do nothing if we're suffixing nothing. // Do nothing if we're suffixing nothing.
guard count > 0 else { guard count > 0 else { return [] }
return []
}
// Make sure we are within bounds. // Make sure we are within bounds.
let suffixCount = Swift.min(count, self.count) let suffixCount = Swift.min(count, self.count)
@@ -352,10 +324,7 @@ extension Collection where Element: Comparable {
/// ///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`. /// collection and *k* is `count`.
@inlinable @inlinable public func min(count: Int) -> [Element] { return min(count: count, sortedBy: <) }
public func min(count: Int) -> [Element] {
return min(count: count, sortedBy: <)
}
/// Returns the largest elements of this collection. /// Returns the largest elements of this collection.
/// ///
@@ -378,8 +347,5 @@ extension Collection where Element: Comparable {
/// ///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`. /// collection and *k* is `count`.
@inlinable @inlinable public func max(count: Int) -> [Element] { return max(count: count, sortedBy: <) }
public func max(count: Int) -> [Element] {
return max(count: count, sortedBy: <)
}
} }
+29 -47
View File
@@ -21,31 +21,24 @@ extension MutableCollection {
/// - Complexity: O(*n* log *n*), where *n* is the number of elements. /// - Complexity: O(*n* log *n*), where *n* is the number of elements.
/// - Precondition: /// - Precondition:
/// `n == distance(from: range.lowerBound, to: range.upperBound)` /// `n == distance(from: range.lowerBound, to: range.upperBound)`
@inlinable @inlinable internal mutating func stablePartition(
internal mutating func stablePartition( count n: Int, subrange: Range<Index>, by belongsInSecondPartition: (Element) throws -> Bool
count n: Int,
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index { ) rethrows -> Index {
if n == 0 { return subrange.lowerBound } if n == 0 { return subrange.lowerBound }
if n == 1 { if n == 1 {
return try belongsInSecondPartition(self[subrange.lowerBound]) return try belongsInSecondPartition(self[subrange.lowerBound])
? subrange.lowerBound ? subrange.lowerBound : subrange.upperBound
: subrange.upperBound
} }
let h = n / 2, i = index(subrange.lowerBound, offsetBy: h) let h = n / 2
let i = index(subrange.lowerBound, offsetBy: h)
let j = try stablePartition( let j = try stablePartition(
count: h, count: h, subrange: subrange.lowerBound..<i, by: belongsInSecondPartition)
subrange: subrange.lowerBound..<i,
by: belongsInSecondPartition)
let k = try stablePartition( let k = try stablePartition(
count: n - h, count: n - h, subrange: i..<subrange.upperBound, by: belongsInSecondPartition)
subrange: i..<subrange.upperBound,
by: belongsInSecondPartition)
return rotate(subrange: j..<k, toStartAt: i) return rotate(subrange: j..<k, toStartAt: i)
} }
/// Moves all elements satisfying the given predicate into a suffix of the /// Moves all elements satisfying the given predicate into a suffix of the
/// given range, preserving the relative order of the elements in both /// given range, preserving the relative order of the elements in both
/// partitions, and returns the start of the resulting suffix. /// partitions, and returns the start of the resulting suffix.
@@ -57,17 +50,14 @@ extension MutableCollection {
/// all elements not satisfying it. /// all elements not satisfying it.
/// ///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection. /// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
@inlinable @inlinable public mutating func stablePartition(
public mutating func stablePartition( subrange: Range<Index>, by belongsInSecondPartition: (Element) throws -> Bool
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index { ) rethrows -> Index {
try stablePartition( try stablePartition(
count: distance(from: subrange.lowerBound, to: subrange.upperBound), count: distance(from: subrange.lowerBound, to: subrange.upperBound), subrange: subrange,
subrange: subrange,
by: belongsInSecondPartition) by: belongsInSecondPartition)
} }
/// Moves all elements satisfying the given predicate into a suffix of this /// Moves all elements satisfying the given predicate into a suffix of this
/// collection, preserving the relative order of the elements in both /// collection, preserving the relative order of the elements in both
/// partitions, and returns the start of the resulting suffix. /// partitions, and returns the start of the resulting suffix.
@@ -77,13 +67,10 @@ extension MutableCollection {
/// all elements not satisfying it. /// all elements not satisfying it.
/// ///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection. /// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
@inlinable @inlinable public mutating func stablePartition(
public mutating func stablePartition( by belongsInSecondPartition: (Element) throws -> Bool
by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index { ) rethrows -> Index {
try stablePartition( try stablePartition(subrange: startIndex..<endIndex, by: belongsInSecondPartition)
subrange: startIndex..<endIndex,
by: belongsInSecondPartition)
} }
} }
@@ -96,16 +83,15 @@ extension MutableCollection {
/// collection, returning the start position of the resulting suffix. /// collection, returning the start position of the resulting suffix.
/// ///
/// - Complexity: O(*n*) where n is the length of the collection. /// - Complexity: O(*n*) where n is the length of the collection.
@inlinable @inlinable public mutating func partition(
public mutating func partition( subrange: Range<Index>, by belongsInSecondPartition: (Element) throws -> Bool
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index { ) rethrows -> Index {
// This version of `partition(subrange:)` is half stable; the elements in // This version of `partition(subrange:)` is half stable; the elements in
// the first partition retain their original relative order. // the first partition retain their original relative order.
guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition) guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition) else {
else { return subrange.upperBound } return subrange.upperBound
}
var j = index(after: i) var j = index(after: i)
while j != subrange.upperBound { while j != subrange.upperBound {
if try !belongsInSecondPartition(self[j]) { if try !belongsInSecondPartition(self[j]) {
@@ -114,7 +100,7 @@ extension MutableCollection {
} }
formIndex(after: &j) formIndex(after: &j)
} }
return i return i
} }
} }
@@ -124,10 +110,8 @@ extension MutableCollection where Self: BidirectionalCollection {
/// collection, returning the start position of the resulting suffix. /// collection, returning the start position of the resulting suffix.
/// ///
/// - Complexity: O(*n*) where n is the length of the collection. /// - Complexity: O(*n*) where n is the length of the collection.
@inlinable @inlinable public mutating func partition(
public mutating func partition( subrange: Range<Index>, by belongsInSecondPartition: (Element) throws -> Bool
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index { ) rethrows -> Index {
var lo = subrange.lowerBound var lo = subrange.lowerBound
var hi = subrange.upperBound var hi = subrange.upperBound
@@ -183,13 +167,12 @@ extension Collection {
/// ///
/// - Complexity: O(log *n*), where *n* is the length of this collection if /// - Complexity: O(log *n*), where *n* is the length of this collection if
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*). /// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
@inlinable @inlinable public func partitioningIndex(where belongsInSecondPartition: (Element) throws -> Bool)
public func partitioningIndex( rethrows -> Index
where belongsInSecondPartition: (Element) throws -> Bool {
) rethrows -> Index {
var n = count var n = count
var l = startIndex var l = startIndex
while n > 0 { while n > 0 {
let half = n / 2 let half = n / 2
let mid = index(l, offsetBy: half) let mid = index(l, offsetBy: half)
@@ -203,4 +186,3 @@ extension Collection {
return l return l
} }
} }
+97 -167
View File
@@ -13,9 +13,7 @@
// nextPermutation() // nextPermutation()
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
extension MutableCollection extension MutableCollection where Self: BidirectionalCollection, Element: Comparable {
where Self: BidirectionalCollection, Element: Comparable
{
/// Permutes this collection's elements through all the lexical orderings. /// Permutes this collection's elements through all the lexical orderings.
/// ///
/// Call `nextPermutation()` repeatedly starting with the collection in /// Call `nextPermutation()` repeatedly starting with the collection in
@@ -28,32 +26,31 @@ extension MutableCollection
/// is in ascending order according to `areInIncreasingOrder`. /// is in ascending order according to `areInIncreasingOrder`.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable internal mutating func nextPermutation(upperBound: Index? = nil) -> Bool {
internal mutating func nextPermutation(upperBound: Index? = nil) -> Bool {
// Ensure we have > 1 element in the collection. // Ensure we have > 1 element in the collection.
guard !isEmpty else { return false } guard !isEmpty else { return false }
var i = index(before: endIndex) var i = index(before: endIndex)
if i == startIndex { return false } if i == startIndex { return false }
let upperBound = upperBound ?? endIndex let upperBound = upperBound ?? endIndex
while true { while true {
let ip1 = i let ip1 = i
formIndex(before: &i) formIndex(before: &i)
// Find the last ascending pair (ie. ..., a, b, ... where a < b) // Find the last ascending pair (ie. ..., a, b, ... where a < b)
if self[i] < self[ip1] { if self[i] < self[ip1] {
// Find the last element greater than self[i] // Find the last element greater than self[i]
// This is _always_ at most `ip1` due to if statement above // This is _always_ at most `ip1` due to if statement above
let j = lastIndex(where: { self[i] < $0 })! let j = lastIndex(where: { self[i] < $0 })!
// At this point we have something like this: // At this point we have something like this:
// 0, 1, 4, 3, 2 // 0, 1, 4, 3, 2
// ^ ^ // ^ ^
// i j // i j
swapAt(i, j) swapAt(i, j)
self.reverse(subrange: ip1 ..< endIndex) self.reverse(subrange: ip1..<endIndex)
// Only return if we've made a change within ..<upperBound region // Only return if we've made a change within ..<upperBound region
if i < upperBound { if i < upperBound {
return true return true
@@ -62,7 +59,7 @@ extension MutableCollection
continue continue
} }
} }
if i == startIndex { if i == startIndex {
self.reverse() self.reverse()
return false return false
@@ -78,95 +75,73 @@ extension MutableCollection
/// A sequence of all the permutations of a collection's elements. /// A sequence of all the permutations of a collection's elements.
public struct Permutations<Base: Collection> { public struct Permutations<Base: Collection> {
/// The base collection to iterate over for permutations. /// The base collection to iterate over for permutations.
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline internal let baseCount: Int
@usableFromInline
internal let baseCount: Int
/// The range of accepted sizes of permutations. /// The range of accepted sizes of permutations.
/// - Note: This may be empty if the attempted range entirely exceeds the /// - Note: This may be empty if the attempted range entirely exceeds the
/// bounds of the size of the `base` collection. /// bounds of the size of the `base` collection.
@usableFromInline @usableFromInline internal let kRange: Range<Int>
internal let kRange: Range<Int>
/// Initializes a `Permutations` for all permutations of `base` of size `k`. /// Initializes a `Permutations` for all permutations of `base` of size `k`.
/// - Parameters: /// - Parameters:
/// - base: The collection to iterate over for permutations /// - base: The collection to iterate over for permutations
/// - k: The expected size of each permutation, or `nil` (default) to /// - k: The expected size of each permutation, or `nil` (default) to
/// iterate over all permutations of the same size as the base collection. /// iterate over all permutations of the same size as the base collection.
@inlinable @inlinable internal init(_ base: Base, k: Int? = nil) {
internal init(_ base: Base, k: Int? = nil) {
let kRange: ClosedRange<Int>? let kRange: ClosedRange<Int>?
if let countToChoose = k { if let countToChoose = k { kRange = countToChoose...countToChoose } else { kRange = nil }
kRange = countToChoose ... countToChoose
} else {
kRange = nil
}
self.init(base, kRange: kRange) self.init(base, kRange: kRange)
} }
/// Initializes a `Permutations` for all combinations of `base` of sizes /// Initializes a `Permutations` for all combinations of `base` of sizes
/// within a given range. /// within a given range.
/// - Parameters: /// - Parameters:
/// - base: The collection to iterate over for permutations. /// - base: The collection to iterate over for permutations.
/// - kRange: The range of accepted sizes of permutations, or `nil` to /// - kRange: The range of accepted sizes of permutations, or `nil` to
/// iterate over all permutations of the same size as the base collection. /// iterate over all permutations of the same size as the base collection.
@inlinable @inlinable internal init<R: RangeExpression>(_ base: Base, kRange: R?) where R.Bound == Int {
internal init<R: RangeExpression>(
_ base: Base, kRange: R?
) where R.Bound == Int {
self.base = base self.base = base
let baseCount = base.count let baseCount = base.count
self.baseCount = baseCount self.baseCount = baseCount
let upperBound = baseCount + 1 let upperBound = baseCount + 1
self.kRange = kRange?.relative(to: 0 ..< .max) self.kRange =
.clamped(to: 0 ..< upperBound) ?? kRange?.relative(to: 0 ..< .max).clamped(to: 0..<upperBound) ?? baseCount..<upperBound
baseCount ..< upperBound
} }
/// The total number of permutations. /// The total number of permutations.
@inlinable @inlinable public var count: Int {
public var count: Int { return kRange.map { stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *) }.reduce(
return kRange.map { 0, +)
stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *)
}.reduce(0, +)
} }
} }
extension Permutations: Sequence { extension Permutations: Sequence {
/// The iterator for a `Permutations` instance. /// The iterator for a `Permutations` instance.
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline internal let baseCount: Int
@usableFromInline
internal let baseCount: Int
/// The current range of accepted sizes of permutations. /// The current range of accepted sizes of permutations.
/// - Note: The range is contracted until empty while iterating over /// - Note: The range is contracted until empty while iterating over
/// permutations of different sizes. When the range is empty, iteration is /// permutations of different sizes. When the range is empty, iteration is
/// finished. /// finished.
@usableFromInline @usableFromInline internal var kRange: Range<Int>
internal var kRange: Range<Int>
/// Whether or not iteration is finished (`kRange` is empty) /// Whether or not iteration is finished (`kRange` is empty)
@inlinable @inlinable internal var isFinished: Bool { return kRange.isEmpty }
internal var isFinished: Bool {
return kRange.isEmpty @usableFromInline internal var indexes: [Base.Index]
}
@inlinable internal init(_ permutations: Permutations) {
@usableFromInline
internal var indexes: [Base.Index]
@inlinable
internal init(_ permutations: Permutations) {
self.base = permutations.base self.base = permutations.base
self.baseCount = permutations.baseCount self.baseCount = permutations.baseCount
self.kRange = permutations.kRange self.kRange = permutations.kRange
self.indexes = Array(permutations.base.indices) self.indexes = Array(permutations.base.indices)
} }
/// Advances the `indexes` array such that the first `countToChoose` /// Advances the `indexes` array such that the first `countToChoose`
/// elements contain the next lexicographic ordering of elements. /// elements contain the next lexicographic ordering of elements.
/// ///
@@ -178,65 +153,55 @@ extension Permutations: Sequence {
/// is in ascending order. /// is in ascending order.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable internal mutating func nextState() -> Bool {
internal mutating func nextState() -> Bool {
let countToChoose = self.kRange.lowerBound let countToChoose = self.kRange.lowerBound
let edge = countToChoose - 1 let edge = countToChoose - 1
// Find first index greater than the one at `edge`. // Find first index greater than the one at `edge`.
if let i = indexes[countToChoose...].firstIndex(where: { indexes[edge] < $0 }) { if let i = indexes[countToChoose...].firstIndex(where: { indexes[edge] < $0 }) {
indexes.swapAt(edge, i) indexes.swapAt(edge, i)
} else { } else {
indexes.reverse(subrange: countToChoose ..< indexes.endIndex) indexes.reverse(subrange: countToChoose..<indexes.endIndex)
// Find last increasing pair below `edge`. // Find last increasing pair below `edge`.
// TODO: This could be indexes[..<edge].adjacentPairs().lastIndex(where: ...) // TODO: This could be indexes[..<edge].adjacentPairs().lastIndex(where: ...)
var lastAscent = edge - 1 var lastAscent = edge - 1
while (lastAscent >= 0 && indexes[lastAscent] >= indexes[lastAscent + 1]) { while lastAscent >= 0 && indexes[lastAscent] >= indexes[lastAscent + 1] { lastAscent -= 1 }
lastAscent -= 1 if lastAscent < 0 { return false }
}
if lastAscent < 0 {
return false
}
// Find rightmost index less than that at `lastAscent`. // Find rightmost index less than that at `lastAscent`.
if let i = indexes[lastAscent...].lastIndex(where: { indexes[lastAscent] < $0 }) { if let i = indexes[lastAscent...].lastIndex(where: { indexes[lastAscent] < $0 }) {
indexes.swapAt(lastAscent, i) indexes.swapAt(lastAscent, i)
} }
indexes.reverse(subrange: (lastAscent + 1) ..< indexes.endIndex) indexes.reverse(subrange: (lastAscent + 1)..<indexes.endIndex)
} }
return true return true
} }
@inlinable @inlinable public mutating func next() -> [Base.Element]? {
public mutating func next() -> [Base.Element]? {
guard !isFinished else { return nil } guard !isFinished else { return nil }
/// Advances `kRange` by incrementing its `lowerBound` until the range is /// Advances `kRange` by incrementing its `lowerBound` until the range is
/// empty, when iteration is finished. /// empty, when iteration is finished.
func advanceKRange() { func advanceKRange() {
kRange.removeFirst() kRange.removeFirst()
indexes = Array(base.indices) indexes = Array(base.indices)
} }
let countToChoose = self.kRange.lowerBound let countToChoose = self.kRange.lowerBound
if countToChoose == 0 { if countToChoose == 0 {
defer { defer { advanceKRange() }
advanceKRange()
}
return [] return []
} }
let permutesFullCollection = (countToChoose == baseCount) let permutesFullCollection = (countToChoose == baseCount)
if permutesFullCollection { if permutesFullCollection {
// If we're permuting the full collection, each iteration is just a // If we're permuting the full collection, each iteration is just a
// call to `nextPermutation` on `indexes`. // call to `nextPermutation` on `indexes`.
defer { defer {
let hasMorePermutations = indexes.nextPermutation() let hasMorePermutations = indexes.nextPermutation()
if !hasMorePermutations { if !hasMorePermutations { advanceKRange() }
advanceKRange()
}
} }
return indexes.map { base[$0] } return indexes.map { base[$0] }
} else { } else {
@@ -244,19 +209,14 @@ extension Permutations: Sequence {
// advance the state. // advance the state.
defer { defer {
let hasMorePermutations = nextState() let hasMorePermutations = nextState()
if !hasMorePermutations { if !hasMorePermutations { advanceKRange() }
advanceKRange()
}
} }
return indexes.prefix(countToChoose).map { base[$0] } return indexes.prefix(countToChoose).map { base[$0] }
} }
} }
} }
@inlinable @inlinable public func makeIterator() -> Iterator { Iterator(self) }
public func makeIterator() -> Iterator {
Iterator(self)
}
} }
extension Permutations: LazySequenceProtocol where Base: LazySequenceProtocol {} extension Permutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
@@ -322,13 +282,9 @@ extension Collection {
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n* /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Permutations` /// is the number of elements in the base collection, since `Permutations`
/// accesses the `count` of the base collection. /// accesses the `count` of the base collection.
@inlinable @inlinable public func permutations<R: RangeExpression>(ofCount kRange: R) -> Permutations<Self>
public func permutations<R: RangeExpression>( where R.Bound == Int { return Permutations(self, kRange: kRange) }
ofCount kRange: R
) -> Permutations<Self> where R.Bound == Int {
return Permutations(self, kRange: kRange)
}
/// Returns a collection of the permutations of this collection of the /// Returns a collection of the permutations of this collection of the
/// specified length. /// specified length.
/// ///
@@ -378,11 +334,8 @@ extension Collection {
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n* /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Permutations` /// is the number of elements in the base collection, since `Permutations`
/// accesses the `count` of the base collection. /// accesses the `count` of the base collection.
@inlinable @inlinable public func permutations(ofCount k: Int? = nil) -> Permutations<Self> {
public func permutations(ofCount k: Int? = nil) -> Permutations<Self> { precondition(k ?? 0 >= 0, "Can't have permutations with a negative number of elements.")
precondition(
k ?? 0 >= 0,
"Can't have permutations with a negative number of elements.")
return Permutations(self, k: k) return Permutations(self, k: k)
} }
} }
@@ -398,77 +351,60 @@ extension Collection {
/// `uniquePermutations` methods on your collection. /// `uniquePermutations` methods on your collection.
public struct UniquePermutations<Base: Collection> { public struct UniquePermutations<Base: Collection> {
/// The base collection to iterate over for permutations. /// The base collection to iterate over for permutations.
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline internal var indexes: [Base.Index]
@usableFromInline
internal var indexes: [Base.Index] @usableFromInline internal let kRange: Range<Int>
@usableFromInline
internal let kRange: Range<Int>
} }
extension UniquePermutations where Base.Element: Hashable { extension UniquePermutations where Base.Element: Hashable {
@inlinable @inlinable internal static func _indexes(_ base: Base) -> [Base.Index] {
internal static func _indexes(_ base: Base) -> [Base.Index] {
let firstIndexesAndCountsByElement = Dictionary( let firstIndexesAndCountsByElement = Dictionary(
base.indices.lazy.map { (base[$0], ($0, 1)) }, base.indices.lazy.map { (base[$0], ($0, 1)) },
uniquingKeysWith: { indexAndCount, _ in (indexAndCount.0, indexAndCount.1 + 1) }) uniquingKeysWith: { indexAndCount, _ in (indexAndCount.0, indexAndCount.1 + 1) })
return firstIndexesAndCountsByElement return firstIndexesAndCountsByElement.values.sorted(by: { $0.0 < $1.0 }).flatMap {
.values.sorted(by: { $0.0 < $1.0 }) index, count in repeatElement(index, count: count)
.flatMap { index, count in repeatElement(index, count: count) } }
}
@inlinable
internal init(_ elements: Base) {
self.indexes = Self._indexes(elements)
self.base = elements
self.kRange = self.indexes.count ..< (self.indexes.count + 1)
} }
@inlinable @inlinable internal init(_ elements: Base) {
internal init<R: RangeExpression>(_ base: Base, _ range: R) self.indexes = Self._indexes(elements)
where R.Bound == Int self.base = elements
{ self.kRange = self.indexes.count..<(self.indexes.count + 1)
}
@inlinable internal init<R: RangeExpression>(_ base: Base, _ range: R) where R.Bound == Int {
self.indexes = Self._indexes(base) self.indexes = Self._indexes(base)
self.base = base self.base = base
let upperBound = self.indexes.count + 1 let upperBound = self.indexes.count + 1
self.kRange = range.relative(to: 0 ..< .max) self.kRange = range.relative(to: 0 ..< .max).clamped(to: 0..<upperBound)
.clamped(to: 0 ..< upperBound)
} }
} }
extension UniquePermutations: Sequence { extension UniquePermutations: Sequence {
/// The iterator for a `UniquePermutations` instance. /// The iterator for a `UniquePermutations` instance.
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline
internal var indexes: [Base.Index]
@usableFromInline
internal var lengths: Range<Int>
@usableFromInline @usableFromInline internal var indexes: [Base.Index]
internal var initial = true
@inlinable @usableFromInline internal var lengths: Range<Int>
internal init(_ elements: Base, indexes: [Base.Index], lengths: Range<Int>) {
@usableFromInline internal var initial = true
@inlinable internal init(_ elements: Base, indexes: [Base.Index], lengths: Range<Int>) {
self.base = elements self.base = elements
self.indexes = indexes self.indexes = indexes
self.lengths = lengths self.lengths = lengths
} }
@inlinable @inlinable public mutating func next() -> [Base.Element]? {
public mutating func next() -> [Base.Element]? {
// In the end case, `lengths` is an empty range. // In the end case, `lengths` is an empty range.
if lengths.isEmpty { if lengths.isEmpty { return nil }
return nil
}
// The first iteration must produce the original sorted array, before any // The first iteration must produce the original sorted array, before any
// permutations. We skip the permutation the first time so that we can // permutations. We skip the permutation the first time so that we can
// always mutate the array _before_ returning a slice, which avoids // always mutate the array _before_ returning a slice, which avoids
@@ -481,17 +417,14 @@ extension UniquePermutations: Sequence {
if !indexes.nextPermutation(upperBound: lengths.lowerBound) { if !indexes.nextPermutation(upperBound: lengths.lowerBound) {
lengths.removeFirst() lengths.removeFirst()
if lengths.isEmpty { if lengths.isEmpty { return nil }
return nil
}
} }
return indexes[..<lengths.lowerBound].map { base[$0] } return indexes[..<lengths.lowerBound].map { base[$0] }
} }
} }
@inlinable @inlinable public func makeIterator() -> Iterator {
public func makeIterator() -> Iterator {
Iterator(base, indexes: indexes, lengths: kRange) Iterator(base, indexes: indexes, lengths: kRange)
} }
} }
@@ -539,7 +472,7 @@ extension Collection where Element: Hashable {
/// collection. /// collection.
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self> { public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self> {
if let k = k { if let k = k {
return UniquePermutations(self, k ..< (k + 1)) return UniquePermutations(self, k..<(k + 1))
} else { } else {
return UniquePermutations(self) return UniquePermutations(self)
} }
@@ -575,8 +508,5 @@ extension Collection where Element: Hashable {
/// - Complexity: O(*n*), where *n* is the number of elements in this /// - Complexity: O(*n*), where *n* is the number of elements in this
/// collection. /// collection.
public func uniquePermutations<R: RangeExpression>(ofCount kRange: R) -> UniquePermutations<Self> public func uniquePermutations<R: RangeExpression>(ofCount kRange: R) -> UniquePermutations<Self>
where R.Bound == Int where R.Bound == Int { UniquePermutations(self, kRange) }
{
UniquePermutations(self, kRange)
}
} }
+146 -200
View File
@@ -12,15 +12,12 @@
/// A sequence that represents the product of two sequences' elements. /// A sequence that represents the product of two sequences' elements.
public struct Product2<Base1: Sequence, Base2: Collection> { public struct Product2<Base1: Sequence, Base2: Collection> {
/// The outer sequence in the product. /// The outer sequence in the product.
@usableFromInline @usableFromInline internal let base1: Base1
internal let base1: Base1
/// The inner sequence in the product. /// The inner sequence in the product.
@usableFromInline @usableFromInline internal let base2: Base2
internal let base2: Base2
@inlinable internal init(_ base1: Base1, _ base2: Base2) {
@inlinable
internal init(_ base1: Base1, _ base2: Base2) {
self.base1 = base1 self.base1 = base1
self.base2 = base2 self.base2 = base2
} }
@@ -28,29 +25,22 @@ public struct Product2<Base1: Sequence, Base2: Collection> {
extension Product2: Sequence { extension Product2: Sequence {
public typealias Element = (Base1.Element, Base2.Element) public typealias Element = (Base1.Element, Base2.Element)
/// The iterator for a `Product2` sequence. /// The iterator for a `Product2` sequence.
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline internal var i1: Base1.Iterator
internal var i1: Base1.Iterator @usableFromInline internal var i2: Base2.Iterator
@usableFromInline @usableFromInline internal var element1: Base1.Element?
internal var i2: Base2.Iterator @usableFromInline internal let base2: Base2
@usableFromInline
internal var element1: Base1.Element?
@usableFromInline
internal let base2: Base2
@inlinable @inlinable internal init(_ c: Product2) {
internal init(_ c: Product2) {
self.base2 = c.base2 self.base2 = c.base2
self.i1 = c.base1.makeIterator() self.i1 = c.base1.makeIterator()
self.i2 = c.base2.makeIterator() self.i2 = c.base2.makeIterator()
self.element1 = nil self.element1 = nil
} }
@inlinable @inlinable public mutating func next() -> (Base1.Element, Base2.Element)? {
public mutating func next() -> (Base1.Element,
Base2.Element)? {
// This is the initial state, where i1.next() has never // This is the initial state, where i1.next() has never
// been called, or the final state, where i1.next() has // been called, or the final state, where i1.next() has
// already returned nil. // already returned nil.
@@ -59,106 +49,78 @@ extension Product2: Sequence {
// once Base1 is exhausted, return `nil` forever // once Base1 is exhausted, return `nil` forever
if element1 == nil { return nil } if element1 == nil { return nil }
} }
// Get the next element from the second sequence, if not // Get the next element from the second sequence, if not
// at end. // at end.
if let element2 = i2.next() { if let element2 = i2.next() { return (element1!, element2) }
return (element1!, element2)
}
// We've reached the end of the second sequence, so: // We've reached the end of the second sequence, so:
// 1) Get the next element of the first sequence, if exists // 1) Get the next element of the first sequence, if exists
// 2) Restart iteration of the second sequence // 2) Restart iteration of the second sequence
// 3) Get the first element of the second sequence, if exists // 3) Get the first element of the second sequence, if exists
element1 = i1.next() element1 = i1.next()
guard let element1 = element1 guard let element1 = element1 else { return nil }
else { return nil }
i2 = base2.makeIterator() i2 = base2.makeIterator()
if let element2 = i2.next() { if let element2 = i2.next() { return (element1, element2) } else { return nil }
return (element1, element2)
} else {
return nil
}
} }
} }
public func makeIterator() -> Iterator { public func makeIterator() -> Iterator { return Iterator(self) }
return Iterator(self)
}
} }
extension Product2: Collection where Base1: Collection { extension Product2: Collection where Base1: Collection {
/// The index type for a `Product2` collection. /// The index type for a `Product2` collection.
public struct Index: Comparable { public struct Index: Comparable {
@usableFromInline @usableFromInline internal var i1: Base1.Index
internal var i1: Base1.Index @usableFromInline internal var i2: Base2.Index
@usableFromInline
internal var i2: Base2.Index @inlinable internal init(i1: Base1.Index, i2: Base2.Index) {
@inlinable
internal init(i1: Base1.Index, i2: Base2.Index) {
self.i1 = i1 self.i1 = i1
self.i2 = i2 self.i2 = i2
} }
@inlinable @inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
public static func < (lhs: Index, rhs: Index) -> Bool {
(lhs.i1, lhs.i2) < (rhs.i1, rhs.i2) (lhs.i1, lhs.i2) < (rhs.i1, rhs.i2)
} }
} }
@inlinable @inlinable public var count: Int { base1.count * base2.count }
public var count: Int {
base1.count * base2.count @inlinable public var startIndex: Index {
Index(i1: base2.isEmpty ? base1.endIndex : base1.startIndex, i2: base2.startIndex)
} }
@inlinable @inlinable public var endIndex: Index {
public var startIndex: Index {
Index(
i1: base2.isEmpty ? base1.endIndex : base1.startIndex,
i2: base2.startIndex)
}
@inlinable
public var endIndex: Index {
// `base2.startIndex` simplifies index calculations. // `base2.startIndex` simplifies index calculations.
Index(i1: base1.endIndex, i2: base2.startIndex) Index(i1: base1.endIndex, i2: base2.startIndex)
} }
@inlinable @inlinable public subscript(position: Index) -> (Base1.Element, Base2.Element) {
public subscript(position: Index) -> (Base1.Element,
Base2.Element) {
(base1[position.i1], base2[position.i2]) (base1[position.i1], base2[position.i2])
} }
/// Forms an index from a pair of base indices, normalizing /// Forms an index from a pair of base indices, normalizing
/// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if /// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if
/// necessary. /// necessary.
@inlinable @inlinable internal func normalizeIndex(_ i1: Base1.Index, _ i2: Base2.Index) -> Index {
internal func normalizeIndex(_ i1: Base1.Index, _ i2: Base2.Index) -> Index {
i2 == base2.endIndex i2 == base2.endIndex
? Index(i1: base1.index(after: i1), i2: base2.startIndex) ? Index(i1: base1.index(after: i1), i2: base2.startIndex) : Index(i1: i1, i2: i2)
: Index(i1: i1, i2: i2)
} }
@inlinable @inlinable public func index(after i: Index) -> Index {
public func index(after i: Index) -> Index {
precondition(i.i1 != base1.endIndex, "Can't advance past endIndex") precondition(i.i1 != base1.endIndex, "Can't advance past endIndex")
return normalizeIndex(i.i1, base2.index(after: i.i2)) return normalizeIndex(i.i1, base2.index(after: i.i2))
} }
@inlinable @inlinable public func distance(from start: Index, to end: Index) -> Int {
public func distance(from start: Index, to end: Index) -> Int { guard start.i1 <= end.i1 else { return -distance(from: end, to: start) }
guard start.i1 <= end.i1 guard start.i1 != end.i1 else { return base2.distance(from: start.i2, to: end.i2) }
else { return -distance(from: end, to: start) }
guard start.i1 != end.i1
else { return base2.distance(from: start.i2, to: end.i2) }
// The number of full cycles through `base2` between `start` and `end`, // The number of full cycles through `base2` between `start` and `end`,
// excluding the cycles that `start` and `end` are on. // excluding the cycles that `start` and `end` are on.
let fullBase2Cycles = base1[start.i1..<end.i1].count - 1 let fullBase2Cycles = base1[start.i1..<end.i1].count - 1
if start.i2 <= end.i2 { if start.i2 <= end.i2 {
// start.i2 // start.i2
// v // v
@@ -169,14 +131,12 @@ extension Product2: Collection where Base1: Collection {
// end.i1 > [l l l c c c c c c|r r r] // end.i1 > [l l l c c c c c c|r r r]
// ^ // ^
// end.i2 // end.i2
let left = base2[..<start.i2].count let left = base2[..<start.i2].count
let center = base2[start.i2..<end.i2].count let center = base2[start.i2..<end.i2].count
let right = base2[end.i2...].count let right = base2[end.i2...].count
return center + right return center + right + fullBase2Cycles * (left + center + right) + left + center
+ fullBase2Cycles * (left + center + right)
+ left + center
} else { } else {
// start.i2 // start.i2
// v // v
@@ -187,80 +147,68 @@ extension Product2: Collection where Base1: Collection {
// end.i1 > [l l l|c c c c c c r r r] // end.i1 > [l l l|c c c c c c r r r]
// ^ // ^
// end.i2 // end.i2
let left = base2[..<end.i2].count let left = base2[..<end.i2].count
let right = base2[start.i2...].count let right = base2[start.i2...].count
// We can avoid traversing `base2[end.i2..<start.i2]` if `start` and `end` // We can avoid traversing `base2[end.i2..<start.i2]` if `start` and `end`
// are on consecutive cycles. // are on consecutive cycles.
guard fullBase2Cycles > 0 else { return right + left } guard fullBase2Cycles > 0 else { return right + left }
let center = base2[end.i2..<start.i2].count let center = base2[end.i2..<start.i2].count
return right return right + fullBase2Cycles * (left + center + right) + left
+ fullBase2Cycles * (left + center + right)
+ left
}
}
@inlinable
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)
}
@inlinable
public func index(
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
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)
} }
} }
@inlinable @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
internal func offsetForward(_ i: Index, by distance: Int) -> Index { guard distance != 0 else { return i }
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") } return distance > 0 ? offsetForward(i, by: distance) : offsetBackward(i, by: -distance)
}
@inlinable public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index?
{
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)
}
}
@inlinable internal 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 return index
} }
@inlinable @inlinable internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
internal func offsetBackward(_ i: Index, by distance: Int) -> Index { guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) else {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) fatalError("Index is out of bounds")
else { fatalError("Index is out of bounds") } }
return index return index
} }
@inlinable @inlinable internal func offsetForward(_ i: Index, by distance: Int, limitedBy limit: Index)
internal func offsetForward( -> Index?
_ i: Index, by distance: Int, limitedBy limit: Index {
) -> Index? {
assert(distance >= 0) assert(distance >= 0)
assert(limit >= i) assert(limit >= i)
if limit.i1 == i.i1 { if limit.i1 == i.i1 {
// Delegate to `base2` if the offset is limited to `i.i1`. // Delegate to `base2` if the offset is limited to `i.i1`.
// //
// i.i2 limit.i2 // i.i2 limit.i2
// v v // v v
// i.i1 > [x x x|x x x x x x|x x x] // i.i1 > [x x x|x x x x x x|x x x]
return base2.index(i.i2, offsetBy: distance, limitedBy: limit.i2) return base2.index(i.i2, offsetBy: distance, limitedBy: limit.i2).map { i2 in
.map { i2 in Index(i1: i.i1, i2: i2) } Index(i1: i.i1, i2: i2)
}
} }
if let i2 = base2.index(i.i2, offsetBy: distance, limitedBy: base2.endIndex) { if let i2 = base2.index(i.i2, offsetBy: distance, limitedBy: base2.endIndex) {
// `distance` does not overflow `base2[i.i2...]`. // `distance` does not overflow `base2[i.i2...]`.
// //
@@ -268,14 +216,14 @@ extension Product2: Collection where Base1: Collection {
// v v // v v
// i.i1 > [x x x|x x x x x x|x x x] // i.i1 > [x x x|x x x x x x|x x x]
// [ |> > > > > >| ] (`distance`) // [ |> > > > > >| ] (`distance`)
return normalizeIndex(i.i1, i2) return normalizeIndex(i.i1, i2)
} }
let suffixCount = base2[i.i2...].count let suffixCount = base2[i.i2...].count
let remaining = distance - suffixCount let remaining = distance - suffixCount
let nextI1 = base1.index(after: i.i1) let nextI1 = base1.index(after: i.i1)
if limit.i1 == nextI1 { if limit.i1 == nextI1 {
// Delegate to `base2` if the offset is limited to `nextI1`. // Delegate to `base2` if the offset is limited to `nextI1`.
// //
@@ -285,11 +233,12 @@ extension Product2: Collection where Base1: Collection {
// nextI1 > [x x x x x x x x x|x x x] // nextI1 > [x x x x x x x x x|x x x]
// ^ // ^
// limit.i2 // limit.i2
return base2.index(base2.startIndex, offsetBy: remaining, limitedBy: limit.i2) return base2.index(base2.startIndex, offsetBy: remaining, limitedBy: limit.i2).map { i2 in
.map { i2 in Index(i1: nextI1, i2: i2) } Index(i1: nextI1, i2: i2)
}
} }
if let i2 = base2.index(base2.startIndex, offsetBy: remaining, limitedBy: i.i2) { if let i2 = base2.index(base2.startIndex, offsetBy: remaining, limitedBy: i.i2) {
// `remaining` does not overflow `base2[..<i.i2]`. // `remaining` does not overflow `base2[..<i.i2]`.
// //
@@ -301,43 +250,45 @@ extension Product2: Collection where Base1: Collection {
// nextI1 > [x x x|x x x x x x x x x] // nextI1 > [x x x|x x x x x x x x x]
// ^ // ^
// i2 // i2
return Index(i1: nextI1, i2: i2) return Index(i1: nextI1, i2: i2)
} }
let prefixCount = base2[..<i.i2].count let prefixCount = base2[..<i.i2].count
let base2Count = prefixCount + suffixCount let base2Count = prefixCount + suffixCount
let base1Distance = remaining / base2Count let base1Distance = remaining / base2Count
guard let i1 = base1.index(nextI1, offsetBy: base1Distance, limitedBy: limit.i1) guard let i1 = base1.index(nextI1, offsetBy: base1Distance, limitedBy: limit.i1) else {
else { return nil } return nil
}
// The distance from `base2.startIndex` to the target. // The distance from `base2.startIndex` to the target.
let base2Distance = remaining % base2Count let base2Distance = remaining % base2Count
let base2Limit = limit.i1 == i1 ? limit.i2 : base2.endIndex let base2Limit = limit.i1 == i1 ? limit.i2 : base2.endIndex
return base2.index(base2.startIndex, offsetBy: base2Distance, limitedBy: base2Limit) return base2.index(base2.startIndex, offsetBy: base2Distance, limitedBy: base2Limit).map { i2 in
.map { i2 in Index(i1: i1, i2: i2) } Index(i1: i1, i2: i2)
}
} }
@inlinable @inlinable internal func offsetBackward(_ i: Index, by distance: Int, limitedBy limit: Index)
internal func offsetBackward( -> Index?
_ i: Index, by distance: Int, limitedBy limit: Index {
) -> Index? {
assert(distance >= 0) assert(distance >= 0)
assert(limit <= i) assert(limit <= i)
if limit.i1 == i.i1 { if limit.i1 == i.i1 {
// Delegate to `base2` if the offset is limited to `i.i1`. // Delegate to `base2` if the offset is limited to `i.i1`.
// //
// limit.i2 i.i2 // limit.i2 i.i2
// v v // v v
// i.i1 > [x x x|x x x x x x|x x x] // i.i1 > [x x x|x x x x x x|x x x]
return base2.index(i.i2, offsetBy: -distance, limitedBy: limit.i2) return base2.index(i.i2, offsetBy: -distance, limitedBy: limit.i2).map { i2 in
.map { i2 in Index(i1: i.i1, i2: i2) } Index(i1: i.i1, i2: i2)
}
} }
if let i2 = base2.index(i.i2, offsetBy: -distance, limitedBy: base2.startIndex) { if let i2 = base2.index(i.i2, offsetBy: -distance, limitedBy: base2.startIndex) {
// `distance` does not underflow `base2[..<i.i2]`. // `distance` does not underflow `base2[..<i.i2]`.
// //
@@ -345,14 +296,14 @@ extension Product2: Collection where Base1: Collection {
// v v // v v
// i.i1 > [x x x|x x x x x x|x x x] // i.i1 > [x x x|x x x x x x|x x x]
// [ |< < < < < <| ] (`distance`) // [ |< < < < < <| ] (`distance`)
return Index(i1: i.i1, i2: i2) return Index(i1: i.i1, i2: i2)
} }
let prefixCount = base2[..<i.i2].count let prefixCount = base2[..<i.i2].count
let remaining = distance - prefixCount let remaining = distance - prefixCount
let previousI1 = base1.index(i.i1, offsetBy: -1) let previousI1 = base1.index(i.i1, offsetBy: -1)
if limit.i1 == previousI1 { if limit.i1 == previousI1 {
// Delegate to `base2` if the offset is limited to `previousI1`. // Delegate to `base2` if the offset is limited to `previousI1`.
// //
@@ -362,11 +313,12 @@ extension Product2: Collection where Base1: Collection {
// i.i1 > [x x x x x x x x x|x x x] // i.i1 > [x x x x x x x x x|x x x]
// ^ // ^
// i.i2 // i.i2
return base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: limit.i2) return base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: limit.i2).map { i2 in
.map { i2 in Index(i1: previousI1, i2: i2) } Index(i1: previousI1, i2: i2)
}
} }
if let i2 = base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: i.i2) { if let i2 = base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: i.i2) {
// `remaining` does not underflow `base2[i.i2...]`. // `remaining` does not underflow `base2[i.i2...]`.
// //
@@ -378,17 +330,17 @@ extension Product2: Collection where Base1: Collection {
// i.i1 > [x x x|x x x x x x x x x] // i.i1 > [x x x|x x x x x x x x x]
// ^ // ^
// i.i2 // i.i2
return Index(i1: previousI1, i2: i2) return Index(i1: previousI1, i2: i2)
} }
let suffixCount = base2[i.i2...].count let suffixCount = base2[i.i2...].count
let base2Count = prefixCount + suffixCount let base2Count = prefixCount + suffixCount
let base1Distance = remaining / base2Count let base1Distance = remaining / base2Count
// The distance from `base2.endIndex` to the target. // The distance from `base2.endIndex` to the target.
let base2Distance = remaining % base2Count let base2Distance = remaining % base2Count
if base2Distance == 0 { if base2Distance == 0 {
// We end up exactly between two cycles, so `base1Distance` would // We end up exactly between two cycles, so `base1Distance` would
// overshoot the target by 1. // overshoot the target by 1.
@@ -401,7 +353,7 @@ extension Product2: Collection where Base1: Collection {
// i.i1 > [x x x|x x x x x x x x x] // i.i1 > [x x x|x x x x x x x x x]
// ^ // ^
// i.i2 // i.i2
if let i1 = base1.index(previousI1, offsetBy: -(base1Distance - 1), limitedBy: limit.i1) { if let i1 = base1.index(previousI1, offsetBy: -(base1Distance - 1), limitedBy: limit.i1) {
let index = Index(i1: i1, i2: base2.startIndex) let index = Index(i1: i1, i2: base2.startIndex)
return index < limit ? nil : index return index < limit ? nil : index
@@ -409,27 +361,24 @@ extension Product2: Collection where Base1: Collection {
return nil return nil
} }
} }
guard let i1 = base1.index(previousI1, offsetBy: -base1Distance, limitedBy: limit.i1) guard let i1 = base1.index(previousI1, offsetBy: -base1Distance, limitedBy: limit.i1) else {
else { return nil } return nil
}
let base2Limit = limit.i1 == i1 ? limit.i2 : base2.startIndex let base2Limit = limit.i1 == i1 ? limit.i2 : base2.startIndex
return base2.index(base2.endIndex, offsetBy: -base2Distance, limitedBy: base2Limit) return base2.index(base2.endIndex, offsetBy: -base2Distance, limitedBy: base2Limit).map { i2 in
.map { i2 in Index(i1: i1, i2: i2) } Index(i1: i1, i2: i2)
}
} }
} }
extension Product2: BidirectionalCollection extension Product2: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
{ @inlinable public func index(before i: Index) -> Index {
@inlinable precondition(i != startIndex, "Can't move before startIndex")
public func index(before i: Index) -> Index {
precondition(i != startIndex,
"Can't move before startIndex")
if i.i2 == base2.startIndex { if i.i2 == base2.startIndex {
return Index( return Index(i1: base1.index(before: i.i1), i2: base2.index(before: base2.endIndex))
i1: base1.index(before: i.i1),
i2: base2.index(before: base2.endIndex))
} else { } else {
return Index(i1: i.i1, i2: base2.index(before: i.i2)) return Index(i1: i.i1, i2: base2.index(before: i.i2))
} }
@@ -437,7 +386,7 @@ extension Product2: BidirectionalCollection
} }
extension Product2: RandomAccessCollection extension Product2: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {} where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {} extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {}
@@ -478,9 +427,6 @@ extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Has
/// - s2: The second sequence to iterate over. /// - s2: The second sequence to iterate over.
/// ///
/// - Complexity: O(1) /// - Complexity: O(1)
@inlinable @inlinable public func product<Base1: Sequence, Base2: Collection>(_ s1: Base1, _ s2: Base2)
public func product<Base1: Sequence, Base2: Collection>( -> Product2<Base1, Base2>
_ s1: Base1, _ s2: Base2 { return Product2(s1, s2) }
) -> Product2<Base1, Base2> {
return Product2(s1, s2)
}
+37 -52
View File
@@ -10,8 +10,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// For log(_:) and root(_:_:) // For log(_:) and root(_:_:)
@_implementationOnly @_implementationOnly import RealModule
import RealModule
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// randomStableSample(count:) // randomStableSample(count:)
@@ -28,18 +27,17 @@ extension Collection {
/// collection's count, then this method returns the full collection. /// collection's count, then this method returns the full collection.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable public func randomStableSample<G: RandomNumberGenerator>(
public func randomStableSample<G: RandomNumberGenerator>(
count k: Int, using rng: inout G count k: Int, using rng: inout G
) -> [Element] { ) -> [Element] {
guard k > 0 else { return [] } guard k > 0 else { return [] }
var remainingCount = count var remainingCount = count
guard k < remainingCount else { return Array(self) } guard k < remainingCount else { return Array(self) }
var result: [Element] = [] var result: [Element] = []
result.reserveCapacity(k) result.reserveCapacity(k)
var i = startIndex var i = startIndex
var countToSelect = k var countToSelect = k
while countToSelect > 0 { while countToSelect > 0 {
@@ -52,10 +50,10 @@ extension Collection {
formIndex(after: &i) formIndex(after: &i)
remainingCount -= 1 remainingCount -= 1
} }
return result return result
} }
/// Randomly selects the specified number of elements from this collection, /// Randomly selects the specified number of elements from this collection,
/// maintaining their relative order. /// maintaining their relative order.
/// ///
@@ -68,8 +66,7 @@ extension Collection {
/// collection's count, then this method returns the full collection. /// collection's count, then this method returns the full collection.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable public func randomStableSample(count k: Int) -> [Element] {
public func randomStableSample(count k: Int) -> [Element] {
var g = SystemRandomNumberGenerator() var g = SystemRandomNumberGenerator()
return randomStableSample(count: k, using: &g) return randomStableSample(count: k, using: &g)
} }
@@ -83,17 +80,13 @@ extension Collection {
// Algorithms of Time Complexity O(n(1 + log(N/n)))": // Algorithms of Time Complexity O(n(1 + log(N/n)))":
// https://dl.acm.org/doi/pdf/10.1145/198429.198435 // https://dl.acm.org/doi/pdf/10.1145/198429.198435
@usableFromInline @usableFromInline internal func nextW<G: RandomNumberGenerator>(k: Int, using rng: inout G)
internal func nextW<G: RandomNumberGenerator>( -> Double
k: Int, using rng: inout G { Double.root(.random(in: 0..<1, using: &rng), k) }
) -> Double {
Double.root(.random(in: 0..<1, using: &rng), k)
}
@usableFromInline @usableFromInline internal func nextOffset<G: RandomNumberGenerator>(w: Double, using rng: inout G)
internal func nextOffset<G: RandomNumberGenerator>( -> Int
w: Double, using rng: inout G {
) -> Int {
let offset = Double.log(.random(in: 0..<1, using: &rng)) / .log(onePlus: -w) let offset = Double.log(.random(in: 0..<1, using: &rng)) / .log(onePlus: -w)
return offset < Double(Int.max) ? Int(offset) : Int.max return offset < Double(Int.max) ? Int(offset) : Int.max
} }
@@ -111,31 +104,30 @@ extension Collection {
/// - Complexity: O(*k*), where *k* is the number of elements to select, if /// - Complexity: O(*k*), where *k* is the number of elements to select, if
/// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*), /// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),
/// where *n* is the length of the collection. /// where *n* is the length of the collection.
@inlinable @inlinable public func randomSample<G: RandomNumberGenerator>(count k: Int, using rng: inout G)
public func randomSample<G: RandomNumberGenerator>( -> [Element]
count k: Int, using rng: inout G {
) -> [Element] {
guard k > 0 else { return [] } guard k > 0 else { return [] }
var w = 1.0 var w = 1.0
var result: [Element] = [] var result: [Element] = []
result.reserveCapacity(k) result.reserveCapacity(k)
// Fill the reservoir with the first `k` elements. // Fill the reservoir with the first `k` elements.
var i = startIndex var i = startIndex
while i < endIndex, result.count < k { while i < endIndex, result.count < k {
result.append(self[i]) result.append(self[i])
formIndex(after: &i) formIndex(after: &i)
} }
while i < endIndex { while i < endIndex {
// Calculate the next value of w. // Calculate the next value of w.
w *= nextW(k: k, using: &rng) w *= nextW(k: k, using: &rng)
// Find index of the next element to swap into the reservoir. // Find index of the next element to swap into the reservoir.
let offset = nextOffset(w: w, using: &rng) let offset = nextOffset(w: w, using: &rng)
i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex
if i < endIndex { if i < endIndex {
// Swap selected element with a randomly chosen one in the reservoir. // Swap selected element with a randomly chosen one in the reservoir.
let j = Int.random(in: 0..<result.count, using: &rng) let j = Int.random(in: 0..<result.count, using: &rng)
@@ -143,12 +135,12 @@ extension Collection {
formIndex(after: &i) formIndex(after: &i)
} }
} }
// FIXME: necessary? // FIXME: necessary?
result.shuffle(using: &rng) result.shuffle(using: &rng)
return result return result
} }
/// Randomly selects the specified number of elements from this collection. /// Randomly selects the specified number of elements from this collection.
/// ///
/// This method is equivalent to calling `randomSample(k:using:)`, passing in /// This method is equivalent to calling `randomSample(k:using:)`, passing in
@@ -163,8 +155,7 @@ extension Collection {
/// - Complexity: O(*k*), where *k* is the number of elements to select, if /// - Complexity: O(*k*), where *k* is the number of elements to select, if
/// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*), /// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),
/// where *n* is the length of the collection. /// where *n* is the length of the collection.
@inlinable @inlinable public func randomSample(count k: Int) -> [Element] {
public func randomSample(count k: Int) -> [Element] {
var g = SystemRandomNumberGenerator() var g = SystemRandomNumberGenerator()
return randomSample(count: k, using: &g) return randomSample(count: k, using: &g)
} }
@@ -181,45 +172,40 @@ extension Sequence {
/// method returns the full sequence. /// method returns the full sequence.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the sequence. /// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable @inlinable public func randomSample<G: RandomNumberGenerator>(count k: Int, using rng: inout G)
public func randomSample<G: RandomNumberGenerator>( -> [Element]
count k: Int, using rng: inout G {
) -> [Element] {
guard k > 0 else { return [] } guard k > 0 else { return [] }
var w = 1.0 var w = 1.0
var result: [Element] = [] var result: [Element] = []
result.reserveCapacity(k) result.reserveCapacity(k)
// Fill the reservoir with the first `k` elements. // Fill the reservoir with the first `k` elements.
var iterator = makeIterator() var iterator = makeIterator()
while result.count < k, let el = iterator.next() { while result.count < k, let el = iterator.next() { result.append(el) }
result.append(el)
}
while true { while true {
// Calculate the next value of w. // Calculate the next value of w.
w *= nextW(k: k, using: &rng) w *= nextW(k: k, using: &rng)
// Find the offset of the next element to swap into the reservoir. // Find the offset of the next element to swap into the reservoir.
var offset = nextOffset(w: w, using: &rng) var offset = nextOffset(w: w, using: &rng)
// Skip over `offset` elements to find the selected element. // Skip over `offset` elements to find the selected element.
while offset > 0, let _ = iterator.next() { while offset > 0, let _ = iterator.next() { offset -= 1 }
offset -= 1
}
guard let nextElement = iterator.next() else { break } guard let nextElement = iterator.next() else { break }
// Swap selected element with a randomly chosen one in the reservoir. // Swap selected element with a randomly chosen one in the reservoir.
let j = Int.random(in: 0..<result.count, using: &rng) let j = Int.random(in: 0..<result.count, using: &rng)
result[j] = nextElement result[j] = nextElement
} }
// FIXME: necessary? // FIXME: necessary?
result.shuffle(using: &rng) result.shuffle(using: &rng)
return result return result
} }
/// Randomly selects the specified number of elements from this sequence. /// Randomly selects the specified number of elements from this sequence.
/// ///
/// This method is equivalent to calling `randomSample(k:using:)`, passing in /// This method is equivalent to calling `randomSample(k:using:)`, passing in
@@ -232,8 +218,7 @@ extension Sequence {
/// method returns the full sequence. /// method returns the full sequence.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the sequence. /// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable @inlinable public func randomSample(count k: Int) -> [Element] {
public func randomSample(count k: Int) -> [Element] {
var g = SystemRandomNumberGenerator() var g = SystemRandomNumberGenerator()
return randomSample(count: k, using: &g) return randomSample(count: k, using: &g)
} }
+108 -224
View File
@@ -34,14 +34,10 @@ extension LazySequenceProtocol {
/// elements. /// elements.
/// ///
/// - Complexity: O(1) /// - Complexity: O(1)
@inlinable @inlinable public func reductions<Result>(
public func reductions<Result>( _ initial: Result, _ transform: @escaping (Result, Element) -> Result
_ initial: Result,
_ transform: @escaping (Result, Element) -> Result
) -> ExclusiveReductions<Result, Self> { ) -> ExclusiveReductions<Result, Self> {
return reductions(into: initial) { result, element in return reductions(into: initial) { result, element in result = transform(result, element) }
result = transform(result, element)
}
} }
/// Returns a sequence containing the accumulated results of combining the /// Returns a sequence containing the accumulated results of combining the
@@ -65,10 +61,8 @@ extension LazySequenceProtocol {
/// elements. /// elements.
/// ///
/// - Complexity: O(1) /// - Complexity: O(1)
@inlinable @inlinable public func reductions<Result>(
public func reductions<Result>( into initial: Result, _ transform: @escaping (inout Result, Element) -> Void
into initial: Result,
_ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductions<Result, Self> { ) -> ExclusiveReductions<Result, Self> {
ExclusiveReductions(base: self, initial: initial, transform: transform) ExclusiveReductions(base: self, initial: initial, transform: transform)
} }
@@ -110,10 +104,8 @@ extension Sequence {
/// - Returns: An array of the initial value followed by the reduced elements. /// - Returns: An array of the initial value followed by the reduced elements.
/// ///
/// - Complexity: O(_n_), where _n_ is the length of the sequence. /// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable @inlinable public func reductions<Result>(
public func reductions<Result>( _ initial: Result, _ transform: (Result, Element) throws -> Result
_ initial: Result,
_ transform: (Result, Element) throws -> Result
) rethrows -> [Result] { ) rethrows -> [Result] {
return try reductions(into: initial) { result, element in return try reductions(into: initial) { result, element in
result = try transform(result, element) result = try transform(result, element)
@@ -154,10 +146,8 @@ extension Sequence {
/// - Returns: An array of the initial value followed by the reduced elements. /// - Returns: An array of the initial value followed by the reduced elements.
/// ///
/// - Complexity: O(_n_), where _n_ is the length of the sequence. /// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable @inlinable public func reductions<Result>(
public func reductions<Result>( into initial: Result, _ transform: (inout Result, Element) throws -> Void
into initial: Result,
_ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result] { ) rethrows -> [Result] {
var output = [Result]() var output = [Result]()
@@ -177,20 +167,14 @@ extension Sequence {
/// A sequence of applying a transform to the element of a sequence and the /// A sequence of applying a transform to the element of a sequence and the
/// previously transformed result. /// previously transformed result.
public struct ExclusiveReductions<Result, Base: Sequence> { public struct ExclusiveReductions<Result, Base: Sequence> {
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline @usableFromInline internal let initial: Result
internal let initial: Result
@usableFromInline @usableFromInline internal let transform: (inout Result, Base.Element) -> Void
internal let transform: (inout Result, Base.Element) -> Void
@inlinable @inlinable internal init(
internal init( base: Base, initial: Result, transform: @escaping (inout Result, Base.Element) -> Void
base: Base,
initial: Result,
transform: @escaping (inout Result, Base.Element) -> Void
) { ) {
self.base = base self.base = base
self.initial = initial self.initial = initial
@@ -200,19 +184,14 @@ public struct ExclusiveReductions<Result, Base: Sequence> {
extension ExclusiveReductions: Sequence { extension ExclusiveReductions: Sequence {
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline internal var iterator: Base.Iterator
internal var iterator: Base.Iterator
@usableFromInline @usableFromInline internal var current: Result?
internal var current: Result?
@usableFromInline @usableFromInline internal let transform: (inout Result, Base.Element) -> Void
internal let transform: (inout Result, Base.Element) -> Void
@inlinable @inlinable internal init(
internal init( iterator: Base.Iterator, current: Result? = nil,
iterator: Base.Iterator,
current: Result? = nil,
transform: @escaping (inout Result, Base.Element) -> Void transform: @escaping (inout Result, Base.Element) -> Void
) { ) {
self.iterator = iterator self.iterator = iterator
@@ -220,11 +199,9 @@ extension ExclusiveReductions: Sequence {
self.transform = transform self.transform = transform
} }
@inlinable @inlinable public mutating func next() -> Result? {
public mutating func next() -> Result? {
guard let result = current else { return nil } guard let result = current else { return nil }
current = iterator.next().map { element in current = iterator.next().map { element in var result = result
var result = result
transform(&result, element) transform(&result, element)
return result return result
} }
@@ -232,40 +209,29 @@ extension ExclusiveReductions: Sequence {
} }
} }
@inlinable @inlinable public func makeIterator() -> Iterator {
public func makeIterator() -> Iterator { Iterator(iterator: base.makeIterator(), current: initial, transform: transform)
Iterator(iterator: base.makeIterator(),
current: initial,
transform: transform)
} }
} }
extension ExclusiveReductions: Collection where Base: Collection { extension ExclusiveReductions: Collection where Base: Collection {
public struct Index: Comparable { public struct Index: Comparable {
@usableFromInline @usableFromInline internal let representation: ReductionsIndexRepresentation<Base.Index, Result>
internal let representation: ReductionsIndexRepresentation<Base.Index, Result>
@inlinable @inlinable internal init(_ representation: ReductionsIndexRepresentation<Base.Index, Result>) {
internal init(
_ representation: ReductionsIndexRepresentation<Base.Index, Result>
) {
self.representation = representation self.representation = representation
} }
@inlinable @inlinable public static func < (lhs: Self, rhs: Self) -> Bool {
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.representation < rhs.representation lhs.representation < rhs.representation
} }
} }
@inlinable @inlinable public var startIndex: Index { Index(.start) }
public var startIndex: Index { Index(.start) }
@inlinable @inlinable public var endIndex: Index { Index(.end) }
public var endIndex: Index { Index(.end) }
@inlinable @inlinable public subscript(position: Index) -> Result {
public subscript(position: Index) -> Result {
switch position.representation { switch position.representation {
case .start: return initial case .start: return initial
case .base(_, let result): return result case .base(_, let result): return result
@@ -273,8 +239,7 @@ extension ExclusiveReductions: Collection where Base: Collection {
} }
} }
@inlinable @inlinable public func index(after i: Index) -> Index {
public func index(after i: Index) -> Index {
func index(base index: Base.Index, previous: Result) -> Index { func index(base index: Base.Index, previous: Result) -> Index {
guard index != base.endIndex else { return endIndex } guard index != base.endIndex else { return endIndex }
var previous = previous var previous = previous
@@ -282,45 +247,30 @@ extension ExclusiveReductions: Collection where Base: Collection {
return Index(.base(index: index, result: previous)) return Index(.base(index: index, result: previous))
} }
switch i.representation { switch i.representation {
case .start: case .start: return index(base: base.startIndex, previous: initial)
return index(base: base.startIndex, previous: initial) case let .base(i, result): return index(base: base.index(after: i), previous: result)
case let .base(i, result): case .end: fatalError("Cannot get index after end index.")
return index(base: base.index(after: i), previous: result)
case .end:
fatalError("Cannot get index after end index.")
} }
} }
@inlinable @inlinable public func distance(from start: Index, to end: Index) -> Int {
public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) { switch (start.representation, end.representation) {
case (.start, .start): case (.start, .start): return 0
return 0 case let (.start, .base(index, _)): return base.distance(from: base.startIndex, to: index) + 1
case let (.start, .base(index, _)): case (.start, .end): return base.distance(from: base.startIndex, to: base.endIndex) + 1
return base.distance(from: base.startIndex, to: index) + 1 case let (.base(index, _), .start): return base.distance(from: index, to: base.startIndex) - 1
case (.start, .end): case let (.base(start, _), .base(end, _)): return base.distance(from: start, to: end)
return base.distance(from: base.startIndex, to: base.endIndex) + 1 case let (.base(index, _), .end): return base.distance(from: index, to: base.endIndex)
case let (.base(index, _), .start): case (.end, .start): return base.distance(from: base.endIndex, to: base.startIndex) - 1
return base.distance(from: index, to: base.startIndex) - 1 case let (.end, .base(index, _)): return base.distance(from: base.endIndex, to: index)
case let (.base(start, _), .base(end, _)): case (.end, .end): return 0
return base.distance(from: start, to: end)
case let (.base(index, _), .end):
return base.distance(from: index, to: base.endIndex)
case (.end, .start):
return base.distance(from: base.endIndex, to: base.startIndex) - 1
case let (.end, .base(index, _)):
return base.distance(from: base.endIndex, to: index)
case (.end, .end):
return 0
} }
} }
} }
extension ExclusiveReductions: LazySequenceProtocol extension ExclusiveReductions: LazySequenceProtocol where Base: LazySequenceProtocol {}
where Base: LazySequenceProtocol {}
extension ExclusiveReductions: LazyCollectionProtocol extension ExclusiveReductions: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
where Base: LazyCollectionProtocol {}
// MARK: - Inclusive Reductions // MARK: - Inclusive Reductions
@@ -345,12 +295,9 @@ extension LazySequenceProtocol {
/// - Returns: A sequence of the reduced elements. /// - Returns: A sequence of the reduced elements.
/// ///
/// - Complexity: O(1) /// - Complexity: O(1)
@inlinable @inlinable public func reductions(_ transform: @escaping (Element, Element) -> Element)
public func reductions( -> InclusiveReductions<Self>
_ transform: @escaping (Element, Element) -> Element { InclusiveReductions(base: self, transform: transform) }
) -> InclusiveReductions<Self> {
InclusiveReductions(base: self, transform: transform)
}
} }
extension Sequence { extension Sequence {
@@ -390,10 +337,9 @@ extension Sequence {
/// - Returns: An array of the reduced elements. /// - Returns: An array of the reduced elements.
/// ///
/// - Complexity: O(_n_), where _n_ is the length of the sequence. /// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable @inlinable public func reductions(_ transform: (Element, Element) throws -> Element) rethrows
public func reductions( -> [Element]
_ transform: (Element, Element) throws -> Element {
) rethrows -> [Element] {
var iterator = makeIterator() var iterator = makeIterator()
guard let initial = iterator.next() else { return [] } guard let initial = iterator.next() else { return [] }
return try IteratorSequence(iterator).reductions(initial, transform) return try IteratorSequence(iterator).reductions(initial, transform)
@@ -401,16 +347,12 @@ extension Sequence {
} }
public struct InclusiveReductions<Base: Sequence> { public struct InclusiveReductions<Base: Sequence> {
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline @usableFromInline internal let transform: (Base.Element, Base.Element) -> Base.Element
internal let transform: (Base.Element, Base.Element) -> Base.Element
@inlinable @inlinable internal init(
internal init( base: Base, transform: @escaping (Base.Element, Base.Element) -> Base.Element
base: Base,
transform: @escaping (Base.Element, Base.Element) -> Base.Element
) { ) {
self.base = base self.base = base
self.transform = transform self.transform = transform
@@ -419,19 +361,14 @@ public struct InclusiveReductions<Base: Sequence> {
extension InclusiveReductions: Sequence { extension InclusiveReductions: Sequence {
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline internal var iterator: Base.Iterator
internal var iterator: Base.Iterator
@usableFromInline @usableFromInline internal var element: Base.Element?
internal var element: Base.Element?
@usableFromInline @usableFromInline internal let transform: (Base.Element, Base.Element) -> Base.Element
internal let transform: (Base.Element, Base.Element) -> Base.Element
@inlinable @inlinable internal init(
internal init( iterator: Base.Iterator, element: Base.Element? = nil,
iterator: Base.Iterator,
element: Base.Element? = nil,
transform: @escaping (Base.Element, Base.Element) -> Base.Element transform: @escaping (Base.Element, Base.Element) -> Base.Element
) { ) {
self.iterator = iterator self.iterator = iterator
@@ -439,8 +376,7 @@ extension InclusiveReductions: Sequence {
self.transform = transform self.transform = transform
} }
@inlinable @inlinable public mutating func next() -> Base.Element? {
public mutating func next() -> Base.Element? {
guard let previous = element else { guard let previous = element else {
element = iterator.next() element = iterator.next()
return element return element
@@ -451,42 +387,33 @@ extension InclusiveReductions: Sequence {
} }
} }
@inlinable @inlinable public func makeIterator() -> Iterator {
public func makeIterator() -> Iterator { Iterator(iterator: base.makeIterator(), transform: transform)
Iterator(iterator: base.makeIterator(),
transform: transform)
} }
} }
extension InclusiveReductions: Collection where Base: Collection { extension InclusiveReductions: Collection where Base: Collection {
public struct Index: Comparable { public struct Index: Comparable {
@usableFromInline @usableFromInline internal let representation:
internal let representation: ReductionsIndexRepresentation<Base.Index, Base.Element> ReductionsIndexRepresentation<Base.Index, Base.Element>
@inlinable @inlinable internal init(
internal init(
_ representation: ReductionsIndexRepresentation<Base.Index, Base.Element> _ representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
) { ) { self.representation = representation }
self.representation = representation
}
@inlinable @inlinable public static func < (lhs: Self, rhs: Self) -> Bool {
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.representation < rhs.representation lhs.representation < rhs.representation
} }
} }
@inlinable @inlinable public var startIndex: Index {
public var startIndex: Index {
guard base.startIndex != base.endIndex else { return endIndex } guard base.startIndex != base.endIndex else { return endIndex }
return Index(.start) return Index(.start)
} }
@inlinable @inlinable public var endIndex: Index { Index(.end) }
public var endIndex: Index { Index(.end) }
@inlinable @inlinable public subscript(position: Index) -> Base.Element {
public subscript(position: Index) -> Base.Element {
switch position.representation { switch position.representation {
case .start: return base[base.startIndex] case .start: return base[base.startIndex]
case .base(_, let result): return result case .base(_, let result): return result
@@ -494,66 +421,48 @@ extension InclusiveReductions: Collection where Base: Collection {
} }
} }
@inlinable @inlinable public func index(after i: Index) -> Index {
public func index(after i: Index) -> Index {
func index(after i: Base.Index, previous: Base.Element) -> Index { func index(after i: Base.Index, previous: Base.Element) -> Index {
let index = base.index(after: i) let index = base.index(after: i)
guard index != base.endIndex else { return endIndex } guard index != base.endIndex else { return endIndex }
return Index(.base(index: index, result: transform(previous, base[index]))) return Index(.base(index: index, result: transform(previous, base[index])))
} }
switch i.representation { switch i.representation {
case .start: case .start: return index(after: base.startIndex, previous: base[base.startIndex])
return index(after: base.startIndex, previous: base[base.startIndex]) case let .base(i, element): return index(after: i, previous: element)
case let .base(i, element): case .end: fatalError("Cannot get index after end index.")
return index(after: i, previous: element)
case .end:
fatalError("Cannot get index after end index.")
} }
} }
@inlinable @inlinable public func distance(from start: Index, to end: Index) -> Int {
public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) { switch (start.representation, end.representation) {
case (.start, .start): case (.start, .start): return 0
return 0 case let (.start, .base(index, _)): return base.distance(from: base.startIndex, to: index)
case let (.start, .base(index, _)): case (.start, .end): return base.distance(from: base.startIndex, to: base.endIndex)
return base.distance(from: base.startIndex, to: index) case let (.base(index, _), .start): return base.distance(from: index, to: base.startIndex)
case (.start, .end): case let (.base(start, _), .base(end, _)): return base.distance(from: start, to: end)
return base.distance(from: base.startIndex, to: base.endIndex) case let (.base(index, _), .end): return base.distance(from: index, to: base.endIndex)
case let (.base(index, _), .start): case (.end, .start): return base.distance(from: base.endIndex, to: base.startIndex)
return base.distance(from: index, to: base.startIndex) case let (.end, .base(index, _)): return base.distance(from: base.endIndex, to: index)
case let (.base(start, _), .base(end, _)): case (.end, .end): return 0
return base.distance(from: start, to: end)
case let (.base(index, _), .end):
return base.distance(from: index, to: base.endIndex)
case (.end, .start):
return base.distance(from: base.endIndex, to: base.startIndex)
case let (.end, .base(index, _)):
return base.distance(from: base.endIndex, to: index)
case (.end, .end):
return 0
} }
} }
} }
extension InclusiveReductions: LazySequenceProtocol extension InclusiveReductions: LazySequenceProtocol where Base: LazySequenceProtocol {}
where Base: LazySequenceProtocol {}
extension InclusiveReductions: LazyCollectionProtocol extension InclusiveReductions: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
where Base: LazyCollectionProtocol {}
// MARK: - ReductionsIndexRepresentation // MARK: - ReductionsIndexRepresentation
@usableFromInline @usableFromInline enum ReductionsIndexRepresentation<BaseIndex: Comparable, Result> {
enum ReductionsIndexRepresentation<BaseIndex: Comparable, Result> {
case start case start
case base(index: BaseIndex, result: Result) case base(index: BaseIndex, result: Result)
case end case end
} }
extension ReductionsIndexRepresentation: Equatable { extension ReductionsIndexRepresentation: Equatable {
@inlinable @inlinable static func == (lhs: Self, rhs: Self) -> Bool {
static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) { switch (lhs, rhs) {
case (.start, .start): return true case (.start, .start): return true
case (.end, .end): return true case (.end, .end): return true
@@ -564,8 +473,7 @@ extension ReductionsIndexRepresentation: Equatable {
} }
extension ReductionsIndexRepresentation: Comparable { extension ReductionsIndexRepresentation: Comparable {
@inlinable @inlinable static func < (lhs: Self, rhs: Self) -> Bool {
static func < (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) { switch (lhs, rhs) {
case (_, .start): return false case (_, .start): return false
case (.start, _): return true case (.start, _): return true
@@ -580,64 +488,40 @@ extension ReductionsIndexRepresentation: Comparable {
extension LazySequenceProtocol { extension LazySequenceProtocol {
@available(*, deprecated, message: "Use reductions(_:_:) instead.") @available(*, deprecated, message: "Use reductions(_:_:) instead.") @inlinable
@inlinable public func scan<Result>(_ initial: Result, _ transform: @escaping (Result, Element) -> Result)
public func scan<Result>( -> ExclusiveReductions<Result, Self>
_ initial: Result, { reductions(initial, transform) }
_ transform: @escaping (Result, Element) -> Result
) -> ExclusiveReductions<Result, Self> {
reductions(initial, transform)
}
@available(*, deprecated, message: "Use reductions(into:_:) instead.") @available(*, deprecated, message: "Use reductions(into:_:) instead.") @inlinable
@inlinable
public func scan<Result>( public func scan<Result>(
into initial: Result, into initial: Result, _ transform: @escaping (inout Result, Element) -> Void
_ transform: @escaping (inout Result, Element) -> Void ) -> ExclusiveReductions<Result, Self> { reductions(into: initial, transform) }
) -> ExclusiveReductions<Result, Self> {
reductions(into: initial, transform)
}
} }
extension Sequence { extension Sequence {
@available(*, deprecated, message: "Use reductions(_:_:) instead.") @available(*, deprecated, message: "Use reductions(_:_:) instead.") @inlinable
@inlinable public func scan<Result>(_ initial: Result, _ transform: (Result, Element) throws -> Result)
public func scan<Result>( rethrows -> [Result]
_ initial: Result, { try reductions(initial, transform) }
_ transform: (Result, Element) throws -> Result
) rethrows -> [Result] {
try reductions(initial, transform)
}
@available(*, deprecated, message: "Use reductions(into:_:) instead.") @available(*, deprecated, message: "Use reductions(into:_:) instead.") @inlinable
@inlinable
public func scan<Result>( public func scan<Result>(
into initial: Result, into initial: Result, _ transform: (inout Result, Element) throws -> Void
_ transform: (inout Result, Element) throws -> Void ) rethrows -> [Result] { try reductions(into: initial, transform) }
) rethrows -> [Result] {
try reductions(into: initial, transform)
}
} }
extension LazySequenceProtocol { extension LazySequenceProtocol {
@available(*, deprecated, message: "Use reductions(_:) instead.") @available(*, deprecated, message: "Use reductions(_:) instead.") @inlinable public func scan(
@inlinable
public func scan(
_ transform: @escaping (Element, Element) -> Element _ transform: @escaping (Element, Element) -> Element
) -> InclusiveReductions<Self> { ) -> InclusiveReductions<Self> { reductions(transform) }
reductions(transform)
}
} }
extension Sequence { extension Sequence {
@available(*, deprecated, message: "Use reductions(_:) instead.") @available(*, deprecated, message: "Use reductions(_:) instead.") @inlinable public func scan(
@inlinable
public func scan(
_ transform: (Element, Element) throws -> Element _ transform: (Element, Element) throws -> Element
) rethrows -> [Element] { ) rethrows -> [Element] { try reductions(transform) }
try reductions(transform)
}
} }
+27 -48
View File
@@ -29,9 +29,7 @@ extension MutableCollection where Self: BidirectionalCollection {
/// ///
/// - Postcondition: For returned indices `(lower, upper)`: /// - Postcondition: For returned indices `(lower, upper)`:
/// `lower == limit || upper == limit` /// `lower == limit || upper == limit`
@inlinable @inlinable @discardableResult internal mutating func _reverse(
@discardableResult
internal mutating func _reverse(
subrange: Range<Index>, until limit: Index subrange: Range<Index>, until limit: Index
) -> (Index, Index) { ) -> (Index, Index) {
var lower = subrange.lowerBound var lower = subrange.lowerBound
@@ -43,7 +41,7 @@ extension MutableCollection where Self: BidirectionalCollection {
} }
return (lower, upper) return (lower, upper)
} }
/// Reverses the elements within the given subrange. /// Reverses the elements within the given subrange.
/// ///
/// This example reverses the numbers within the subrange at the start of the /// This example reverses the numbers within the subrange at the start of the
@@ -56,8 +54,7 @@ extension MutableCollection where Self: BidirectionalCollection {
/// - Parameter subrange: The subrange of this collection to reverse. /// - Parameter subrange: The subrange of this collection to reverse.
/// ///
/// - Complexity: O(*n*), where *n* is the length of `subrange`. /// - Complexity: O(*n*), where *n* is the length of `subrange`.
@inlinable @inlinable public mutating func reverse(subrange: Range<Index>) {
public mutating func reverse(subrange: Range<Index>) {
if subrange.isEmpty { return } if subrange.isEmpty { return }
var lower = subrange.lowerBound var lower = subrange.lowerBound
var upper = subrange.upperBound var upper = subrange.upperBound
@@ -94,21 +91,19 @@ extension MutableCollection {
/// - distance(from: lhs.lowerBound, to: p) == distance(from: /// - distance(from: lhs.lowerBound, to: p) == distance(from:
/// rhs.lowerBound, to: q) /// rhs.lowerBound, to: q)
/// - p == lhs.upperBound || q == rhs.upperBound /// - p == lhs.upperBound || q == rhs.upperBound
@inlinable @inlinable internal mutating func _swapNonemptySubrangePrefixes(
internal mutating func _swapNonemptySubrangePrefixes(
_ lhs: Range<Index>, _ rhs: Range<Index> _ lhs: Range<Index>, _ rhs: Range<Index>
) -> (Index, Index) { ) -> (Index, Index) {
assert(!lhs.isEmpty) assert(!lhs.isEmpty)
assert(!rhs.isEmpty) assert(!rhs.isEmpty)
var p = lhs.lowerBound var p = lhs.lowerBound
var q = rhs.lowerBound var q = rhs.lowerBound
repeat { repeat {
swapAt(p, q) swapAt(p, q)
formIndex(after: &p) formIndex(after: &p)
formIndex(after: &q) formIndex(after: &q)
} } while p != lhs.upperBound && q != rhs.upperBound
while p != lhs.upperBound && q != rhs.upperBound
return (p, q) return (p, q)
} }
@@ -133,19 +128,17 @@ extension MutableCollection {
/// `subrange` pre-rotation. /// `subrange` pre-rotation.
/// ///
/// - Complexity: O(*n*), where *n* is the length of `subrange`. /// - Complexity: O(*n*), where *n* is the length of `subrange`.
@inlinable @inlinable @discardableResult public mutating func rotate(
@discardableResult subrange: Range<Index>, toStartAt newStart: Index
public mutating func rotate(
subrange: Range<Index>,
toStartAt newStart: Index
) -> Index { ) -> Index {
var m = newStart, s = subrange.lowerBound var m = newStart
var s = subrange.lowerBound
let e = subrange.upperBound let e = subrange.upperBound
// Handle the trivial cases // Handle the trivial cases
if s == m { return e } if s == m { return e }
if m == e { return s } if m == e { return s }
// We have two regions of possibly-unequal length that need to be // We have two regions of possibly-unequal length that need to be
// exchanged. The return value of this method is going to be the // exchanged. The return value of this method is going to be the
// position following that of the element that is currently last // position following that of the element that is currently last
@@ -155,7 +148,7 @@ extension MutableCollection {
// ^ ^ ^ ^ ^ ^ // ^ ^ ^ ^ ^ ^
// s m e s m e // s m e s m e
// //
var ret = e // start with a known incorrect result. var ret = e // start with a known incorrect result.
while true { while true {
// Exchange the leading elements of each region (up to the // Exchange the leading elements of each region (up to the
// length of the shorter region). // length of the shorter region).
@@ -167,7 +160,7 @@ extension MutableCollection {
// s s1 m m1/e s s1/m m1 e // s s1 m m1/e s s1/m m1 e
// //
let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e) let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e)
if m1 == e { if m1 == e {
// Left-hand case: we have moved element j into position. if // Left-hand case: we have moved element j into position. if
// we haven't already, we can capture the return value which // we haven't already, we can capture the return value which
@@ -177,11 +170,11 @@ extension MutableCollection {
// comparison once the return value is known. I'm not sure // comparison once the return value is known. I'm not sure
// it's a worthwhile optimization, though. // it's a worthwhile optimization, though.
if ret == e { ret = s1 } if ret == e { ret = s1 }
// If both regions were the same size, we're done. // If both regions were the same size, we're done.
if s1 == m { break } if s1 == m { break }
} }
// Now we have a smaller problem that is also a rotation, so we // Now we have a smaller problem that is also a rotation, so we
// can adjust our bounds and repeat. // can adjust our bounds and repeat.
// //
@@ -191,10 +184,10 @@ extension MutableCollection {
s = s1 s = s1
if s == m { m = m1 } if s == m { m = m1 }
} }
return ret return ret
} }
/// Rotates the elements of this collection so that the element /// Rotates the elements of this collection so that the element
/// at the specified index becomes the start of the collection. /// at the specified index becomes the start of the collection.
/// ///
@@ -213,9 +206,7 @@ extension MutableCollection {
/// - Returns: The new index of the element that was first pre-rotation. /// - Returns: The new index of the element that was first pre-rotation.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable @discardableResult public mutating func rotate(toStartAt newStart: Index) -> Index {
@discardableResult
public mutating func rotate(toStartAt newStart: Index) -> Index {
rotate(subrange: startIndex..<endIndex, toStartAt: newStart) rotate(subrange: startIndex..<endIndex, toStartAt: newStart)
} }
} }
@@ -242,11 +233,8 @@ extension MutableCollection where Self: BidirectionalCollection {
/// `subrange` pre-rotation. /// `subrange` pre-rotation.
/// ///
/// - Complexity: O(*n*), where *n* is the length of `subrange`. /// - Complexity: O(*n*), where *n* is the length of `subrange`.
@inlinable @inlinable @discardableResult public mutating func rotate(
@discardableResult subrange: Range<Index>, toStartAt newStart: Index
public mutating func rotate(
subrange: Range<Index>,
toStartAt newStart: Index
) -> Index { ) -> Index {
reverse(subrange: subrange.lowerBound..<newStart) reverse(subrange: subrange.lowerBound..<newStart)
reverse(subrange: newStart..<subrange.upperBound) reverse(subrange: newStart..<subrange.upperBound)
@@ -273,9 +261,7 @@ extension MutableCollection where Self: BidirectionalCollection {
/// - Returns: The new index of the element that was first pre-rotation. /// - Returns: The new index of the element that was first pre-rotation.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable @discardableResult public mutating func rotate(toStartAt newStart: Index) -> Index {
@discardableResult
public mutating func rotate(toStartAt newStart: Index) -> Index {
rotate(subrange: startIndex..<endIndex, toStartAt: newStart) rotate(subrange: startIndex..<endIndex, toStartAt: newStart)
} }
} }
@@ -283,18 +269,11 @@ extension MutableCollection where Self: BidirectionalCollection {
// Deprecations // Deprecations
extension MutableCollection { extension MutableCollection {
@available(*, deprecated, renamed: "rotate(subrange:toStartAt:)") @available(*, deprecated, renamed: "rotate(subrange:toStartAt:)") @discardableResult
@discardableResult public mutating func rotate(subrange: Range<Index>, at newStart: Index) -> Index {
public mutating func rotate(
subrange: Range<Index>,
at newStart: Index) -> Index
{
rotate(subrange: subrange, toStartAt: newStart) rotate(subrange: subrange, toStartAt: newStart)
} }
@available(*, deprecated, renamed: "rotate(toStartAt:)") @available(*, deprecated, renamed: "rotate(toStartAt:)") @discardableResult
@discardableResult public mutating func rotate(at newStart: Index) -> Index { rotate(toStartAt: newStart) }
public mutating func rotate(at newStart: Index) -> Index {
rotate(toStartAt: newStart)
}
} }
+68 -140
View File
@@ -26,8 +26,7 @@ extension Sequence {
/// - Parameter step: The amount to step with each iteration. /// - Parameter step: The amount to step with each iteration.
/// - Returns: Returns a sequence for stepping through the /// - Returns: Returns a sequence for stepping through the
/// elements by the specified amount. /// elements by the specified amount.
@inlinable @inlinable public func striding(by step: Int) -> StrideSequence<Self> {
public func striding(by step: Int) -> StrideSequence<Self> {
StrideSequence(base: self, stride: step) StrideSequence(base: self, stride: step)
} }
} }
@@ -46,23 +45,19 @@ extension Collection {
/// - Parameter step: The amount to step with each iteration. /// - Parameter step: The amount to step with each iteration.
/// - Returns: Returns a collection for stepping through the /// - Returns: Returns a collection for stepping through the
/// elements by the specified amount. /// elements by the specified amount.
@inlinable @inlinable public func striding(by step: Int) -> StrideCollection<Self> {
public func striding(by step: Int) -> StrideCollection<Self> {
StrideCollection(base: self, stride: step) StrideCollection(base: self, stride: step)
} }
} }
/// A wrapper that strides over a base sequence. /// A wrapper that strides over a base sequence.
public struct StrideSequence<Base: Sequence>: Sequence { public struct StrideSequence<Base: Sequence>: Sequence {
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline internal let stride: Int
@usableFromInline
internal let stride: Int @inlinable internal init(base: Base, stride: Int) {
@inlinable
internal init(base: Base, stride: Int) {
precondition(stride > 0, "striding must be greater than zero") precondition(stride > 0, "striding must be greater than zero")
self.base = base self.base = base
self.stride = stride self.stride = stride
@@ -70,60 +65,46 @@ public struct StrideSequence<Base: Sequence>: Sequence {
} }
extension StrideSequence { extension StrideSequence {
/// An iterator over a `Stride` sequence. /// An iterator over a `Stride` sequence.
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline internal var iterator: Base.Iterator
internal var iterator: Base.Iterator
@usableFromInline internal let stride: Int
@usableFromInline
internal let stride: Int @usableFromInline internal var striding: Bool = false
@usableFromInline @inlinable internal init(iterator: Base.Iterator, stride: Int) {
internal var striding: Bool = false
@inlinable
internal init(iterator: Base.Iterator, stride: Int) {
self.iterator = iterator self.iterator = iterator
self.stride = stride self.stride = stride
} }
@inlinable @inlinable public mutating func next() -> Base.Element? {
public mutating func next() -> Base.Element? {
guard striding else { guard striding else {
striding = true striding = true
return iterator.next() return iterator.next()
} }
for _ in 0..<stride - 1 { for _ in 0..<stride - 1 { guard iterator.next() != nil else { break } }
guard iterator.next() != nil else { break }
}
return iterator.next() return iterator.next()
} }
} }
@inlinable @inlinable public func makeIterator() -> Iterator {
public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(), stride: stride) Iterator(iterator: base.makeIterator(), stride: stride)
} }
} }
extension StrideSequence { extension StrideSequence {
@inlinable @inlinable public func striding(by step: Int) -> Self { Self(base: base, stride: stride * step) }
public func striding(by step: Int) -> Self {
Self(base: base, stride: stride * step)
}
} }
/// A wrapper that strides over a base collection. /// A wrapper that strides over a base collection.
public struct StrideCollection<Base: Collection> { public struct StrideCollection<Base: Collection> {
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline internal let stride: Int
@usableFromInline
internal let stride: Int @inlinable internal init(base: Base, stride: Int) {
@inlinable
internal init(base: Base, stride: Int) {
precondition(stride > 0, "striding must be greater than zero") precondition(stride > 0, "striding must be greater than zero")
self.base = base self.base = base
self.stride = stride self.stride = stride
@@ -131,124 +112,73 @@ public struct StrideCollection<Base: Collection> {
} }
extension StrideCollection { extension StrideCollection {
@inlinable @inlinable public func striding(by step: Int) -> Self { Self(base: base, stride: stride * step) }
public func striding(by step: Int) -> Self {
Self(base: base, stride: stride * step)
}
} }
extension StrideCollection: Collection { extension StrideCollection: Collection {
/// A position in a `Stride` collection. /// A position in a `Stride` collection.
public struct Index: Comparable { public struct Index: Comparable {
@usableFromInline @usableFromInline internal let base: Base.Index
internal let base: Base.Index
@usableFromInline internal init(_ base: Base.Index) { self.base = base }
@usableFromInline
internal init(_ base: Base.Index) { @inlinable public static func < (lhs: Index, rhs: Index) -> Bool { lhs.base < rhs.base }
self.base = base
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.base < rhs.base
}
} }
@inlinable @inlinable public var startIndex: Index { Index(base.startIndex) }
public var startIndex: Index {
Index(base.startIndex) @inlinable public var endIndex: Index { Index(base.endIndex) }
}
@inlinable public subscript(i: Index) -> Base.Element { base[i.base] }
@inlinable
public var endIndex: Index { @inlinable public func index(after i: Index) -> Index {
Index(base.endIndex)
}
@inlinable
public subscript(i: Index) -> Base.Element {
base[i.base]
}
@inlinable
public func index(after i: Index) -> Index {
precondition(i.base < base.endIndex, "Advancing past end index") precondition(i.base < base.endIndex, "Advancing past end index")
return index(i, offsetBy: 1) return index(i, offsetBy: 1)
} }
@inlinable @inlinable public func index(_ i: Index, offsetBy n: Int, limitedBy limit: Index) -> Index? {
public func index(
_ i: Index,
offsetBy n: Int,
limitedBy limit: Index
) -> Index? {
guard n != 0 else { return i } guard n != 0 else { return i }
guard limit != i else { return nil } guard limit != i else { return nil }
return n > 0 return n > 0
? offsetForward(i, offsetBy: n, limitedBy: limit) ? offsetForward(i, offsetBy: n, limitedBy: limit)
: offsetBackward(i, offsetBy: -n, limitedBy: limit) : offsetBackward(i, offsetBy: -n, limitedBy: limit)
} }
@inlinable @inlinable internal func offsetForward(_ i: Index, offsetBy n: Int, limitedBy limit: Index)
internal func offsetForward( -> Index?
_ i: Index, {
offsetBy n: Int,
limitedBy limit: Index
) -> Index? {
if limit < i { if limit < i {
if let idx = base.index( if let idx = base.index(i.base, offsetBy: n * stride, limitedBy: base.endIndex) {
i.base,
offsetBy: n * stride,
limitedBy: base.endIndex
) {
return Index(idx) return Index(idx)
} else { } else {
assert(distance(from: i, to: endIndex) == n, "Advancing past end index") assert(distance(from: i, to: endIndex) == n, "Advancing past end index")
return endIndex return endIndex
} }
} else if let idx = base.index( } else if let idx = base.index(i.base, offsetBy: n * stride, limitedBy: limit.base) {
i.base,
offsetBy: n * stride,
limitedBy: limit.base
) {
return Index(idx) return Index(idx)
} else { } else {
return distance(from: i, to: limit) == n return distance(from: i, to: limit) == n ? endIndex : nil
? endIndex
: nil
} }
} }
@inlinable @inlinable internal func offsetBackward(_ i: Index, offsetBy n: Int, limitedBy limit: Index)
internal func offsetBackward( -> Index?
_ i: Index, {
offsetBy n: Int, let distance =
limitedBy limit: Index i == endIndex ? -((base.count - 1) % stride + 1) + (n - 1) * -stride : n * -stride
) -> Index? { return base.index(i.base, offsetBy: distance, limitedBy: limit.base).map(Index.init)
let distance = i == endIndex
? -((base.count - 1) % stride + 1) + (n - 1) * -stride
: n * -stride
return base.index(
i.base,
offsetBy: distance,
limitedBy: limit.base
).map(Index.init)
} }
@inlinable @inlinable public var count: Int { base.isEmpty ? 0 : (base.count - 1) / stride + 1 }
public var count: Int {
base.isEmpty ? 0 : (base.count - 1) / stride + 1 @inlinable public func distance(from start: Index, to end: Index) -> Int {
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
let distance = base.distance(from: start.base, to: end.base) let distance = base.distance(from: start.base, to: end.base)
return distance / stride + (distance % stride).signum() return distance / stride + (distance % stride).signum()
} }
@inlinable @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
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.endIndex, "Advancing past end index")
precondition(distance >= 0 || i.base > base.startIndex, "Incrementing past start index") precondition(distance >= 0 || i.base > base.startIndex, "Incrementing past start index")
let limit = distance > 0 ? endIndex : startIndex let limit = distance > 0 ? endIndex : startIndex
@@ -258,11 +188,9 @@ extension StrideCollection: Collection {
} }
} }
extension StrideCollection: BidirectionalCollection extension StrideCollection: BidirectionalCollection where Base: RandomAccessCollection {
where Base: RandomAccessCollection {
@inlinable public func index(before i: Index) -> Index {
@inlinable
public func index(before i: Index) -> Index {
precondition(i.base > base.startIndex, "Incrementing past start index") precondition(i.base > base.startIndex, "Incrementing past start index")
return index(i, offsetBy: -1) return index(i, offsetBy: -1)
} }
+8 -18
View File
@@ -23,10 +23,7 @@ extension BidirectionalCollection {
/// returns `false` it will not be called again. /// returns `false` it will not be called again.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable public func suffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence {
public func suffix(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
try self[startOfSuffix(while: predicate)...] try self[startOfSuffix(while: predicate)...]
} }
} }
@@ -45,14 +42,10 @@ extension Collection {
/// be called again. /// be called again.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable internal func endOfPrefix(while predicate: (Element) throws -> Bool) rethrows -> Index
internal func endOfPrefix( {
while predicate: (Element) throws -> Bool
) rethrows -> Index {
var index = startIndex var index = startIndex
while try index != endIndex && predicate(self[index]) { while try index != endIndex && predicate(self[index]) { formIndex(after: &index) }
formIndex(after: &index)
}
return index return index
} }
} }
@@ -71,17 +64,14 @@ extension BidirectionalCollection {
/// be called again. /// be called again.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable internal func startOfSuffix(while predicate: (Element) throws -> Bool) rethrows
internal func startOfSuffix( -> Index
while predicate: (Element) throws -> Bool {
) rethrows -> Index {
var index = endIndex var index = endIndex
while index != startIndex { while index != startIndex {
let after = index let after = index
formIndex(before: &index) formIndex(before: &index)
if try !predicate(self[index]) { if try !predicate(self[index]) { return after }
return after
}
} }
return index return index
} }
+2 -4
View File
@@ -25,10 +25,8 @@ extension BidirectionalCollection {
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
/// ///
@inlinable @inlinable public func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
public func trimming( {
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
let start = try endOfPrefix(while: predicate) let start = try endOfPrefix(while: predicate)
let end = try self[start...].startOfSuffix(while: predicate) let end = try self[start...].startOfSuffix(while: predicate)
return self[start..<end] return self[start..<end]
+26 -45
View File
@@ -12,15 +12,12 @@
/// A sequence wrapper that leaves out duplicate elements of a base sequence. /// A sequence wrapper that leaves out duplicate elements of a base sequence.
public struct Uniqued<Base: Sequence, Subject: Hashable> { public struct Uniqued<Base: Sequence, Subject: Hashable> {
/// The base collection. /// The base collection.
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
/// The projection function. /// The projection function.
@usableFromInline @usableFromInline internal let projection: (Base.Element) -> Subject
internal let projection: (Base.Element) -> Subject
@usableFromInline internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {
@usableFromInline
internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {
self.base = base self.base = base
self.projection = projection self.projection = projection
} }
@@ -29,37 +26,28 @@ public struct Uniqued<Base: Sequence, Subject: Hashable> {
extension Uniqued: Sequence { extension Uniqued: Sequence {
/// The iterator for a `Uniqued` sequence. /// The iterator for a `Uniqued` sequence.
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline internal var base: Base.Iterator
internal var base: Base.Iterator
@usableFromInline internal let projection: (Base.Element) -> Subject
@usableFromInline
internal let projection: (Base.Element) -> Subject @usableFromInline internal var seen: Set<Subject> = []
@usableFromInline @usableFromInline internal init(
internal var seen: Set<Subject> = [] base: Base.Iterator, projection: @escaping (Base.Element) -> Subject
@usableFromInline
internal init(
base: Base.Iterator,
projection: @escaping (Base.Element) -> Subject
) { ) {
self.base = base self.base = base
self.projection = projection self.projection = projection
} }
@inlinable @inlinable public mutating func next() -> Base.Element? {
public mutating func next() -> Base.Element? {
while let element = base.next() { while let element = base.next() {
if seen.insert(projection(element)).inserted { if seen.insert(projection(element)).inserted { return element }
return element
}
} }
return nil return nil
} }
} }
@inlinable @inlinable public func makeIterator() -> Iterator {
public func makeIterator() -> Iterator {
Iterator(base: base.makeIterator(), projection: projection) Iterator(base: base.makeIterator(), projection: projection)
} }
} }
@@ -82,8 +70,7 @@ extension Sequence where Element: Hashable {
/// - Returns: A sequence with only the unique elements of this sequence. /// - Returns: A sequence with only the unique elements of this sequence.
/// . /// .
/// - Complexity: O(1). /// - Complexity: O(1).
@inlinable @inlinable public func uniqued() -> Uniqued<Self, Element> {
public func uniqued() -> Uniqued<Self, Element> {
Uniqued(base: self, projection: { $0 }) Uniqued(base: self, projection: { $0 })
} }
} }
@@ -110,16 +97,13 @@ extension Sequence {
/// determined by the result of `projection` for each element. /// determined by the result of `projection` for each element.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the sequence. /// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable @inlinable public func uniqued<Subject: Hashable>(on projection: (Element) throws -> Subject)
public func uniqued<Subject: Hashable>( rethrows -> [Element]
on projection: (Element) throws -> Subject {
) rethrows -> [Element] {
var seen: Set<Subject> = [] var seen: Set<Subject> = []
var result: [Element] = [] var result: [Element] = []
for element in self { for element in self {
if seen.insert(try projection(element)).inserted { if seen.insert(try projection(element)).inserted { result.append(element) }
result.append(element)
}
} }
return result return result
} }
@@ -135,10 +119,7 @@ extension LazySequenceProtocol {
/// of each unique element. /// of each unique element.
/// ///
/// - Complexity: O(1). /// - Complexity: O(1).
@inlinable @inlinable public func uniqued<Subject: Hashable>(on projection: @escaping (Element) -> Subject)
public func uniqued<Subject: Hashable>( -> Uniqued<Self, Subject>
on projection: @escaping (Element) -> Subject { Uniqued(base: self, projection: projection) }
) -> Uniqued<Self, Subject> {
Uniqued(base: self, projection: projection)
}
} }
+98 -150
View File
@@ -38,8 +38,7 @@ extension Collection {
/// - Complexity: O(1) if the collection conforms to /// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`. /// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`.
/// Access to successive windows is O(1). /// Access to successive windows is O(1).
@inlinable @inlinable public func windows(ofCount count: Int) -> Windows<Self> {
public func windows(ofCount count: Int) -> Windows<Self> {
Windows(base: self, size: count) Windows(base: self, size: count)
} }
} }
@@ -47,133 +46,106 @@ extension Collection {
/// A collection wrapper that presents a sliding window over the elements of /// A collection wrapper that presents a sliding window over the elements of
/// a collection. /// a collection.
public struct Windows<Base: Collection> { public struct Windows<Base: Collection> {
@usableFromInline @usableFromInline internal let base: Base
internal let base: Base
@usableFromInline
internal let size: Int
@usableFromInline
internal var firstUpperBound: Base.Index?
@inlinable @usableFromInline internal let size: Int
internal init(base: Base, size: Int) {
@usableFromInline internal var firstUpperBound: Base.Index?
@inlinable internal init(base: Base, size: Int) {
precondition(size > 0, "Windows size must be greater than zero") precondition(size > 0, "Windows size must be greater than zero")
self.base = base self.base = base
self.size = size self.size = size
self.firstUpperBound = self.firstUpperBound = base.index(base.startIndex, offsetBy: size, limitedBy: base.endIndex)
base.index(base.startIndex, offsetBy: size, limitedBy: base.endIndex)
} }
} }
extension Windows: Collection { extension Windows: Collection {
/// A position in a `Windows` collection. /// A position in a `Windows` collection.
public struct Index: Comparable { public struct Index: Comparable {
@usableFromInline @usableFromInline internal var lowerBound: Base.Index
internal var lowerBound: Base.Index
@usableFromInline internal var upperBound: Base.Index
@usableFromInline
internal var upperBound: Base.Index @inlinable internal init(lowerBound: Base.Index, upperBound: Base.Index) {
@inlinable
internal init(lowerBound: Base.Index, upperBound: Base.Index) {
self.lowerBound = lowerBound self.lowerBound = lowerBound
self.upperBound = upperBound self.upperBound = upperBound
} }
@inlinable @inlinable public static func == (lhs: Index, rhs: Index) -> Bool {
public static func == (lhs: Index, rhs: Index) -> Bool {
lhs.lowerBound == rhs.lowerBound lhs.lowerBound == rhs.lowerBound
} }
@inlinable @inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.lowerBound < rhs.lowerBound lhs.lowerBound < rhs.lowerBound
} }
} }
@inlinable @inlinable public var startIndex: Index {
public var startIndex: Index {
if let upperBound = firstUpperBound { if let upperBound = firstUpperBound {
return Index(lowerBound: base.startIndex, upperBound: upperBound) return Index(lowerBound: base.startIndex, upperBound: upperBound)
} else { } else {
return endIndex return endIndex
} }
} }
@inlinable @inlinable public var endIndex: Index {
public var endIndex: Index {
Index(lowerBound: base.endIndex, upperBound: base.endIndex) Index(lowerBound: base.endIndex, upperBound: base.endIndex)
} }
@inlinable @inlinable public subscript(index: Index) -> Base.SubSequence {
public subscript(index: Index) -> Base.SubSequence { precondition(index.lowerBound != index.upperBound, "Windows index is out of range")
precondition(
index.lowerBound != index.upperBound,
"Windows index is out of range")
return base[index.lowerBound..<index.upperBound] return base[index.lowerBound..<index.upperBound]
} }
@inlinable @inlinable public func index(after index: Index) -> Index {
public func index(after index: Index) -> Index {
precondition(index < endIndex, "Advancing past end index") precondition(index < endIndex, "Advancing past end index")
guard index.upperBound < base.endIndex else { return endIndex } guard index.upperBound < base.endIndex else { return endIndex }
return Index( return Index(
lowerBound: base.index(after: index.lowerBound), lowerBound: base.index(after: index.lowerBound),
upperBound: base.index(after: index.upperBound) upperBound: base.index(after: index.upperBound))
)
} }
@inlinable @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i } guard distance != 0 else { return i }
return distance > 0 return distance > 0 ? offsetForward(i, by: distance) : offsetBackward(i, by: -distance)
? offsetForward(i, by: distance)
: offsetBackward(i, by: -distance)
} }
@inlinable @inlinable public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index?
public func index( {
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
guard distance != 0 else { return i } guard distance != 0 else { return i }
guard limit != i else { return nil } guard limit != i else { return nil }
if distance > 0 { if distance > 0 {
return limit > i return limit > i
? offsetForward(i, by: distance, limitedBy: limit) ? offsetForward(i, by: distance, limitedBy: limit) : offsetForward(i, by: distance)
: offsetForward(i, by: distance)
} else { } else {
return limit < i return limit < i
? offsetBackward(i, by: -distance, limitedBy: limit) ? offsetBackward(i, by: -distance, limitedBy: limit) : offsetBackward(i, by: -distance)
: offsetBackward(i, by: -distance)
} }
} }
@inlinable @inlinable internal func offsetForward(_ i: Index, by distance: Int) -> Index {
internal func offsetForward(_ i: Index, by distance: Int) -> Index { guard let index = offsetForward(i, by: distance, limitedBy: endIndex) else {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex) fatalError("Index is out of bounds")
else { fatalError("Index is out of bounds") } }
return index return index
} }
@inlinable @inlinable internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
internal func offsetBackward(_ i: Index, by distance: Int) -> Index { guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) else {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) fatalError("Index is out of bounds")
else { fatalError("Index is out of bounds") } }
return index return index
} }
@inlinable @inlinable internal func offsetForward(_ i: Index, by distance: Int, limitedBy limit: Index)
internal func offsetForward( -> Index?
_ i: Index, by distance: Int, limitedBy limit: Index {
) -> Index? {
assert(distance > 0) assert(distance > 0)
assert(limit > i) assert(limit > i)
// `endIndex` and the index before it both have `base.endIndex` as their // `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 // 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` // bound of the output, in order to avoid advancing past the end of `base`
@@ -184,67 +156,58 @@ extension Windows: Collection {
// input: [x|x x x x x|x x x x] [x x|x x x x x|x x x] // input: [x|x x x x x|x x x x] [x x|x x x x x|x x x]
// |> > >|>| or |> > >| // |> > >|>| or |> > >|
// output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`) // output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`)
if distance >= size { if distance >= size {
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the lower // 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 // bound of the output is greater than or equal to the upper bound of the
// input. // input.
// input: [x|x x x x|x x x x x x x] // 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] // output: [x x x x x x x|x x x x|x]
guard limit.lowerBound >= i.upperBound, guard limit.lowerBound >= i.upperBound,
let lowerBound = base.index( let lowerBound = base.index(
i.upperBound, i.upperBound, offsetBy: distance - size, limitedBy: limit.lowerBound),
offsetBy: distance - size, let indexBeforeUpperBound = base.index(
limitedBy: limit.lowerBound), lowerBound, offsetBy: size - 1, limitedBy: limit.upperBound)
let indexBeforeUpperBound = base.index(
lowerBound,
offsetBy: size - 1,
limitedBy: limit.upperBound)
else { return nil } else { return nil }
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to // If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
// `endIndex`. // `endIndex`.
guard indexBeforeUpperBound != base.endIndex else { return endIndex } guard indexBeforeUpperBound != base.endIndex else { return endIndex }
return Index( return Index(lowerBound: lowerBound, upperBound: base.index(after: indexBeforeUpperBound))
lowerBound: lowerBound,
upperBound: base.index(after: indexBeforeUpperBound))
} else { } else {
// input: [x|x x x x x x|x x x x x] // 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] // output: [x x x x x|x x x x x x|x]
guard let indexBeforeUpperBound = base.index( guard
i.upperBound, let indexBeforeUpperBound = base.index(
offsetBy: distance - 1, i.upperBound, offsetBy: distance - 1, limitedBy: limit.upperBound)
limitedBy: limit.upperBound)
else { return nil } else { return nil }
// If `indexBeforeUpperBound` equals the limit, the upper bound itself // If `indexBeforeUpperBound` equals the limit, the upper bound itself
// exceeds it. // exceeds it.
guard indexBeforeUpperBound != limit.upperBound || limit == endIndex guard indexBeforeUpperBound != limit.upperBound || limit == endIndex else { return nil }
else { return nil }
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to // If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
// `endIndex`. // `endIndex`.
guard indexBeforeUpperBound != base.endIndex else { return endIndex } guard indexBeforeUpperBound != base.endIndex else { return endIndex }
return Index( return Index(
lowerBound: base.index(i.lowerBound, offsetBy: distance), lowerBound: base.index(i.lowerBound, offsetBy: distance),
upperBound: base.index(after: indexBeforeUpperBound)) upperBound: base.index(after: indexBeforeUpperBound))
} }
} }
@inlinable @inlinable internal func offsetBackward(_ i: Index, by distance: Int, limitedBy limit: Index)
internal func offsetBackward( -> Index?
_ i: Index, by distance: Int, limitedBy limit: Index {
) -> Index? {
assert(distance > 0) assert(distance > 0)
assert(limit < i) assert(limit < i)
if i == endIndex { if i == endIndex {
// Advance `base.endIndex` by `distance - 1`, because the index before // Advance `base.endIndex` by `distance - 1`, because the index before
// `endIndex` also has `base.endIndex` as its upper bound. // `endIndex` also has `base.endIndex` as its upper bound.
@@ -254,16 +217,13 @@ extension Windows: Collection {
// input: [x x x x x x x x x x] (`endIndex`) // input: [x x x x x x x x x x] (`endIndex`)
// |< < < < <|< < <| // |< < < < <|< < <|
// output: [x x|x x x x x|x x x] // output: [x x|x x x x x|x x x]
guard let upperBound = base.index( guard
base.endIndex, let upperBound = base.index(
offsetBy: -(distance - 1), base.endIndex, offsetBy: -(distance - 1), limitedBy: limit.upperBound)
limitedBy: limit.upperBound)
else { return nil } else { return nil }
return Index( return Index(lowerBound: base.index(upperBound, offsetBy: -size), upperBound: upperBound)
lowerBound: base.index(upperBound, offsetBy: -size),
upperBound: upperBound)
} else if distance >= size { } else if distance >= size {
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the upper // 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 // bound of the output is less than or equal to the lower bound of the
@@ -272,36 +232,28 @@ extension Windows: Collection {
// input: [x x x x x x x|x x x x|x] // 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] // output: [x|x x x x|x x x x x x x]
guard limit.upperBound <= i.lowerBound, guard limit.upperBound <= i.lowerBound,
let upperBound = base.index( let upperBound = base.index(
i.lowerBound, i.lowerBound, offsetBy: -(distance - size), limitedBy: limit.upperBound)
offsetBy: -(distance - size),
limitedBy: limit.upperBound)
else { return nil } else { return nil }
return Index( return Index(lowerBound: base.index(upperBound, offsetBy: -size), upperBound: upperBound)
lowerBound: base.index(upperBound, offsetBy: -size),
upperBound: upperBound)
} else { } else {
// input: [x x x x x|x x x x x x|x] // 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] // output: [x|x x x x x x|x x x x x]
guard let lowerBound = base.index( guard
i.lowerBound, let lowerBound = base.index(i.lowerBound, offsetBy: -distance, limitedBy: limit.lowerBound)
offsetBy: -distance,
limitedBy: limit.lowerBound)
else { return nil } else { return nil }
return Index( return Index(
lowerBound: lowerBound, lowerBound: lowerBound, upperBound: base.index(i.lowerBound, offsetBy: -distance))
upperBound: base.index(i.lowerBound, offsetBy: -distance))
} }
} }
@inlinable @inlinable public func distance(from start: Index, to end: Index) -> Int {
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 -distance(from: end, to: start) }
guard start != end else { return 0 } guard start != end else { return 0 }
guard end < endIndex else { guard end < endIndex else {
@@ -317,32 +269,28 @@ extension Windows: Collection {
// start: [x|x x x x|x x x x x x x] // 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] // end: [x x x x x x x|x x x x|x]
return size + base[start.upperBound..<end.lowerBound].count return size + base[start.upperBound..<end.lowerBound].count
} else { } else {
// start: [x|x x x x x x|x x x x x] // 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] // end: [x x x x x|x x x x x x|x]
return base[start.lowerBound..<end.lowerBound].count return base[start.lowerBound..<end.lowerBound].count
} }
} }
} }
extension Windows: BidirectionalCollection where Base: BidirectionalCollection { extension Windows: BidirectionalCollection where Base: BidirectionalCollection {
@inlinable @inlinable public func index(before index: Index) -> Index {
public func index(before index: Index) -> Index {
precondition(index > startIndex, "Incrementing past start index") precondition(index > startIndex, "Incrementing past start index")
if index == endIndex { if index == endIndex {
return Index( return Index(
lowerBound: base.index(index.lowerBound, offsetBy: -size), lowerBound: base.index(index.lowerBound, offsetBy: -size), upperBound: index.upperBound)
upperBound: index.upperBound
)
} else { } else {
return Index( return Index(
lowerBound: base.index(before: index.lowerBound), lowerBound: base.index(before: index.lowerBound),
upperBound: base.index(before: index.upperBound) upperBound: base.index(before: index.upperBound))
)
} }
} }
} }
+4 -4
View File
@@ -11,9 +11,9 @@
#error(""" #error("""
----------------------------------------------------- -----------------------------------------------------
Please test with `swift test --enable-test-discovery` Please test with `swift test --enable-test-discovery`
----------------------------------------------------- -----------------------------------------------------
""") """)
+11 -14
View File
@@ -10,6 +10,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
final class ChainTests: XCTestCase { final class ChainTests: XCTestCase {
@@ -17,51 +18,47 @@ final class ChainTests: XCTestCase {
let run = chain((1...).prefix(10), 20...) let run = chain((1...).prefix(10), 20...)
XCTAssertEqualSequences(run.prefix(20), Array(1...10) + (20..<30)) XCTAssertEqualSequences(run.prefix(20), Array(1...10) + (20..<30))
} }
func testChainForwardCollection() { func testChainForwardCollection() {
let s1 = Set(0...10) let s1 = Set(0...10)
let s2 = Set(20...30) let s2 = Set(20...30)
let c = chain(s1, s2) let c = chain(s1, s2)
XCTAssertEqualSequences(c, Array(s1) + Array(s2)) XCTAssertEqualSequences(c, Array(s1) + Array(s2))
} }
func testChainBidirectionalCollection() { func testChainBidirectionalCollection() {
let s1 = "ABCDEFGHIJ" let s1 = "ABCDEFGHIJ"
let s2 = "klmnopqrstuv" let s2 = "klmnopqrstuv"
let c = chain(s1, s2) let c = chain(s1, s2)
XCTAssertEqualSequences(c, "ABCDEFGHIJklmnopqrstuv") XCTAssertEqualSequences(c, "ABCDEFGHIJklmnopqrstuv")
XCTAssertEqualSequences(c.reversed(), "ABCDEFGHIJklmnopqrstuv".reversed()) XCTAssertEqualSequences(c.reversed(), "ABCDEFGHIJklmnopqrstuv".reversed())
XCTAssertEqualSequences(chain(s1.reversed(), s2), "JIHGFEDCBAklmnopqrstuv") XCTAssertEqualSequences(chain(s1.reversed(), s2), "JIHGFEDCBAklmnopqrstuv")
} }
func testChainIndexTraversals() { func testChainIndexTraversals() {
validateIndexTraversals( validateIndexTraversals(
chain("abcd", "XYZ"), chain("abcd", "XYZ"), chain("abcd", ""), chain("", "XYZ"), chain("", ""),
chain("abcd", ""),
chain("", "XYZ"),
chain("", ""),
indices: { chain in indices: { chain in
chain.base1.indices.map { .init(first: $0) } chain.base1.indices.map { .init(first: $0) } + chain.base2.indices.map { .init(second: $0) }
+ chain.base2.indices.map { .init(second: $0) }
+ [.init(second: chain.base2.endIndex)] + [.init(second: chain.base2.endIndex)]
}) })
} }
func testChainIndexOffsetAcrossBoundary() { func testChainIndexOffsetAcrossBoundary() {
let c = chain("abc", "XYZ") let c = chain("abc", "XYZ")
do { do {
let i = c.index(c.startIndex, offsetBy: 3, limitedBy: c.startIndex) let i = c.index(c.startIndex, offsetBy: 3, limitedBy: c.startIndex)
XCTAssertNil(i) XCTAssertNil(i)
} }
do { do {
let i = c.index(c.startIndex, offsetBy: 4) let i = c.index(c.startIndex, offsetBy: 4)
let j = c.index(i, offsetBy: -2) let j = c.index(i, offsetBy: -2)
XCTAssertEqual(c[j], "c") XCTAssertEqual(c[j], "c")
} }
do { do {
let i = c.index(c.startIndex, offsetBy: 3) let i = c.index(c.startIndex, offsetBy: 3)
let j = c.index(i, offsetBy: -1, limitedBy: i) let j = c.index(i, offsetBy: -1, limitedBy: i)
+44 -55
View File
@@ -9,47 +9,38 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest
import Algorithms import Algorithms
import XCTest
final class ChunkedTests: XCTestCase { final class ChunkedTests: XCTestCase {
let fruits = [ let fruits = [
"Apple", "Apricot", "Avocado", "Banana", "Apple", "Apricot", "Avocado", "Banana", "Bilberry", "Blackberry", "Blackcurrant", "Blueberry",
"Bilberry", "Blackberry", "Blackcurrant", "Blueberry", "Currant", "Cherry", "Cherimoya", "Clementine", "Date", "Damson", "Dragonfruit", "Durian",
"Currant", "Cherry", "Cherimoya", "Clementine", "Eggplant", "Elderberry", "Feijoa", "Grape", "Grapefruit", "Guava",
"Date", "Damson", "Dragonfruit", "Durian",
"Eggplant", "Elderberry", "Feijoa",
"Grape", "Grapefruit", "Guava",
] ]
func validateFruitChunks<C: BidirectionalCollection>(_ fruitChunks: C) func validateFruitChunks<C: BidirectionalCollection>(_ fruitChunks: C)
where C.Element == ArraySlice<String> where C.Element == ArraySlice<String> {
{ let expectedChunks: [ArraySlice<String>] = [
let expectedChunks: Array<ArraySlice<String>> = [ fruits[0..<3], fruits[3..<8], fruits[8..<12], fruits[12..<16], fruits[16..<18],
fruits[0..<3], fruits[18..<19], fruits[19..<22],
fruits[3..<8],
fruits[8..<12],
fruits[12..<16],
fruits[16..<18],
fruits[18..<19],
fruits[19..<22],
] ]
XCTAssertEqualSequences(expectedChunks, fruitChunks, by: ==) XCTAssertEqualSequences(expectedChunks, fruitChunks, by: ==)
XCTAssertEqual(fruits[19..<22], fruitChunks.last) XCTAssertEqual(fruits[19..<22], fruitChunks.last)
XCTAssertEqual("Currant", fruitChunks.first(where: { $0.count == 4 })?.first) XCTAssertEqual("Currant", fruitChunks.first(where: { $0.count == 4 })?.first)
XCTAssertEqual("Date", fruitChunks.last(where: { $0.count == 4 })?.first) XCTAssertEqual("Date", fruitChunks.last(where: { $0.count == 4 })?.first)
XCTAssertNil(fruitChunks.first(where: { $0.count == 0 })) XCTAssertNil(fruitChunks.first(where: { $0.count == 0 }))
XCTAssertNil(fruitChunks.last(where: { $0.count == 0 })) XCTAssertNil(fruitChunks.last(where: { $0.count == 0 }))
} }
func testSimple() { func testSimple() {
// Example // Example
let names = ["David", "Kyle", "Karoy", "Nate"] let names = ["David", "Kyle", "Karoy", "Nate"]
let chunks = names.chunked(on: { $0.first }) let chunks = names.chunked(on: { $0.first })
XCTAssertEqualSequences([["David"], ["Kyle", "Karoy"], ["Nate"]], chunks) XCTAssertEqualSequences([["David"], ["Kyle", "Karoy"], ["Nate"]], chunks)
// Empty sequence // Empty sequence
XCTAssertEqual(0, names.prefix(0).chunked(on: { $0.first }).count) XCTAssertEqual(0, names.prefix(0).chunked(on: { $0.first }).count)
@@ -57,27 +48,26 @@ final class ChunkedTests: XCTestCase {
let namesStartingWithD = ["David", "Don", "Darren"] let namesStartingWithD = ["David", "Don", "Darren"]
XCTAssertEqual(1, namesStartingWithD.chunked(on: { $0.first }).count) XCTAssertEqual(1, namesStartingWithD.chunked(on: { $0.first }).count)
} }
func testChunkedOn() { func testChunkedOn() {
validateFruitChunks(fruits.chunked(on: { $0.first })) validateFruitChunks(fruits.chunked(on: { $0.first }))
let lazyChunks = fruits.lazy.chunked(on: { $0.first }) let lazyChunks = fruits.lazy.chunked(on: { $0.first })
validateFruitChunks(lazyChunks) validateFruitChunks(lazyChunks)
} }
func testChunkedBy() { func testChunkedBy() {
validateFruitChunks(fruits.chunked(by: { $0.first == $1.first })) validateFruitChunks(fruits.chunked(by: { $0.first == $1.first }))
let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first }) let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first })
validateFruitChunks(lazyChunks) validateFruitChunks(lazyChunks)
} }
func testChunkedLazy() { func testChunkedLazy() {
XCTAssertLazySequence(fruits.lazy.chunked(by: { $0.first == $1.first })) XCTAssertLazySequence(fruits.lazy.chunked(by: { $0.first == $1.first }))
XCTAssertLazySequence(fruits.lazy.chunked(on: { $0.first })) XCTAssertLazySequence(fruits.lazy.chunked(on: { $0.first }))
} }
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// Tests for `chunks(ofCount:)` // Tests for `chunks(ofCount:)`
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
@@ -86,37 +76,36 @@ final class ChunkedTests: XCTestCase {
XCTAssertEqualSequences([Int]().chunks(ofCount: 5), []) XCTAssertEqualSequences([Int]().chunks(ofCount: 5), [])
let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
XCTAssertEqualSequences(collection1.chunks(ofCount: 1), XCTAssertEqualSequences(
[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]) collection1.chunks(ofCount: 1), [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
XCTAssertEqualSequences(collection1.chunks(ofCount: 3), XCTAssertEqualSequences(
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]) collection1.chunks(ofCount: 3), [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]])
XCTAssertEqualSequences(collection1.chunks(ofCount: 5), XCTAssertEqualSequences(collection1.chunks(ofCount: 5), [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) XCTAssertEqualSequences(collection1.chunks(ofCount: 11), [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
XCTAssertEqualSequences(collection1.chunks(ofCount: 11),
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
XCTAssertEqualSequences(collection2.chunks(ofCount: 3), XCTAssertEqualSequences(
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]) collection2.chunks(ofCount: 3), [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]])
} }
func testChunksOfCountBidirectional() { func testChunksOfCountBidirectional() {
let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
XCTAssertEqualSequences(collection1.chunks(ofCount: 1).reversed(), XCTAssertEqualSequences(
[[10], [9], [8], [7], [6], [5], [4], [3], [2], [1]]) collection1.chunks(ofCount: 1).reversed(),
XCTAssertEqualSequences(collection1.chunks(ofCount: 3).reversed(), [[10], [9], [8], [7], [6], [5], [4], [3], [2], [1]])
[[10], [7, 8, 9], [4, 5, 6], [1, 2, 3]]) XCTAssertEqualSequences(
XCTAssertEqualSequences(collection1.chunks(ofCount: 5).reversed(), collection1.chunks(ofCount: 3).reversed(), [[10], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
[[6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]) XCTAssertEqualSequences(
XCTAssertEqualSequences(collection1.chunks(ofCount: 11).reversed(), collection1.chunks(ofCount: 5).reversed(), [[6, 7, 8, 9, 10], [1, 2, 3, 4, 5]])
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) XCTAssertEqualSequences(
collection1.chunks(ofCount: 11).reversed(), [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
XCTAssertEqualSequences(collection2.chunks(ofCount: 3).reversed(), XCTAssertEqualSequences(
[[10, 11], [7, 8, 9], [4, 5, 6], [1, 2, 3]]) collection2.chunks(ofCount: 3).reversed(), [[10, 11], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
} }
func testChunksOfCountCount() { func testChunksOfCountCount() {
XCTAssertEqual([Int]().chunks(ofCount: 1).count, 0) XCTAssertEqual([Int]().chunks(ofCount: 1).count, 0)
XCTAssertEqual([Int]().chunks(ofCount: 5).count, 0) XCTAssertEqual([Int]().chunks(ofCount: 5).count, 0)
@@ -126,22 +115,22 @@ final class ChunkedTests: XCTestCase {
XCTAssertEqual(collection1.chunks(ofCount: 3).count, 4) XCTAssertEqual(collection1.chunks(ofCount: 3).count, 4)
XCTAssertEqual(collection1.chunks(ofCount: 5).count, 2) XCTAssertEqual(collection1.chunks(ofCount: 5).count, 2)
XCTAssertEqual(collection1.chunks(ofCount: 11).count, 1) XCTAssertEqual(collection1.chunks(ofCount: 11).count, 1)
let collection2 = (1...50).map { $0 } let collection2 = (1...50).map { $0 }
XCTAssertEqual(collection2.chunks(ofCount: 9).count, 6) XCTAssertEqual(collection2.chunks(ofCount: 9).count, 6)
} }
func testEmptyChunksOfCountTraversal() { func testEmptyChunksOfCountTraversal() {
let emptyChunks = [Int]().chunks(ofCount: 1) let emptyChunks = [Int]().chunks(ofCount: 1)
validateIndexTraversals(emptyChunks) validateIndexTraversals(emptyChunks)
} }
func testChunksOfCountTraversal() { func testChunksOfCountTraversal() {
for i in 1..<10 { for i in 1..<10 {
let collection = (1...50).map { $0 } let collection = (1...50).map { $0 }
let chunks = collection.chunks(ofCount: i) let chunks = collection.chunks(ofCount: i)
validateIndexTraversals(chunks) validateIndexTraversals(chunks)
} }
} }
@@ -9,113 +9,131 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest
import Algorithms import Algorithms
import XCTest
final class CombinationsTests: XCTestCase { final class CombinationsTests: XCTestCase {
func testCount() { func testCount() {
let c = "ABCD" let c = "ABCD"
let c0 = c.combinations(ofCount: 0).count let c0 = c.combinations(ofCount: 0).count
XCTAssertEqual(c0, 1) XCTAssertEqual(c0, 1)
let c1 = c.combinations(ofCount: 1).count let c1 = c.combinations(ofCount: 1).count
XCTAssertEqual(c1, 4) XCTAssertEqual(c1, 4)
let c2 = c.combinations(ofCount: 2).count let c2 = c.combinations(ofCount: 2).count
XCTAssertEqual(c2, 6) XCTAssertEqual(c2, 6)
let c3 = c.combinations(ofCount: 3).count let c3 = c.combinations(ofCount: 3).count
XCTAssertEqual(c3, 4) XCTAssertEqual(c3, 4)
let c4 = c.combinations(ofCount: 4).count let c4 = c.combinations(ofCount: 4).count
XCTAssertEqual(c4, 1) XCTAssertEqual(c4, 1)
let c5 = c.combinations(ofCount: 0...0).count let c5 = c.combinations(ofCount: 0...0).count
XCTAssertEqual(c5, 1) XCTAssertEqual(c5, 1)
let c6 = c.combinations(ofCount: 1...1).count let c6 = c.combinations(ofCount: 1...1).count
XCTAssertEqual(c6, 4) XCTAssertEqual(c6, 4)
let c7 = c.combinations(ofCount: 1...2).count let c7 = c.combinations(ofCount: 1...2).count
XCTAssertEqual(c7, 10) XCTAssertEqual(c7, 10)
let c8 = c.combinations(ofCount: 1...3).count let c8 = c.combinations(ofCount: 1...3).count
XCTAssertEqual(c8, 14) XCTAssertEqual(c8, 14)
let c9 = c.combinations(ofCount: 2...4).count let c9 = c.combinations(ofCount: 2...4).count
XCTAssertEqual(c9, 11) XCTAssertEqual(c9, 11)
// `k` greater than element count results in same number of combinations // `k` greater than element count results in same number of combinations
let c10 = c.combinations(ofCount: 3...10).count let c10 = c.combinations(ofCount: 3...10).count
XCTAssertEqual(c10, 5) XCTAssertEqual(c10, 5)
// `k` greater than element count results in same number of combinations // `k` greater than element count results in same number of combinations
let c11 = c.combinations(ofCount: 4...10).count let c11 = c.combinations(ofCount: 4...10).count
XCTAssertEqual(c11, 1) XCTAssertEqual(c11, 1)
// `k` entirely greater than element count results in no combinations // `k` entirely greater than element count results in no combinations
let c12 = c.combinations(ofCount: 5...10).count let c12 = c.combinations(ofCount: 5...10).count
XCTAssertEqual(c12, 0) XCTAssertEqual(c12, 0)
let c13 = c.combinations(ofCount: 0...).count let c13 = c.combinations(ofCount: 0...).count
XCTAssertEqual(c13, 16) XCTAssertEqual(c13, 16)
let c14 = c.combinations(ofCount: ...3).count let c14 = c.combinations(ofCount: ...3).count
XCTAssertEqual(c14, 15) XCTAssertEqual(c14, 15)
let c15 = c.combinations(ofCount: 0...).count let c15 = c.combinations(ofCount: 0...).count
XCTAssertEqual(c15, 16) XCTAssertEqual(c15, 16)
} }
func testCombinations() { func testCombinations() {
let c = "ABCD" let c = "ABCD"
let c1 = c.combinations(ofCount: 1) let c1 = c.combinations(ofCount: 1)
XCTAssertEqual(["A", "B", "C", "D"], c1.map { String($0) }) XCTAssertEqual(["A", "B", "C", "D"], c1.map { String($0) })
let c2 = c.combinations(ofCount: 2) let c2 = c.combinations(ofCount: 2)
XCTAssertEqual(["AB", "AC", "AD", "BC", "BD", "CD"], c2.map { String($0) }) XCTAssertEqual(["AB", "AC", "AD", "BC", "BD", "CD"], c2.map { String($0) })
let c3 = c.combinations(ofCount: 3) let c3 = c.combinations(ofCount: 3)
XCTAssertEqual(["ABC", "ABD", "ACD", "BCD"], c3.map { String($0) }) XCTAssertEqual(["ABC", "ABD", "ACD", "BCD"], c3.map { String($0) })
let c4 = c.combinations(ofCount: 4) let c4 = c.combinations(ofCount: 4)
XCTAssertEqual(["ABCD"], c4.map { String($0) }) XCTAssertEqual(["ABCD"], c4.map { String($0) })
let c5 = c.combinations(ofCount: 2...4) let c5 = c.combinations(ofCount: 2...4)
XCTAssertEqual(["AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c5.map { String($0) }) XCTAssertEqual(
["AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"],
c5.map { String($0) })
let c6 = c.combinations(ofCount: 0...4) let c6 = c.combinations(ofCount: 0...4)
XCTAssertEqual(["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c6.map { String($0) }) XCTAssertEqual(
[
"", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD",
"ABCD",
], c6.map { String($0) })
let c7 = c.combinations(ofCount: 0...) let c7 = c.combinations(ofCount: 0...)
XCTAssertEqual(["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c7.map { String($0) }) XCTAssertEqual(
[
"", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD",
"ABCD",
], c7.map { String($0) })
let c8 = c.combinations(ofCount: ...4) let c8 = c.combinations(ofCount: ...4)
XCTAssertEqual(["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c8.map { String($0) }) XCTAssertEqual(
[
"", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD",
"ABCD",
], c8.map { String($0) })
let c9 = c.combinations(ofCount: ...3) let c9 = c.combinations(ofCount: ...3)
XCTAssertEqual(["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD"], c9.map { String($0) }) XCTAssertEqual(
["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD"],
c9.map { String($0) })
let c10 = c.combinations(ofCount: 1...) let c10 = c.combinations(ofCount: 1...)
XCTAssertEqual(["A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c10.map { String($0) }) XCTAssertEqual(
["A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"],
c10.map { String($0) })
} }
func testEmpty() { func testEmpty() {
// `k == 0` results in one zero-length combination // `k == 0` results in one zero-length combination
XCTAssertEqualSequences([[]], "".combinations(ofCount: 0)) XCTAssertEqualSequences([[]], "".combinations(ofCount: 0))
XCTAssertEqualSequences([[]], "".combinations(ofCount: 0...0)) XCTAssertEqualSequences([[]], "".combinations(ofCount: 0...0))
XCTAssertEqualSequences([[]], "ABCD".combinations(ofCount: 0)) XCTAssertEqualSequences([[]], "ABCD".combinations(ofCount: 0))
XCTAssertEqualSequences([[]], "ABCD".combinations(ofCount: 0...0)) XCTAssertEqualSequences([[]], "ABCD".combinations(ofCount: 0...0))
// `k` greater than element count results in zero combinations // `k` greater than element count results in zero combinations
XCTAssertEqualSequences([], "".combinations(ofCount: 5)) XCTAssertEqualSequences([], "".combinations(ofCount: 5))
XCTAssertEqualSequences([], "".combinations(ofCount: 5...10)) XCTAssertEqualSequences([], "".combinations(ofCount: 5...10))
XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5)) XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5))
XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5...10)) XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5...10))
} }
func testCombinationsLazy() { func testCombinationsLazy() {
XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1)) XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1))
XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1...3)) XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1...3))
@@ -9,36 +9,28 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest
import Algorithms import Algorithms
import XCTest
final class CompactedTests: XCTestCase { final class CompactedTests: XCTestCase {
let tests: [[Int?]] = let tests: [[Int?]] = [nil, nil, nil, 0, 1, 2].uniquePermutations(ofCount: 0...).map(Array.init)
[nil, nil, nil, 0, 1, 2]
.uniquePermutations(ofCount: 0...)
.map(Array.init)
func testCompactedCompacted() { func testCompactedCompacted() {
for collection in self.tests { for collection in self.tests {
let seq = AnySequence(collection) let seq = AnySequence(collection)
XCTAssertEqualSequences( XCTAssertEqualSequences(seq.compactMap({ $0 }), seq.compacted())
seq.compactMap({ $0 }), seq.compacted()) XCTAssertEqualSequences(collection.compactMap({ $0 }), collection.compacted())
XCTAssertEqualSequences(
collection.compactMap({ $0 }), collection.compacted())
} }
} }
func testCompactedBidirectionalCollection() { func testCompactedBidirectionalCollection() {
for array in self.tests { for array in self.tests {
XCTAssertEqualSequences(array.compactMap({ $0 }).reversed(), XCTAssertEqualSequences(array.compactMap({ $0 }).reversed(), array.compacted().reversed())
array.compacted().reversed())
} }
} }
func testCollectionTraversals() { func testCollectionTraversals() {
for array in self.tests { for array in self.tests { validateIndexTraversals(array.compacted()) }
validateIndexTraversals(array.compacted())
}
} }
} }
+6 -15
View File
@@ -9,16 +9,14 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest
import Algorithms import Algorithms
import XCTest
final class CycleTests: XCTestCase { final class CycleTests: XCTestCase {
func testCycle() { func testCycle() {
let cycle = (1...4).cycled() let cycle = (1...4).cycled()
XCTAssertEqualSequences( XCTAssertEqualSequences(
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], cycle.prefix(20))
cycle.prefix(20)
)
} }
func testCycleClosedRangePrefix() { func testCycleClosedRangePrefix() {
@@ -31,15 +29,11 @@ final class CycleTests: XCTestCase {
XCTAssert(empty.isEmpty) XCTAssert(empty.isEmpty)
} }
func testCycleLazy() { func testCycleLazy() { XCTAssertLazySequence((1...4).lazy.cycled()) }
XCTAssertLazySequence((1...4).lazy.cycled())
}
func testRepeated() { func testRepeated() {
let repeats = (1...4).cycled(times: 3) let repeats = (1...4).cycled(times: 3)
XCTAssertEqualSequences( XCTAssertEqualSequences([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], repeats)
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
repeats)
} }
func testRepeatedClosedRange() { func testRepeatedClosedRange() {
@@ -57,9 +51,7 @@ final class CycleTests: XCTestCase {
XCTAssert(empty2.isEmpty) XCTAssert(empty2.isEmpty)
} }
func testRepeatedLazy() { func testRepeatedLazy() { XCTAssertLazySequence((1...4).lazy.cycled(times: 3)) }
XCTAssertLazySequence((1...4).lazy.cycled(times: 3))
}
func testRepeatedIndexMethods() { func testRepeatedIndexMethods() {
let cycle = (1..<5).cycled(times: 2) let cycle = (1..<5).cycled(times: 2)
@@ -73,8 +65,7 @@ final class CycleTests: XCTestCase {
nextIndex = cycle.index(nextIndex, offsetBy: 2, limitedBy: cycle.endIndex)! nextIndex = cycle.index(nextIndex, offsetBy: 2, limitedBy: cycle.endIndex)!
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 8) XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 8)
let outOfBounds = cycle.index(nextIndex, offsetBy: 1, let outOfBounds = cycle.index(nextIndex, offsetBy: 1, limitedBy: cycle.endIndex)
limitedBy: cycle.endIndex)
XCTAssertNil(outOfBounds) XCTAssertNil(outOfBounds)
let previousIndex = cycle.index(before: nextIndex) let previousIndex = cycle.index(before: nextIndex)
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest
import Algorithms import Algorithms
import XCTest
final class FirstNonNilTests: XCTestCase { final class FirstNonNilTests: XCTestCase {
func testFirstNonNil() { func testFirstNonNil() {
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest
import Algorithms import Algorithms
import XCTest
final class IndexedTests: XCTestCase { final class IndexedTests: XCTestCase {
func testIndexed() { func testIndexed() {
@@ -27,8 +27,6 @@ final class IndexedTests: XCTestCase {
let indexOfI = si.last(where: { $0.element == "I" })!.index let indexOfI = si.last(where: { $0.element == "I" })!.index
XCTAssertEqual("I", s[indexOfI]) XCTAssertEqual("I", s[indexOfI])
} }
func testIndexedLazy() { func testIndexedLazy() { XCTAssertLazyCollection("ABCD".lazy.indexed()) }
XCTAssertLazyCollection("ABCD".lazy.indexed())
}
} }
@@ -9,13 +9,13 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest
import Algorithms import Algorithms
import XCTest
final class IntersperseTests: XCTestCase { final class IntersperseTests: XCTestCase {
func testSequence() { func testSequence() {
let interspersed = (1...).prefix(5).interspersed(with: 0) let interspersed = (1...).prefix(5).interspersed(with: 0)
XCTAssertEqualSequences(interspersed, [1,0,2,0,3,0,4,0,5]) XCTAssertEqualSequences(interspersed, [1, 0, 2, 0, 3, 0, 4, 0, 5])
} }
func testSequenceEmpty() { func testSequenceEmpty() {
@@ -36,8 +36,8 @@ final class IntersperseTests: XCTestCase {
} }
func testArray() { func testArray() {
let interspersed = [1,2,3,4].interspersed(with: 0) let interspersed = [1, 2, 3, 4].interspersed(with: 0)
XCTAssertEqualSequences(interspersed, [1,0,2,0,3,0,4]) XCTAssertEqualSequences(interspersed, [1, 0, 2, 0, 3, 0, 4])
validateIndexTraversals(interspersed) validateIndexTraversals(interspersed)
} }
@@ -48,7 +48,7 @@ final class IntersperseTests: XCTestCase {
} }
func testCollection() { func testCollection() {
let interspersed = ["A","B","C","D"].interspersed(with: "-") let interspersed = ["A", "B", "C", "D"].interspersed(with: "-")
XCTAssertEqual(interspersed.count, 7) XCTAssertEqual(interspersed.count, 7)
} }
+217 -432
View File
@@ -17,13 +17,7 @@ import XCTest
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
final class LazySplitTests: XCTestCase { final class LazySplitTests: XCTestCase {
func testEmpty() { func testEmpty() { Validator(subject: [], separator: .element(0), maxSplits: 1).validate() }
Validator(
subject: [],
separator: .element(0),
maxSplits: 1
).validate()
}
// The following test names indicate the sequence being split, using the // The following test names indicate the sequence being split, using the
// notation // notation
@@ -41,54 +35,35 @@ final class LazySplitTests: XCTestCase {
// Length 1 // Length 1
//===--------------------------------------------------------------------===// //===--------------------------------------------------------------------===//
func testE() { func testE() { Validator(subject: [1], separator: .element(0), maxSplits: 0).validate() }
Validator(subject: [1], separator: .element(0), maxSplits: 0).validate()
}
func testS() { func testS() { Validator(subject: [0], separator: .element(0), maxSplits: 0).validate() }
Validator(subject: [0], separator: .element(0), maxSplits: 0).validate()
}
//===--------------------------------------------------------------------===// //===--------------------------------------------------------------------===//
// Length 2 // Length 2
//===--------------------------------------------------------------------===// //===--------------------------------------------------------------------===//
func testEE() { func testEE() { Validator(subject: [1, 1], separator: .element(0), maxSplits: 0).validate() }
Validator(subject: [1, 1], separator: .element(0), maxSplits: 0).validate()
}
func testSS() { func testSS() { Validator(subject: [0, 0], separator: .element(0), maxSplits: 1).validate() }
Validator(subject: [0, 0], separator: .element(0), maxSplits: 1).validate()
}
func testES() { func testES() { Validator(subject: [1, 0], separator: .element(0), maxSplits: 0).validate() }
Validator(subject: [1, 0], separator: .element(0), maxSplits: 0).validate()
}
func testSE() { func testSE() { Validator(subject: [0, 1], separator: .element(0), maxSplits: 0).validate() }
Validator(subject: [0, 1], separator: .element(0), maxSplits: 0).validate()
}
//===--------------------------------------------------------------------===// //===--------------------------------------------------------------------===//
// Length 3 // Length 3
//===--------------------------------------------------------------------===// //===--------------------------------------------------------------------===//
func testEEE() { func testEEE() { Validator(subject: [1, 1, 1], separator: .element(0), maxSplits: 0).validate() }
Validator(subject: [1, 1, 1], separator: .element(0), maxSplits: 0)
.validate()
}
func testSSS() { func testSSS() { Validator(subject: [0, 0, 0], separator: .element(0), maxSplits: 1).validate() }
Validator(subject: [0, 0, 0], separator: .element(0), maxSplits: 1)
.validate()
}
func testAllEES() { func testAllEES() {
let permutations = [[1, 1, 0], [1, 0, 1], [0, 1, 1]] let permutations = [[1, 1, 0], [1, 0, 1], [0, 1, 1]]
for permutation in permutations { for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 0) Validator(subject: permutation, separator: .element(0), maxSplits: 0).validate()
.validate()
} }
} }
@@ -96,8 +71,7 @@ final class LazySplitTests: XCTestCase {
let permutations = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] let permutations = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
for permutation in permutations { for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1) Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
.validate()
} }
} }
@@ -106,18 +80,14 @@ final class LazySplitTests: XCTestCase {
//===--------------------------------------------------------------------===// //===--------------------------------------------------------------------===//
func testEEEE() { func testEEEE() {
Validator(subject: [1, 1, 1, 1], separator: .element(0), maxSplits: 0) Validator(subject: [1, 1, 1, 1], separator: .element(0), maxSplits: 0).validate()
.validate()
} }
func testAllEEES() { func testAllEEES() {
let permutations = [ let permutations = [[1, 1, 1, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1]]
[1, 1, 1, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1]
]
for permutation in permutations { for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 0) Validator(subject: permutation, separator: .element(0), maxSplits: 0).validate()
.validate()
} }
} }
@@ -128,48 +98,41 @@ final class LazySplitTests: XCTestCase {
// All separators. // All separators.
func testSSSS() { func testSSSS() {
Validator(subject: [0, 0, 0, 0], separator: .element(0), maxSplits: 1) Validator(subject: [0, 0, 0, 0], separator: .element(0), maxSplits: 1).validate()
.validate()
} }
// Equal numbers of elements and separators. // Equal numbers of elements and separators.
func testAllEESS() { func testAllEESS() {
let permutations = [ let permutations = [
[1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 0, 1, 1],
[0, 1, 1, 0], [0, 1, 0, 1], [0, 0, 1, 1],
] ]
for permutation in permutations { for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1) Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
.validate()
} }
} }
// More separators than elements. // More separators than elements.
func testAllEESSS() { func testAllEESSS() {
let permutations = [ let permutations = [
[1, 1, 0, 0, 0], [1, 0, 1, 0, 0], [1, 0, 0, 1, 0], [1, 0, 0, 0, 1], [1, 1, 0, 0, 0], [1, 0, 1, 0, 0], [1, 0, 0, 1, 0], [1, 0, 0, 0, 1], [0, 1, 1, 0, 0],
[0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 1], [0, 0, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 1], [0, 0, 1, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 1, 1],
[0, 0, 1, 0, 1], [0, 0, 0, 1, 1],
] ]
for permutation in permutations { for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1) Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
.validate()
} }
} }
// More elements than separators. // More elements than separators.
func testAllEEESS() { func testAllEEESS() {
let permutations = [ let permutations = [
[1, 1, 1, 0, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 1], [1, 0, 1, 1, 0], [1, 1, 1, 0, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 1], [1, 0, 1, 1, 0], [1, 0, 1, 0, 1],
[1, 0, 1, 0, 1], [1, 0, 0, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], [1, 0, 0, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], [0, 1, 0, 1, 1], [0, 0, 1, 1, 1],
[0, 1, 0, 1, 1], [0, 0, 1, 1, 1],
] ]
for permutation in permutations { for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1) Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
.validate()
} }
} }
@@ -178,35 +141,28 @@ final class LazySplitTests: XCTestCase {
//===--------------------------------------------------------------------===// //===--------------------------------------------------------------------===//
func testAllESSS() { func testAllESSS() {
let permutations = [ let permutations = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1],
]
for permutation in permutations { for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1) Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
.validate()
} }
} }
func testAllEEEESSS() { func testAllEEEESSS() {
let permutations = [ let permutations = [
[1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0], [1, 1, 1, 0, 0, 1, 0], [1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0], [1, 1, 1, 0, 0, 1, 0], [1, 1, 1, 0, 0, 0, 1],
[1, 1, 1, 0, 0, 0, 1], [1, 1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1, 0], [1, 1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1, 0], [1, 1, 0, 1, 0, 0, 1], [1, 1, 0, 0, 1, 1, 0],
[1, 1, 0, 1, 0, 0, 1], [1, 1, 0, 0, 1, 1, 0], [1, 1, 0, 0, 1, 0, 1], [1, 1, 0, 0, 1, 0, 1], [1, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0],
[1, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0], [1, 0, 1, 1, 0, 0, 1], [1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 0, 1, 1],
[1, 0, 1, 1, 0, 0, 1], [1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1], [1, 0, 0, 1, 1, 1, 0], [1, 0, 0, 1, 1, 0, 1], [1, 0, 0, 1, 0, 1, 1], [1, 0, 0, 0, 1, 1, 1],
[1, 0, 1, 0, 0, 1, 1], [1, 0, 0, 1, 1, 1, 0], [1, 0, 0, 1, 1, 0, 1], [0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0],
[1, 0, 0, 1, 0, 1, 1], [1, 0, 0, 0, 1, 1, 1], [0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 0, 1], [0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 1, 1, 0], [0, 1, 0, 1, 1, 0, 1],
[0, 1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0], [0, 1, 0, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 1],
[0, 1, 1, 0, 1, 0, 1], [0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 1, 1, 0], [0, 0, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1],
[0, 1, 0, 1, 1, 0, 1], [0, 1, 0, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 1], [0, 0, 1, 1, 0, 1, 1],
[0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1],
] ]
for permutation in permutations { for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1) Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
.validate()
} }
} }
@@ -219,143 +175,105 @@ final class LazySplitTests: XCTestCase {
// Equal numbers of separators and elements. // Equal numbers of separators and elements.
func testAllEEEESSSS() { func testAllEEEESSSS() {
let permutations = [ let permutations = [
[1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0, 0], [1, 1, 1, 0, 0, 1, 0, 0],
[1, 1, 1, 0, 0, 1, 0, 0], [1, 1, 1, 0, 0, 0, 1, 0], [1, 1, 1, 0, 0, 0, 1, 0], [1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 0, 1, 1, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 0, 1, 1, 0, 0, 0], [1, 1, 0, 1, 0, 1, 0, 0], [1, 1, 0, 1, 0, 0, 1, 0], [1, 1, 0, 1, 0, 0, 0, 1],
[1, 1, 0, 1, 0, 1, 0, 0], [1, 1, 0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 0, 1, 0], [1, 1, 0, 0, 1, 0, 0, 1],
[1, 1, 0, 1, 0, 0, 0, 1], [1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 0, 1, 1, 0], [1, 1, 0, 0, 0, 1, 0, 1], [1, 1, 0, 0, 0, 0, 1, 1],
[1, 1, 0, 0, 1, 0, 1, 0], [1, 1, 0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 1, 0, 0, 0], [1, 0, 1, 1, 0, 1, 0, 0], [1, 0, 1, 1, 0, 0, 1, 0],
[1, 1, 0, 0, 0, 1, 1, 0], [1, 1, 0, 0, 0, 1, 0, 1], [1, 0, 1, 1, 0, 0, 0, 1], [1, 0, 1, 0, 1, 1, 0, 0], [1, 0, 1, 0, 1, 0, 1, 0],
[1, 1, 0, 0, 0, 0, 1, 1], [1, 0, 1, 1, 1, 0, 0, 0], [1, 0, 1, 0, 1, 0, 0, 1], [1, 0, 1, 0, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 0, 1],
[1, 0, 1, 1, 0, 1, 0, 0], [1, 0, 1, 1, 0, 0, 1, 0], [1, 0, 1, 0, 0, 0, 1, 1], [1, 0, 0, 1, 1, 1, 0, 0], [1, 0, 0, 1, 1, 0, 1, 0],
[1, 0, 1, 1, 0, 0, 0, 1], [1, 0, 1, 0, 1, 1, 0, 0], [1, 0, 0, 1, 1, 0, 0, 1], [1, 0, 0, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0], [1, 0, 1, 0, 1, 0, 0, 1], [1, 0, 0, 1, 0, 0, 1, 1], [1, 0, 0, 0, 1, 1, 1, 0], [1, 0, 0, 0, 1, 1, 0, 1],
[1, 0, 1, 0, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 0, 1], [1, 0, 0, 0, 1, 0, 1, 1], [1, 0, 0, 0, 0, 1, 1, 1], [0, 1, 1, 1, 1, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 1, 1], [1, 0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 1, 0, 0], [0, 1, 1, 1, 0, 0, 1, 0], [0, 1, 1, 1, 0, 0, 0, 1],
[1, 0, 0, 1, 1, 0, 1, 0], [1, 0, 0, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0, 0], [0, 1, 1, 0, 1, 0, 1, 0], [0, 1, 1, 0, 1, 0, 0, 1],
[1, 0, 0, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0, 1, 0, 1], [0, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 0, 0, 0, 1, 1],
[1, 0, 0, 1, 0, 0, 1, 1], [1, 0, 0, 0, 1, 1, 1, 0], [0, 1, 0, 1, 1, 1, 0, 0], [0, 1, 0, 1, 1, 0, 1, 0], [0, 1, 0, 1, 1, 0, 0, 1],
[1, 0, 0, 0, 1, 1, 0, 1], [1, 0, 0, 0, 1, 0, 1, 1], [0, 1, 0, 1, 0, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 0, 1, 1],
[1, 0, 0, 0, 0, 1, 1, 1], [0, 1, 1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 1, 1, 1, 0], [0, 1, 0, 0, 1, 1, 0, 1], [0, 1, 0, 0, 1, 0, 1, 1],
[0, 1, 1, 1, 0, 1, 0, 0], [0, 1, 1, 1, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 1, 0],
[0, 1, 1, 1, 0, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0, 1], [0, 0, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 0, 1, 0, 1],
[0, 1, 1, 0, 1, 0, 1, 0], [0, 1, 1, 0, 1, 0, 0, 1], [0, 0, 1, 1, 0, 0, 1, 1], [0, 0, 1, 0, 1, 1, 1, 0], [0, 0, 1, 0, 1, 1, 0, 1],
[0, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 1], [0, 0, 1, 0, 1, 0, 1, 1], [0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1, 0],
[0, 1, 1, 0, 0, 0, 1, 1], [0, 1, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 1], [0, 0, 0, 1, 1, 0, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1],
[0, 1, 0, 1, 1, 0, 1, 0], [0, 1, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 1, 1, 1, 1],
[0, 1, 0, 1, 0, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 0, 1, 1], [0, 1, 0, 0, 1, 1, 1, 0],
[0, 1, 0, 0, 1, 1, 0, 1], [0, 1, 0, 0, 1, 0, 1, 1],
[0, 1, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 0, 1, 0, 1],
[0, 0, 1, 1, 0, 0, 1, 1], [0, 0, 1, 0, 1, 1, 1, 0],
[0, 0, 1, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1, 0, 1, 1],
[0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1, 0],
[0, 0, 0, 1, 1, 1, 0, 1], [0, 0, 0, 1, 1, 0, 1, 1],
[0, 0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1],
] ]
for permutation in permutations { for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1) Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
.validate()
} }
} }
// More separators than elements. // More separators than elements.
func testAllEEESSSS() { func testAllEEESSSS() {
let permutations = [ let permutations = [
[1, 1, 1, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0], [1, 1, 0, 0, 1, 0, 0], [1, 1, 1, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0], [1, 1, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 1, 0],
[1, 1, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 0, 0], [1, 1, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 0, 0], [1, 0, 1, 0, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0],
[1, 0, 1, 0, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0], [1, 0, 1, 0, 0, 0, 1], [1, 0, 1, 0, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0], [1, 0, 0, 1, 0, 1, 0], [1, 0, 0, 1, 0, 0, 1],
[1, 0, 0, 1, 1, 0, 0], [1, 0, 0, 1, 0, 1, 0], [1, 0, 0, 1, 0, 0, 1], [1, 0, 0, 0, 1, 1, 0], [1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 1, 1], [0, 1, 1, 1, 0, 0, 0],
[1, 0, 0, 0, 1, 1, 0], [1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 1, 1], [0, 1, 1, 0, 1, 0, 0], [0, 1, 1, 0, 0, 1, 0], [0, 1, 1, 0, 0, 0, 1], [0, 1, 0, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0], [0, 1, 1, 0, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 0, 1], [0, 1, 0, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0, 1],
[0, 1, 1, 0, 0, 0, 1], [0, 1, 0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 0, 0, 1, 1], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1, 0], [0, 0, 1, 1, 0, 0, 1],
[0, 1, 0, 1, 0, 0, 1], [0, 1, 0, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0, 1], [0, 0, 1, 0, 1, 1, 0], [0, 0, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 0],
[0, 1, 0, 0, 0, 1, 1], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1, 0], [0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 1, 1, 1],
[0, 0, 1, 1, 0, 0, 1], [0, 0, 1, 0, 1, 1, 0], [0, 0, 1, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 1, 1, 0, 1],
[0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 1, 1, 1],
] ]
for permutation in permutations { for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1) Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
.validate()
} }
} }
// More elements than separators. // More elements than separators.
func testAllEEEEESSSS() { func testAllEEEEESSSS() {
let permutations = [ let permutations = [
[1, 1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 0, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 0, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 0],
[1, 1, 1, 1, 0, 0, 1, 0, 0], [1, 1, 1, 1, 0, 0, 0, 1, 0], [1, 1, 1, 1, 0, 0, 0, 1, 0], [1, 1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 1, 0, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 1, 0, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 0, 1, 0, 0], [1, 1, 1, 0, 1, 0, 0, 1, 0], [1, 1, 1, 0, 1, 0, 0, 0, 1],
[1, 1, 1, 0, 1, 0, 1, 0, 0], [1, 1, 1, 0, 1, 0, 0, 1, 0], [1, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 1, 0, 0, 1, 0, 1, 0], [1, 1, 1, 0, 0, 1, 0, 0, 1],
[1, 1, 1, 0, 1, 0, 0, 0, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 1, 0, 0, 0, 1, 1, 0], [1, 1, 1, 0, 0, 0, 1, 0, 1], [1, 1, 1, 0, 0, 0, 0, 1, 1],
[1, 1, 1, 0, 0, 1, 0, 1, 0], [1, 1, 1, 0, 0, 1, 0, 0, 1], [1, 1, 0, 1, 1, 1, 0, 0, 0], [1, 1, 0, 1, 1, 0, 1, 0, 0], [1, 1, 0, 1, 1, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 0, 1, 1, 0], [1, 1, 1, 0, 0, 0, 1, 0, 1], [1, 1, 0, 1, 1, 0, 0, 0, 1], [1, 1, 0, 1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1, 0, 1, 0],
[1, 1, 1, 0, 0, 0, 0, 1, 1], [1, 1, 0, 1, 1, 1, 0, 0, 0], [1, 1, 0, 1, 0, 1, 0, 0, 1], [1, 1, 0, 1, 0, 0, 1, 1, 0], [1, 1, 0, 1, 0, 0, 1, 0, 1],
[1, 1, 0, 1, 1, 0, 1, 0, 0], [1, 1, 0, 1, 1, 0, 0, 1, 0], [1, 1, 0, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 1, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 1, 0],
[1, 1, 0, 1, 1, 0, 0, 0, 1], [1, 1, 0, 1, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1], [1, 1, 0, 0, 1, 0, 1, 1, 0], [1, 1, 0, 0, 1, 0, 1, 0, 1],
[1, 1, 0, 1, 0, 1, 0, 1, 0], [1, 1, 0, 1, 0, 1, 0, 0, 1], [1, 1, 0, 0, 1, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1, 1, 0], [1, 1, 0, 0, 0, 1, 1, 0, 1],
[1, 1, 0, 1, 0, 0, 1, 1, 0], [1, 1, 0, 1, 0, 0, 1, 0, 1], [1, 1, 0, 0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 0, 0, 1, 1, 1], [1, 0, 1, 1, 1, 1, 0, 0, 0],
[1, 1, 0, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 1, 1, 1, 0, 0], [1, 0, 1, 1, 1, 0, 1, 0, 0], [1, 0, 1, 1, 1, 0, 0, 1, 0], [1, 0, 1, 1, 1, 0, 0, 0, 1],
[1, 1, 0, 0, 1, 1, 0, 1, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1], [1, 0, 1, 1, 0, 1, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0, 1, 0], [1, 0, 1, 1, 0, 1, 0, 0, 1],
[1, 1, 0, 0, 1, 0, 1, 1, 0], [1, 1, 0, 0, 1, 0, 1, 0, 1], [1, 0, 1, 1, 0, 0, 1, 1, 0], [1, 0, 1, 1, 0, 0, 1, 0, 1], [1, 0, 1, 1, 0, 0, 0, 1, 1],
[1, 1, 0, 0, 1, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1, 1, 0], [1, 0, 1, 0, 1, 1, 1, 0, 0], [1, 0, 1, 0, 1, 1, 0, 1, 0], [1, 0, 1, 0, 1, 1, 0, 0, 1],
[1, 1, 0, 0, 0, 1, 1, 0, 1], [1, 1, 0, 0, 0, 1, 0, 1, 1], [1, 0, 1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0, 0, 1, 1],
[1, 1, 0, 0, 0, 0, 1, 1, 1], [1, 0, 1, 1, 1, 1, 0, 0, 0], [1, 0, 1, 0, 0, 1, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1], [1, 0, 1, 0, 0, 1, 0, 1, 1],
[1, 0, 1, 1, 1, 0, 1, 0, 0], [1, 0, 1, 1, 1, 0, 0, 1, 0], [1, 0, 1, 0, 0, 0, 1, 1, 1], [1, 0, 0, 1, 1, 1, 1, 0, 0], [1, 0, 0, 1, 1, 1, 0, 1, 0],
[1, 0, 1, 1, 1, 0, 0, 0, 1], [1, 0, 1, 1, 0, 1, 1, 0, 0], [1, 0, 0, 1, 1, 1, 0, 0, 1], [1, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 0, 1, 1, 0, 1, 0, 1],
[1, 0, 1, 1, 0, 1, 0, 1, 0], [1, 0, 1, 1, 0, 1, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0, 1, 1], [1, 0, 0, 1, 0, 1, 1, 1, 0], [1, 0, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 1, 1, 0, 0, 1, 1, 0], [1, 0, 1, 1, 0, 0, 1, 0, 1], [1, 0, 0, 1, 0, 1, 0, 1, 1], [1, 0, 0, 1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 1, 1, 1, 1, 0],
[1, 0, 1, 1, 0, 0, 0, 1, 1], [1, 0, 1, 0, 1, 1, 1, 0, 0], [1, 0, 0, 0, 1, 1, 1, 0, 1], [1, 0, 0, 0, 1, 1, 0, 1, 1], [1, 0, 0, 0, 1, 0, 1, 1, 1],
[1, 0, 1, 0, 1, 1, 0, 1, 0], [1, 0, 1, 0, 1, 1, 0, 0, 1], [1, 0, 0, 0, 0, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 1, 1, 1, 0, 0, 1, 0], [0, 1, 1, 1, 1, 0, 0, 0, 1], [0, 1, 1, 1, 0, 1, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 1, 1], [1, 0, 1, 0, 0, 1, 1, 1, 0], [0, 1, 1, 1, 0, 1, 0, 1, 0], [0, 1, 1, 1, 0, 1, 0, 0, 1], [0, 1, 1, 1, 0, 0, 1, 1, 0],
[1, 0, 1, 0, 0, 1, 1, 0, 1], [1, 0, 1, 0, 0, 1, 0, 1, 1], [0, 1, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 1, 0, 0, 0, 1, 1], [0, 1, 1, 0, 1, 1, 1, 0, 0],
[1, 0, 1, 0, 0, 0, 1, 1, 1], [1, 0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0, 1, 0], [0, 1, 1, 0, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 0, 1, 1, 0],
[1, 0, 0, 1, 1, 1, 0, 1, 0], [1, 0, 0, 1, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 0, 1, 0, 1], [0, 1, 1, 0, 1, 0, 0, 1, 1], [0, 1, 1, 0, 0, 1, 1, 1, 0],
[1, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 0, 1, 1, 0, 1, 0, 1], [0, 1, 1, 0, 0, 1, 1, 0, 1], [0, 1, 1, 0, 0, 1, 0, 1, 1], [0, 1, 1, 0, 0, 0, 1, 1, 1],
[1, 0, 0, 1, 1, 0, 0, 1, 1], [1, 0, 0, 1, 0, 1, 1, 1, 0], [0, 1, 0, 1, 1, 1, 1, 0, 0], [0, 1, 0, 1, 1, 1, 0, 1, 0], [0, 1, 0, 1, 1, 1, 0, 0, 1],
[1, 0, 0, 1, 0, 1, 1, 0, 1], [1, 0, 0, 1, 0, 1, 0, 1, 1], [0, 1, 0, 1, 1, 0, 1, 1, 0], [0, 1, 0, 1, 1, 0, 1, 0, 1], [0, 1, 0, 1, 1, 0, 0, 1, 1],
[1, 0, 0, 1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 1, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 1, 0, 1], [0, 1, 0, 1, 0, 1, 0, 1, 1],
[1, 0, 0, 0, 1, 1, 1, 0, 1], [1, 0, 0, 0, 1, 1, 0, 1, 1], [0, 1, 0, 1, 0, 0, 1, 1, 1], [0, 1, 0, 0, 1, 1, 1, 1, 0], [0, 1, 0, 0, 1, 1, 1, 0, 1],
[1, 0, 0, 0, 1, 0, 1, 1, 1], [1, 0, 0, 0, 0, 1, 1, 1, 1], [0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 1, 0, 0, 1, 0, 1, 1, 1], [0, 1, 0, 0, 0, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0, 1],
[0, 1, 1, 1, 1, 0, 0, 1, 0], [0, 1, 1, 1, 1, 0, 0, 0, 1], [0, 0, 1, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 1, 0, 1, 0, 1], [0, 0, 1, 1, 1, 0, 0, 1, 1],
[0, 1, 1, 1, 0, 1, 1, 0, 0], [0, 1, 1, 1, 0, 1, 0, 1, 0], [0, 0, 1, 1, 0, 1, 1, 1, 0], [0, 0, 1, 1, 0, 1, 1, 0, 1], [0, 0, 1, 1, 0, 1, 0, 1, 1],
[0, 1, 1, 1, 0, 1, 0, 0, 1], [0, 1, 1, 1, 0, 0, 1, 1, 0], [0, 0, 1, 1, 0, 0, 1, 1, 1], [0, 0, 1, 0, 1, 1, 1, 1, 0], [0, 0, 1, 0, 1, 1, 1, 0, 1],
[0, 1, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 1, 0, 0, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1, 1, 1, 1],
[0, 1, 1, 0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0, 1, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 0, 1], [0, 0, 0, 1, 1, 1, 0, 1, 1],
[0, 1, 1, 0, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0, 1, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1, 1],
[0, 1, 1, 0, 1, 0, 1, 0, 1], [0, 1, 1, 0, 1, 0, 0, 1, 1],
[0, 1, 1, 0, 0, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0, 1],
[0, 1, 1, 0, 0, 1, 0, 1, 1], [0, 1, 1, 0, 0, 0, 1, 1, 1],
[0, 1, 0, 1, 1, 1, 1, 0, 0], [0, 1, 0, 1, 1, 1, 0, 1, 0],
[0, 1, 0, 1, 1, 1, 0, 0, 1], [0, 1, 0, 1, 1, 0, 1, 1, 0],
[0, 1, 0, 1, 1, 0, 1, 0, 1], [0, 1, 0, 1, 1, 0, 0, 1, 1],
[0, 1, 0, 1, 0, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 1, 0, 1],
[0, 1, 0, 1, 0, 1, 0, 1, 1], [0, 1, 0, 1, 0, 0, 1, 1, 1],
[0, 1, 0, 0, 1, 1, 1, 1, 0], [0, 1, 0, 0, 1, 1, 1, 0, 1],
[0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 1, 0, 0, 1, 0, 1, 1, 1],
[0, 1, 0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 1, 0, 1, 0, 1],
[0, 0, 1, 1, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 1, 1, 1, 0],
[0, 0, 1, 1, 0, 1, 1, 0, 1], [0, 0, 1, 1, 0, 1, 0, 1, 1],
[0, 0, 1, 1, 0, 0, 1, 1, 1], [0, 0, 1, 0, 1, 1, 1, 1, 0],
[0, 0, 1, 0, 1, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1, 0, 1, 1],
[0, 0, 1, 0, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 0, 1],
[0, 0, 0, 1, 1, 1, 0, 1, 1], [0, 0, 0, 1, 1, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1, 1],
] ]
for permutation in permutations { for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1) Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
.validate()
} }
} }
@@ -367,53 +285,38 @@ final class LazySplitTests: XCTestCase {
// More separators than elements. // More separators than elements.
func testAllEEESSSSSS() { func testAllEEESSSSSS() {
let permutations = [ let permutations = [
[1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 1, 0, 0, 0, 0],
[1, 1, 0, 0, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 1, 0, 0, 0], [1, 1, 0, 0, 0, 1, 0, 0, 0], [1, 1, 0, 0, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 0, 0, 1, 0],
[1, 1, 0, 0, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 0, 0, 0, 0], [1, 0, 1, 0, 1, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 1, 0, 0, 0], [1, 0, 1, 0, 0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 0, 0, 1, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 1, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0, 0, 0], [1, 0, 0, 1, 0, 1, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 0, 0, 1, 0], [1, 0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 0, 1, 0, 0, 0, 1, 0], [1, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0, 0, 0], [1, 0, 0, 0, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 0, 1, 0, 0], [1, 0, 0, 0, 1, 0, 0, 1, 0],
[1, 0, 0, 1, 0, 1, 0, 0, 0], [1, 0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 0, 0, 1, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1, 1, 0, 0], [1, 0, 0, 0, 0, 1, 0, 1, 0],
[1, 0, 0, 1, 0, 0, 0, 1, 0], [1, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 1, 0], [1, 0, 0, 0, 0, 0, 1, 0, 1],
[1, 0, 0, 0, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 1], [0, 1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 1, 0, 0, 1, 0], [1, 0, 0, 0, 1, 0, 0, 0, 1], [0, 1, 1, 0, 0, 1, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 0, 0], [0, 1, 1, 0, 0, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 1, 1, 0, 0], [1, 0, 0, 0, 0, 1, 0, 1, 0], [0, 1, 1, 0, 0, 0, 0, 0, 1], [0, 1, 0, 1, 1, 0, 0, 0, 0], [0, 1, 0, 1, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 1, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 1, 0], [0, 1, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1, 1], [0, 1, 0, 0, 1, 1, 0, 0, 0], [0, 1, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0, 0, 1, 0],
[0, 1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 1], [0, 1, 0, 0, 0, 1, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 1, 0],
[0, 1, 1, 0, 0, 1, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0, 1], [0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0, 1],
[0, 1, 1, 0, 0, 0, 0, 1, 0], [0, 1, 1, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 1, 1], [0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 1, 0, 0, 0],
[0, 1, 0, 1, 1, 0, 0, 0, 0], [0, 1, 0, 1, 0, 1, 0, 0, 0], [0, 0, 1, 1, 0, 0, 1, 0, 0], [0, 0, 1, 1, 0, 0, 0, 1, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1],
[0, 1, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0, 1, 0],
[0, 1, 0, 1, 0, 0, 0, 0, 1], [0, 1, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0, 1], [0, 0, 1, 0, 0, 1, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 1, 0],
[0, 1, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 0, 1, 0, 1],
[0, 1, 0, 0, 1, 0, 0, 0, 1], [0, 1, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 1, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0, 0, 1], [0, 0, 0, 1, 1, 0, 0, 1, 0], [0, 0, 0, 1, 1, 0, 0, 0, 1], [0, 0, 0, 1, 0, 1, 1, 0, 0],
[0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 1, 0, 1, 0], [0, 0, 0, 1, 0, 1, 0, 0, 1], [0, 0, 0, 1, 0, 0, 1, 1, 0],
[0, 1, 0, 0, 0, 0, 0, 1, 1], [0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 1, 0, 0, 0], [0, 0, 1, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 1, 0, 1, 0], [0, 0, 0, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 1, 0, 1, 1, 0],
[0, 0, 1, 1, 0, 0, 0, 1, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 0],
[0, 0, 1, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 1, 0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 1, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 1, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 0, 1, 1, 0],
[0, 0, 1, 0, 0, 0, 1, 0, 1], [0, 0, 1, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 1, 0, 0, 1, 0], [0, 0, 0, 1, 1, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 1, 1, 0, 0], [0, 0, 0, 1, 0, 1, 0, 1, 0],
[0, 0, 0, 1, 0, 1, 0, 0, 1], [0, 0, 0, 1, 0, 0, 1, 1, 0],
[0, 0, 0, 1, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 1, 1, 0, 1],
[0, 0, 0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1],
] ]
for permutation in permutations { for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1) Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
.validate()
} }
} }
@@ -424,11 +327,7 @@ final class LazySplitTests: XCTestCase {
// The motivating example from // The motivating example from
// https://github.com/apple/swift-algorithms/issues/59. // https://github.com/apple/swift-algorithms/issues/59.
func testSplitFilenameComponents() { func testSplitFilenameComponents() {
Validator( Validator(subject: "archive.tar.gz", separator: .element("."), maxSplits: 1).validate()
subject: "archive.tar.gz",
separator: .element("."),
maxSplits: 1
).validate()
} }
// Examples from documentation. // Examples from documentation.
@@ -436,15 +335,12 @@ final class LazySplitTests: XCTestCase {
// Closure version. // Closure version.
let numbers = stride(from: 1, through: 16, by: 1) let numbers = stride(from: 1, through: 16, by: 1)
Validator( Validator(
subject: Array(numbers), subject: Array(numbers), separator: .closure({ $0 % 3 == 0 || $0 % 5 == 0 }), maxSplits: 1
separator: .closure({ $0 % 3 == 0 || $0 % 5 == 0 }),
maxSplits: 1
).validate() ).validate()
// Equatable element version. // Equatable element version.
let numbers2 = [1, 2, 0, 3, 4, 0, 0, 5] let numbers2 = [1, 2, 0, 3, 4, 0, 0, 5]
Validator(subject: numbers2, separator: .element(0), maxSplits: 1) Validator(subject: numbers2, separator: .element(0), maxSplits: 1).validate()
.validate()
} }
func testCollectionDocExample() { func testCollectionDocExample() {
@@ -456,22 +352,17 @@ final class LazySplitTests: XCTestCase {
// above. Preserved to ensure we're not losing any test coverage. // above. Preserved to ensure we're not losing any test coverage.
func testVintagePatterns() { func testVintagePatterns() {
let pattern1 = [1, 2, 42, 3, 4, 42, 5, 6, 42, 7] let pattern1 = [1, 2, 42, 3, 4, 42, 5, 6, 42, 7]
Validator(subject: pattern1, separator: .element(42), maxSplits: 2) Validator(subject: pattern1, separator: .element(42), maxSplits: 2).validate()
.validate() Validator(subject: pattern1, separator: .element(42), maxSplits: 0).validate()
Validator(subject: pattern1, separator: .element(42), maxSplits: 0)
.validate()
let pattern2 = [42, 1, 2, 42, 3, 4, 42, 5, 6, 42, 7] let pattern2 = [42, 1, 2, 42, 3, 4, 42, 5, 6, 42, 7]
Validator(subject: pattern2, separator: .element(42), maxSplits: 2) Validator(subject: pattern2, separator: .element(42), maxSplits: 2).validate()
.validate()
let pattern3 = [1, 2, 42, 3, 4, 42, 42, 5, 6, 42, 7] let pattern3 = [1, 2, 42, 3, 4, 42, 42, 5, 6, 42, 7]
Validator(subject: pattern3, separator: .element(42), maxSplits: 2) Validator(subject: pattern3, separator: .element(42), maxSplits: 2).validate()
.validate()
let pattern4 = [1, 2, 42, 3, 4, 42, 42, 5, 6, 42, 7, 42, 42, 42] let pattern4 = [1, 2, 42, 3, 4, 42, 42, 5, 6, 42, 7, 42, 42, 42]
Validator(subject: pattern4, separator: .element(42), maxSplits: 1) Validator(subject: pattern4, separator: .element(42), maxSplits: 1).validate()
.validate()
} }
//===--------------------------------------------------------------------===// //===--------------------------------------------------------------------===//
@@ -507,8 +398,7 @@ final class LazySplitTests: XCTestCase {
/// determine the element--on which to split. /// determine the element--on which to split.
/// - maxSplits: The value to pass for `maxSplits` during validation. The /// - maxSplits: The value to pass for `maxSplits` during validation. The
/// default value is also validated. /// default value is also validated.
fileprivate struct Validator<C: Collection> fileprivate struct Validator<C: Collection> where C.Element: Equatable, C.SubSequence: Equatable {
where C.Element: Equatable, C.SubSequence: Equatable {
enum Separator { enum Separator {
case element(C.Element) case element(C.Element)
case closure((C.Element) -> Bool) case closure((C.Element) -> Bool)
@@ -529,10 +419,8 @@ final class LazySplitTests: XCTestCase {
var description: String { var description: String {
switch self { switch self {
case .provided(let value): case .provided(let value): return "maxSplits: \(value)"
return "maxSplits: \(value)" case .defaultValue: return "maxSplits: default"
case .defaultValue:
return "maxSplits: default"
} }
} }
} }
@@ -543,159 +431,108 @@ final class LazySplitTests: XCTestCase {
var description: String { var description: String {
switch self { switch self {
case .provided(let value): case .provided(let value): return "omittingEmptySubsequences: \(value)"
return "omittingEmptySubsequences: \(value)" case .defaultValue: return "omittingEmptySubsequences: default"
case .defaultValue:
return "omittingEmptySubsequences: default"
} }
} }
} }
private func failureMessage<L: LazySequenceProtocol, S: Sequence>( private func failureMessage<L: LazySequenceProtocol, S: Sequence>(
actual: L, actual: L, expected: S, maxSplits: MaxSplits,
expected: S,
maxSplits: MaxSplits,
omittingEmptySubsequences: OmittingEmptySubsequences omittingEmptySubsequences: OmittingEmptySubsequences
) -> String { ) -> String {
"for \(Array(subject).debugDescription), \(maxSplits), \(omittingEmptySubsequences): \(Array(actual).debugDescription) != \(Array(expected).debugDescription)" "for \(Array(subject).debugDescription), \(maxSplits), \(omittingEmptySubsequences): \(Array(actual).debugDescription) != \(Array(expected).debugDescription)"
} }
private func _validateAsSequence<T: Sequence>(_ s: T) private func _validateAsSequence<T: Sequence>(_ s: T) where T.Element == C.Element {
where T.Element == C.Element {
// Default max splits, omitting empty sequences // Default max splits, omitting empty sequences
switch separator { switch separator {
case let .element(element): case let .element(element):
let expected = s.split(separator: element).map { Array($0) } let expected = s.split(separator: element).map { Array($0) }
let actual = s.lazy.split(separator: element) let actual = s.lazy.split(separator: element)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue, actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue) omittingEmptySubsequences: .defaultValue))
)
case let .closure(closure): case let .closure(closure):
let expected = s.split(whereSeparator: closure).map { Array($0) } let expected = s.split(whereSeparator: closure).map { Array($0) }
let actual = s.lazy.split(whereSeparator: closure) let actual = s.lazy.split(whereSeparator: closure)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue, actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue) omittingEmptySubsequences: .defaultValue))
)
} }
// Provided max splits, omitting empty sequences // Provided max splits, omitting empty sequences
switch separator { switch separator {
case let .element(element): case let .element(element):
let expected = s.split( let expected = s.split(separator: element, maxSplits: maxSplits).map { Array($0) }
separator: element, let actual = s.lazy.split(separator: element, maxSplits: maxSplits)
maxSplits: maxSplits
).map { Array($0) }
let actual = s.lazy.split(
separator: element,
maxSplits: maxSplits
)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits), actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue) omittingEmptySubsequences: .defaultValue))
)
case let .closure(closure): case let .closure(closure):
let expected = s.split( let expected = s.split(maxSplits: maxSplits, whereSeparator: closure).map { Array($0) }
maxSplits: maxSplits, let actual = s.lazy.split(maxSplits: maxSplits, whereSeparator: closure)
whereSeparator: closure
).map { Array($0) }
let actual = s.lazy.split(
maxSplits: maxSplits,
whereSeparator: closure
)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits), actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue) omittingEmptySubsequences: .defaultValue))
)
} }
// Default max splits, including empty sequences // Default max splits, including empty sequences
switch separator { switch separator {
case let .element(element): case let .element(element):
let expected = s.split( let expected = s.split(separator: element, omittingEmptySubsequences: false).map {
separator: element, Array($0)
omittingEmptySubsequences: false }
).map { Array($0) } let actual = s.lazy.split(separator: element, omittingEmptySubsequences: false)
let actual = s.lazy.split(
separator: element,
omittingEmptySubsequences: false
)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue, actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false)) omittingEmptySubsequences: .provided(false)))
)
case let .closure(closure): case let .closure(closure):
let expected = s.split( let expected = s.split(omittingEmptySubsequences: false, whereSeparator: closure).map {
omittingEmptySubsequences: false, Array($0)
whereSeparator: closure }
).map { Array($0) } let actual = s.lazy.split(omittingEmptySubsequences: false, whereSeparator: closure)
let actual = s.lazy.split(
omittingEmptySubsequences: false,
whereSeparator: closure
)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue, actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false)) omittingEmptySubsequences: .provided(false)))
)
} }
// Provided max splits, including empty sequences // Provided max splits, including empty sequences
switch separator { switch separator {
case let .element(element): case let .element(element):
let expected = s.split( let expected = s.split(
separator: element, separator: element, maxSplits: maxSplits, omittingEmptySubsequences: false
maxSplits: maxSplits,
omittingEmptySubsequences: false
).map { Array($0) } ).map { Array($0) }
let actual = s.lazy.split( let actual = s.lazy.split(
separator: element, separator: element, maxSplits: maxSplits, omittingEmptySubsequences: false)
maxSplits: maxSplits,
omittingEmptySubsequences: false
)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits), actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false)) omittingEmptySubsequences: .provided(false)))
)
case let .closure(closure): case let .closure(closure):
let expected = s.split( let expected = s.split(
maxSplits: maxSplits, maxSplits: maxSplits, omittingEmptySubsequences: false, whereSeparator: closure
omittingEmptySubsequences: false,
whereSeparator: closure
).map { Array($0) } ).map { Array($0) }
let actual = s.lazy.split( let actual = s.lazy.split(
maxSplits: maxSplits, maxSplits: maxSplits, omittingEmptySubsequences: false, whereSeparator: closure)
omittingEmptySubsequences: false,
whereSeparator: closure
)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits), actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false)) omittingEmptySubsequences: .provided(false)))
)
} }
} }
@@ -706,134 +543,82 @@ final class LazySplitTests: XCTestCase {
let expected = c.split(separator: element) let expected = c.split(separator: element)
let actual = c.lazy.split(separator: element) let actual = c.lazy.split(separator: element)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue, actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue) omittingEmptySubsequences: .defaultValue))
)
case let .closure(closure): case let .closure(closure):
let expected = c.split(whereSeparator: closure) let expected = c.split(whereSeparator: closure)
let actual = c.lazy.split(whereSeparator: closure) let actual = c.lazy.split(whereSeparator: closure)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue, actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue) omittingEmptySubsequences: .defaultValue))
)
} }
// Provided max splits, omitting empty sequences // Provided max splits, omitting empty sequences
switch separator { switch separator {
case let .element(element): case let .element(element):
let expected = c.split( let expected = c.split(separator: element, maxSplits: maxSplits)
separator: element, let actual = c.lazy.split(separator: element, maxSplits: maxSplits)
maxSplits: maxSplits
)
let actual = c.lazy.split(
separator: element,
maxSplits: maxSplits
)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits), actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue) omittingEmptySubsequences: .defaultValue))
)
case let .closure(closure): case let .closure(closure):
let expected = c.split( let expected = c.split(maxSplits: maxSplits, whereSeparator: closure)
maxSplits: maxSplits, let actual = c.lazy.split(maxSplits: maxSplits, whereSeparator: closure)
whereSeparator: closure
)
let actual = c.lazy.split(
maxSplits: maxSplits,
whereSeparator: closure
)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits), actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue) omittingEmptySubsequences: .defaultValue))
)
} }
// Default max splits, including empty sequences // Default max splits, including empty sequences
switch separator { switch separator {
case let .element(element): case let .element(element):
let expected = c.split( let expected = c.split(separator: element, omittingEmptySubsequences: false)
separator: element, let actual = c.lazy.split(separator: element, omittingEmptySubsequences: false)
omittingEmptySubsequences: false
)
let actual = c.lazy.split(
separator: element,
omittingEmptySubsequences: false
)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue, actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false)) omittingEmptySubsequences: .provided(false)))
)
case let .closure(closure): case let .closure(closure):
let expected = c.split( let expected = c.split(omittingEmptySubsequences: false, whereSeparator: closure)
omittingEmptySubsequences: false, let actual = c.lazy.split(omittingEmptySubsequences: false, whereSeparator: closure)
whereSeparator: closure
)
let actual = c.lazy.split(
omittingEmptySubsequences: false,
whereSeparator: closure
)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue, actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false)) omittingEmptySubsequences: .provided(false)))
)
} }
// Provided max splits, including empty sequences // Provided max splits, including empty sequences
switch separator { switch separator {
case let .element(element): case let .element(element):
let expected = c.split( let expected = c.split(
separator: element, separator: element, maxSplits: maxSplits, omittingEmptySubsequences: false)
maxSplits: maxSplits,
omittingEmptySubsequences: false
)
let actual = c.lazy.split( let actual = c.lazy.split(
separator: element, separator: element, maxSplits: maxSplits, omittingEmptySubsequences: false)
maxSplits: maxSplits,
omittingEmptySubsequences: false
)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits), actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false)) omittingEmptySubsequences: .provided(false)))
)
case let .closure(closure): case let .closure(closure):
let expected = c.split( let expected = c.split(
maxSplits: maxSplits, maxSplits: maxSplits, omittingEmptySubsequences: false, whereSeparator: closure)
omittingEmptySubsequences: false,
whereSeparator: closure
)
let actual = c.lazy.split( let actual = c.lazy.split(
maxSplits: maxSplits, maxSplits: maxSplits, omittingEmptySubsequences: false, whereSeparator: closure)
omittingEmptySubsequences: false,
whereSeparator: closure
)
XCTAssertEqualSequences( XCTAssertEqualSequences(
expected, expected, actual,
actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits), actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false)) omittingEmptySubsequences: .provided(false)))
)
} }
} }
} }
+44 -72
View File
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest
import Algorithms import Algorithms
import XCTest
final class SortedPrefixTests: XCTestCase { final class SortedPrefixTests: XCTestCase {
func testMinCount() { func testMinCount() {
@@ -20,12 +20,11 @@ final class SortedPrefixTests: XCTestCase {
XCTAssertEqualSequences(min, 0..<5) XCTAssertEqualSequences(min, 0..<5)
// Stability with all equal values // Stability with all equal values
let maxZeroes = Array(repeating: 0, count: 100) let maxZeroes = Array(repeating: 0, count: 100).enumerated().max(
.enumerated() count: 5, sortedBy: { $0.element < $1.element })
.max(count: 5, sortedBy: { $0.element < $1.element })
XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100) XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
} }
func testMaxCount() { func testMaxCount() {
// Replacement at start and end // Replacement at start and end
let input = [0, 11, 12, 1, 13, 2, 14, 3, 4, 5, 6, 7, 8, 9, 10] let input = [0, 11, 12, 1, 13, 2, 14, 3, 4, 5, 6, 7, 8, 9, 10]
@@ -33,17 +32,16 @@ final class SortedPrefixTests: XCTestCase {
XCTAssertEqualSequences(max, 10..<15) XCTAssertEqualSequences(max, 10..<15)
// Stability with all equal values // Stability with all equal values
let maxZeroes = Array(repeating: 0, count: 100) let maxZeroes = Array(repeating: 0, count: 100).enumerated().max(
.enumerated() count: 5, sortedBy: { $0.element < $1.element })
.max(count: 5, sortedBy: { $0.element < $1.element })
XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100) XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
} }
func testEmpty() { func testEmpty() {
let array = [Int]() let array = [Int]()
XCTAssertEqual(array.min(count: 0), []) XCTAssertEqual(array.min(count: 0), [])
XCTAssertEqual(array.min(count: 100), []) XCTAssertEqual(array.min(count: 100), [])
XCTAssertEqual(array.max(count: 0), []) XCTAssertEqual(array.max(count: 0), [])
XCTAssertEqual(array.max(count: 100), []) XCTAssertEqual(array.max(count: 100), [])
} }
@@ -51,14 +49,14 @@ final class SortedPrefixTests: XCTestCase {
func testMinMaxSequences() { func testMinMaxSequences() {
let input = (1...100).shuffled().interspersed(with: 50) let input = (1...100).shuffled().interspersed(with: 50)
let seq = AnySequence(input) let seq = AnySequence(input)
XCTAssertEqualSequences(seq.min(count: 0), []) XCTAssertEqualSequences(seq.min(count: 0), [])
XCTAssertEqualSequences(seq.min(count: 5), 1...5) XCTAssertEqualSequences(seq.min(count: 5), 1...5)
XCTAssertEqualSequences(seq.max(count: 0), []) XCTAssertEqualSequences(seq.max(count: 0), [])
XCTAssertEqualSequences(seq.max(count: 5), 96...100) XCTAssertEqualSequences(seq.max(count: 5), 96...100)
} }
func testSortedPrefixComparable() { func testSortedPrefixComparable() {
let array: [Int] = [20, 1, 4, 70, 100, 2, 3, 7, 90] let array: [Int] = [20, 1, 4, 70, 100, 2, 3, 7, 90]
@@ -67,7 +65,7 @@ final class SortedPrefixTests: XCTestCase {
XCTAssertEqualSequences(array.min(count: 5), array.sorted().prefix(5)) XCTAssertEqualSequences(array.min(count: 5), array.sorted().prefix(5))
XCTAssertEqual(array.min(count: 10), array.sorted()) XCTAssertEqual(array.min(count: 10), array.sorted())
} }
func testMinMaxWithHugeCount() { func testMinMaxWithHugeCount() {
XCTAssertEqual([4, 2, 1, 3].min(count: .max), [1, 2, 3, 4]) XCTAssertEqual([4, 2, 1, 3].min(count: .max), [1, 2, 3, 4])
XCTAssertEqual([4, 2, 1, 3].max(count: .max), [1, 2, 3, 4]) XCTAssertEqual([4, 2, 1, 3].max(count: .max), [1, 2, 3, 4])
@@ -84,21 +82,13 @@ final class SortedPrefixTests: XCTestCase {
XCTAssertEqual(input.min(count: 1, sortedBy: >), [range.upperBound]) XCTAssertEqual(input.min(count: 1, sortedBy: >), [range.upperBound])
XCTAssertEqualSequences(input.min(count: 5, sortedBy: <), range.prefix(5)) XCTAssertEqualSequences(input.min(count: 5, sortedBy: <), range.prefix(5))
XCTAssertEqualSequences( XCTAssertEqualSequences(input.min(count: 5, sortedBy: >), range.suffix(5).reversed())
input.min(count: 5, sortedBy: >),
range.suffix(5).reversed())
XCTAssertEqualSequences( XCTAssertEqualSequences(input.min(count: 500, sortedBy: <), range.prefix(500))
input.min(count: 500, sortedBy: <), XCTAssertEqualSequences(input.min(count: 500, sortedBy: >), range.suffix(500).reversed())
range.prefix(500))
XCTAssertEqualSequences(
input.min(count: 500, sortedBy: >),
range.suffix(500).reversed())
XCTAssertEqualSequences(input.min(count: 1000, sortedBy: <), range) XCTAssertEqualSequences(input.min(count: 1000, sortedBy: <), range)
XCTAssertEqualSequences( XCTAssertEqualSequences(input.min(count: 1000, sortedBy: >), range.reversed())
input.min(count: 1000, sortedBy: >),
range.reversed())
} }
func testMaxCountWithHugeInput() { func testMaxCountWithHugeInput() {
@@ -112,28 +102,20 @@ final class SortedPrefixTests: XCTestCase {
XCTAssertEqual(input.max(count: 1, sortedBy: >), [range.lowerBound]) XCTAssertEqual(input.max(count: 1, sortedBy: >), [range.lowerBound])
XCTAssertEqualSequences(input.max(count: 5, sortedBy: <), range.suffix(5)) XCTAssertEqualSequences(input.max(count: 5, sortedBy: <), range.suffix(5))
XCTAssertEqualSequences( XCTAssertEqualSequences(input.max(count: 5, sortedBy: >), range.prefix(5).reversed())
input.max(count: 5, sortedBy: >),
range.prefix(5).reversed())
XCTAssertEqualSequences( XCTAssertEqualSequences(input.max(count: 500, sortedBy: <), range.suffix(500))
input.max(count: 500, sortedBy: <), XCTAssertEqualSequences(input.max(count: 500, sortedBy: >), range.prefix(500).reversed())
range.suffix(500))
XCTAssertEqualSequences(
input.max(count: 500, sortedBy: >),
range.prefix(500).reversed())
XCTAssertEqualSequences(input.max(count: 1000, sortedBy: <), range) XCTAssertEqualSequences(input.max(count: 1000, sortedBy: <), range)
XCTAssertEqualSequences( XCTAssertEqualSequences(input.max(count: 1000, sortedBy: >), range.reversed())
input.max(count: 1000, sortedBy: >),
range.reversed())
} }
func testStability() { func testStability() {
assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 3) assertStability([1, 1, 1, 2, 5, 7, 3, 6, 2, 5, 7, 3, 6], withCount: 3)
assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 6) assertStability([1, 1, 1, 2, 5, 7, 3, 6, 2, 5, 7, 3, 6], withCount: 6)
assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 20) assertStability([1, 1, 1, 2, 5, 7, 3, 6, 2, 5, 7, 3, 6], withCount: 20)
assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 1000) assertStability([1, 1, 1, 2, 5, 7, 3, 6, 2, 5, 7, 3, 6], withCount: 1000)
assertStability(Array(repeating: 0, count: 100), withCount: 0) assertStability(Array(repeating: 0, count: 100), withCount: 0)
assertStability(Array(repeating: 0, count: 100), withCount: 1) assertStability(Array(repeating: 0, count: 100), withCount: 1)
assertStability(Array(repeating: 0, count: 100), withCount: 2) assertStability(Array(repeating: 0, count: 100), withCount: 2)
@@ -144,43 +126,33 @@ final class SortedPrefixTests: XCTestCase {
assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 5) assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 5)
assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 20) assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 20)
assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 50) assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 50)
assertStability([0,0], withCount: 1) assertStability([0, 0], withCount: 1)
assertStability([0,0], withCount: 2) assertStability([0, 0], withCount: 2)
assertStability([0,1,0,1,0,1], withCount: 2) assertStability([0, 1, 0, 1, 0, 1], withCount: 2)
assertStability([0,1,0,1,0,1], withCount: 6) assertStability([0, 1, 0, 1, 0, 1], withCount: 6)
assertStability([0,0,0,1,1,1], withCount: 1) assertStability([0, 0, 0, 1, 1, 1], withCount: 1)
assertStability([0,0,0,1,1,1], withCount: 3) assertStability([0, 0, 0, 1, 1, 1], withCount: 3)
assertStability([0,0,0,1,1,1], withCount: 4) assertStability([0, 0, 0, 1, 1, 1], withCount: 4)
assertStability([0,0,0,1,1,1], withCount: 6) assertStability([0, 0, 0, 1, 1, 1], withCount: 6)
assertStability([1,1,1,0,0,0], withCount: 1) assertStability([1, 1, 1, 0, 0, 0], withCount: 1)
assertStability([1,1,1,0,0,0], withCount: 3) assertStability([1, 1, 1, 0, 0, 0], withCount: 3)
assertStability([1,1,1,0,0,0], withCount: 4) assertStability([1, 1, 1, 0, 0, 0], withCount: 4)
assertStability([1,1,1,0,0,0], withCount: 6) assertStability([1, 1, 1, 0, 0, 0], withCount: 6)
assertStability([1,1,1,0,0,0], withCount: 5) assertStability([1, 1, 1, 0, 0, 0], withCount: 5)
} }
func assertStability( func assertStability(_ actual: [Int], withCount count: Int) {
_ actual: [Int], func stableOrder(a: (offset: Int, element: Int), b: (offset: Int, element: Int)) -> Bool {
withCount count: Int a.element == b.element ? a.offset < b.offset : a.element < b.element
) {
func stableOrder(
a: (offset: Int, element: Int),
b: (offset: Int, element: Int)) -> Bool
{
a.element == b.element
? a.offset < b.offset
: a.element < b.element
} }
do { do {
let sorted = actual.enumerated() let sorted = actual.enumerated().min(count: count) { $0.element < $1.element }
.min(count: count) { $0.element < $1.element }
XCTAssert(sorted.isSorted(by: stableOrder)) XCTAssert(sorted.isSorted(by: stableOrder))
} }
do { do {
let sorted = actual.enumerated() let sorted = actual.enumerated().max(count: count) { $0.element < $1.element }
.max(count: count) { $0.element < $1.element }
XCTAssert(sorted.isSorted(by: stableOrder)) XCTAssert(sorted.isSorted(by: stableOrder))
} }
} }
+23 -15
View File
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest
import Algorithms import Algorithms
import XCTest
final class PartitionTests: XCTestCase { final class PartitionTests: XCTestCase {
func testStablePartition() { func testStablePartition() {
@@ -60,7 +60,7 @@ final class PartitionTests: XCTestCase {
} }
} }
} }
func testStablePartitionWithSubrange() { func testStablePartitionWithSubrange() {
for length in 10...20 { for length in 10...20 {
let a = Array(0..<length) let a = Array(0..<length)
@@ -72,13 +72,15 @@ final class PartitionTests: XCTestCase {
let p = b.stablePartition(subrange: partitionRange, by: condition) let p = b.stablePartition(subrange: partitionRange, by: condition)
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1) XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) }) XCTAssertEqualSequences(
XCTAssertEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition)) b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
XCTAssertEqualSequences(
b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
} }
} }
} }
} }
func testPartitioningIndex() { func testPartitioningIndex() {
for i in 0..<7 { for i in 0..<7 {
for j in i..<11 { for j in i..<11 {
@@ -91,7 +93,7 @@ final class PartitionTests: XCTestCase {
} }
} }
} }
func testPartitionWithSubrangeBidirectionalCollection() { func testPartitionWithSubrangeBidirectionalCollection() {
for length in 10...20 { for length in 10...20 {
let a = Array(0..<length) let a = Array(0..<length)
@@ -101,10 +103,12 @@ final class PartitionTests: XCTestCase {
let partitionRange = j..<i let partitionRange = j..<i
let condition = { $0 < i - 1 } let condition = { $0 < i - 1 }
let p = b.partition(subrange: partitionRange, by: condition) let p = b.partition(subrange: partitionRange, by: condition)
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1) XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) }) XCTAssertEqualSequences(
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition)) b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
XCTAssertUnorderedEqualSequences(
b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
} }
} }
} }
@@ -121,14 +125,18 @@ final class PartitionTests: XCTestCase {
let condition = { $0 < i - 1 } let condition = { $0 < i - 1 }
let p = b.partition(subrange: partitionRange, by: condition) let p = b.partition(subrange: partitionRange, by: condition)
let bdcp = bdc.partition(subrange: partitionRange, by: condition) let bdcp = bdc.partition(subrange: partitionRange, by: condition)
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1) XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) }) XCTAssertEqualSequences(
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition)) b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
XCTAssertUnorderedEqualSequences(
b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
// Must produce the same result as the `BidirectionalCollection` specialized overload. // Must produce the same result as the `BidirectionalCollection` specialized overload.
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], bdc[partitionRange.lowerBound..<bdcp]) XCTAssertEqualSequences(
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], bdc[bdcp..<partitionRange.upperBound]) b[partitionRange.lowerBound..<p], bdc[partitionRange.lowerBound..<bdcp])
XCTAssertUnorderedEqualSequences(
b[p..<partitionRange.upperBound], bdc[bdcp..<partitionRange.upperBound])
} }
} }
} }
@@ -10,15 +10,16 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
final class PermutationsTests: XCTestCase { final class PermutationsTests: XCTestCase {
func testPermutations() { func testPermutations() {
let c = "ABCDE" let c = "ABCDE"
func t(count: Int?) { func t(count: Int?) {
let p = c.permutations(ofCount: count) let p = c.permutations(ofCount: count)
let count = count ?? c.count let count = count ?? c.count
let permCount = c.count.factorial() / (c.count - count).factorial() let permCount = c.count.factorial() / (c.count - count).factorial()
XCTAssertEqual(permCount, p.count) XCTAssertEqual(permCount, p.count)
@@ -26,20 +27,18 @@ final class PermutationsTests: XCTestCase {
XCTAssertTrue(p.allSatisfy { $0.count == count }) XCTAssertTrue(p.allSatisfy { $0.count == count })
XCTAssertTrue(p.isSorted(by: { $0.lexicographicallyPrecedes($1) })) XCTAssertTrue(p.isSorted(by: { $0.lexicographicallyPrecedes($1) }))
} }
func ts<R: RangeExpression>(count: R) where R.Bound == Int { func ts<R: RangeExpression>(count: R) where R.Bound == Int {
let p = count.relative(to: 0 ..< .max) let p = count.relative(to: 0 ..< .max).clamped(to: 0..<c.count + 1).flatMap {
.clamped(to: 0 ..< c.count + 1) c.permutations(ofCount: $0)
.flatMap { }
c.permutations(ofCount: $0)
}
let p2 = c.permutations(ofCount: count) let p2 = c.permutations(ofCount: count)
XCTAssertEqual(p.count, p2.count) XCTAssertEqual(p.count, p2.count)
XCTAssertEqualSequences(p, Array(p2)) XCTAssertEqualSequences(p, Array(p2))
} }
t(count: 0) t(count: 0)
t(count: 1) t(count: 1)
t(count: 2) t(count: 2)
@@ -47,7 +46,7 @@ final class PermutationsTests: XCTestCase {
t(count: 4) t(count: 4)
t(count: 5) t(count: 5)
t(count: nil) t(count: nil)
ts(count: 0...0) ts(count: 0...0)
ts(count: 1...1) ts(count: 1...1)
ts(count: 0...1) ts(count: 0...1)
@@ -60,7 +59,7 @@ final class PermutationsTests: XCTestCase {
ts(count: ...4) ts(count: ...4)
ts(count: ...6) ts(count: ...6)
} }
func testEmpty() { func testEmpty() {
// `k == 0` results in one zero-length permutation // `k == 0` results in one zero-length permutation
XCTAssertEqual(1, "".permutations().count) XCTAssertEqual(1, "".permutations().count)
@@ -70,7 +69,7 @@ final class PermutationsTests: XCTestCase {
XCTAssertEqual(Array("".permutations(ofCount: 0)), [[]]) XCTAssertEqual(Array("".permutations(ofCount: 0)), [[]])
XCTAssertEqual(Array("ABCD".permutations(ofCount: 0)), [[]]) XCTAssertEqual(Array("ABCD".permutations(ofCount: 0)), [[]])
XCTAssertEqual(Array("ABCD".permutations(ofCount: 0...0)), [[]]) XCTAssertEqual(Array("ABCD".permutations(ofCount: 0...0)), [[]])
// `k` greater than element count results in zero permutations // `k` greater than element count results in zero permutations
XCTAssertEqual(0, "".permutations(ofCount: 5).count) XCTAssertEqual(0, "".permutations(ofCount: 5).count)
XCTAssertEqual(Array("".permutations(ofCount: 5)), []) XCTAssertEqual(Array("".permutations(ofCount: 5)), [])
@@ -79,10 +78,10 @@ final class PermutationsTests: XCTestCase {
XCTAssertEqual(Array("ABCD".permutations(ofCount: 5..<7)), []) XCTAssertEqual(Array("ABCD".permutations(ofCount: 5..<7)), [])
XCTAssertEqual(Array("ABCD".permutations(ofCount: 5...)), []) XCTAssertEqual(Array("ABCD".permutations(ofCount: 5...)), [])
} }
func testNextPermutation() { func testNextPermutation() {
var numbers = Array(1...7) var numbers = Array(1...7)
_ = numbers.nextPermutation() _ = numbers.nextPermutation()
XCTAssertEqual([1, 2, 3, 4, 5, 7, 6], numbers) XCTAssertEqual([1, 2, 3, 4, 5, 7, 6], numbers)
_ = numbers.nextPermutation() _ = numbers.nextPermutation()
@@ -95,110 +94,73 @@ final class PermutationsTests: XCTestCase {
XCTAssertEqual([1, 2, 3, 4, 7, 6, 5], numbers) XCTAssertEqual([1, 2, 3, 4, 7, 6, 5], numbers)
_ = numbers.nextPermutation() _ = numbers.nextPermutation()
XCTAssertEqual([1, 2, 3, 5, 4, 6, 7], numbers) XCTAssertEqual([1, 2, 3, 5, 4, 6, 7], numbers)
// Fast-forward to end of permutations. // Fast-forward to end of permutations.
while numbers.nextPermutation() {} while numbers.nextPermutation() {}
XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], numbers) XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], numbers)
} }
func testPermutationsLazy() { func testPermutationsLazy() { XCTAssertLazySequence("ABCD".lazy.permutations(ofCount: 2)) }
XCTAssertLazySequence("ABCD".lazy.permutations(ofCount: 2))
}
func testDocumentationExample1() { func testDocumentationExample1() {
// From Guides/Permutations.md // From Guides/Permutations.md
let numbers = [10, 20, 30] let numbers = [10, 20, 30]
let permutations = numbers.permutations() let permutations = numbers.permutations()
XCTAssertEqualSequences(permutations, [ XCTAssertEqualSequences(
[10, 20, 30], permutations,
[10, 30, 20], [[10, 20, 30], [10, 30, 20], [20, 10, 30], [20, 30, 10], [30, 10, 20], [30, 20, 10]])
[20, 10, 30],
[20, 30, 10],
[30, 10, 20],
[30, 20, 10],
])
} }
func testDocumentationExample2() { func testDocumentationExample2() {
// From Guides/Permutations.md // From Guides/Permutations.md
let numbers = [10, 20, 30] let numbers = [10, 20, 30]
let permutations = numbers.permutations(ofCount: 2) let permutations = numbers.permutations(ofCount: 2)
XCTAssertEqualSequences(permutations, [ XCTAssertEqualSequences(
[10, 20], permutations, [[10, 20], [10, 30], [20, 10], [20, 30], [30, 10], [30, 20]])
[10, 30],
[20, 10],
[20, 30],
[30, 10],
[30, 20],
])
} }
func testDocumentationExample3() { func testDocumentationExample3() {
// From Guides/Permutations.md // From Guides/Permutations.md
let numbers2 = [20, 10, 10] let numbers2 = [20, 10, 10]
let permutations = numbers2.permutations() let permutations = numbers2.permutations()
XCTAssertEqualSequences(permutations, [ XCTAssertEqualSequences(
[20, 10, 10], permutations,
[20, 10, 10], [[20, 10, 10], [20, 10, 10], [10, 20, 10], [10, 10, 20], [10, 20, 10], [10, 10, 20]])
[10, 20, 10],
[10, 10, 20],
[10, 20, 10],
[10, 10, 20],
])
} }
func testDocumentationExample4() { func testDocumentationExample4() {
// From Guides/Permutations.md // From Guides/Permutations.md
let numbers = [10, 20, 30] let numbers = [10, 20, 30]
let permutations = numbers.permutations(ofCount: 0...) let permutations = numbers.permutations(ofCount: 0...)
XCTAssertEqualSequences(permutations, [ XCTAssertEqualSequences(
[], permutations,
[10], [
[20], [], [10], [20], [30], [10, 20], [10, 30], [20, 10], [20, 30], [30, 10], [30, 20],
[30], [10, 20, 30], [10, 30, 20], [20, 10, 30], [20, 30, 10], [30, 10, 20], [30, 20, 10],
[10, 20], ])
[10, 30],
[20, 10],
[20, 30],
[30, 10],
[30, 20],
[10, 20, 30],
[10, 30, 20],
[20, 10, 30],
[20, 30, 10],
[30, 10, 20],
[30, 20, 10],
])
} }
func testDocumentationExample5() { func testDocumentationExample5() {
// From Permutations.swift // From Permutations.swift
let names = ["Alex", "Celeste", "Davide"] let names = ["Alex", "Celeste", "Davide"]
let permutations = names.permutations(ofCount: 2) let permutations = names.permutations(ofCount: 2)
XCTAssertEqualSequences(permutations, [ XCTAssertEqualSequences(
["Alex", "Celeste"], permutations,
["Alex", "Davide"], [
["Celeste", "Alex"], ["Alex", "Celeste"], ["Alex", "Davide"], ["Celeste", "Alex"], ["Celeste", "Davide"],
["Celeste", "Davide"], ["Davide", "Alex"], ["Davide", "Celeste"],
["Davide", "Alex"], ])
["Davide", "Celeste"],
])
} }
func testDocumentationExample6() { func testDocumentationExample6() {
// From Permutations.swift // From Permutations.swift
let names = ["Alex", "Celeste", "Davide"] let names = ["Alex", "Celeste", "Davide"]
let permutations = names.permutations(ofCount: 1...2) let permutations = names.permutations(ofCount: 1...2)
XCTAssertEqualSequences(permutations, [ XCTAssertEqualSequences(
["Alex"], permutations,
["Celeste"], [
["Davide"], ["Alex"], ["Celeste"], ["Davide"], ["Alex", "Celeste"], ["Alex", "Davide"],
["Alex", "Celeste"], ["Celeste", "Alex"], ["Celeste", "Davide"], ["Davide", "Alex"], ["Davide", "Celeste"],
["Alex", "Davide"], ])
["Celeste", "Alex"],
["Celeste", "Davide"],
["Davide", "Alex"],
["Davide", "Celeste"],
])
} }
} }
+9 -16
View File
@@ -10,45 +10,38 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
final class ProductTests: XCTestCase { final class ProductTests: XCTestCase {
func testProduct() { func testProduct() {
XCTAssertEqualSequences( XCTAssertEqualSequences(
[(1, "A" as Character), (1, "B"), (2, "A"), (2, "B")], [(1, "A" as Character), (1, "B"), (2, "A"), (2, "B")], product(1...2, "AB"), by: ==)
product(1...2, "AB"),
by: ==)
XCTAssertEqualSequences(product(1...10, ""), [], by: ==) XCTAssertEqualSequences(product(1...10, ""), [], by: ==)
XCTAssertEqualSequences(product("", 1...10), [], by: ==) XCTAssertEqualSequences(product("", 1...10), [], by: ==)
} }
func testProductReversed() { func testProductReversed() {
XCTAssertEqualSequences( XCTAssertEqualSequences(
[(2, "B" as Character), (2, "A"), (1, "B"), (1, "A")], [(2, "B" as Character), (2, "A"), (1, "B"), (1, "A")], product(1...2, "AB").reversed(), by: ==
product(1...2, "AB").reversed(), )
by: ==)
XCTAssertEqualSequences(product(1...10, "").reversed(), [], by: ==) XCTAssertEqualSequences(product(1...10, "").reversed(), [], by: ==)
XCTAssertEqualSequences(product("", 1...10).reversed(), [], by: ==) XCTAssertEqualSequences(product("", 1...10).reversed(), [], by: ==)
} }
func testProductDistanceFromTo() { func testProductDistanceFromTo() {
let p = product([1, 2], "abc") let p = product([1, 2], "abc")
XCTAssertEqual(p.distance(from: p.startIndex, to: p.endIndex), 6) XCTAssertEqual(p.distance(from: p.startIndex, to: p.endIndex), 6)
} }
func testProductIndexTraversals() { func testProductIndexTraversals() {
validateIndexTraversals( validateIndexTraversals(
product([1, 2, 3, 4], "abc"), product([1, 2, 3, 4], "abc"), product([1, 2, 3, 4], ""), product([], "abc"), product([], ""),
product([1, 2, 3, 4], ""),
product([], "abc"),
product([], ""),
indices: { product in indices: { product in
product.base1.indices.flatMap { i1 in product.base1.indices.flatMap { i1 in
product.base2.indices.map { i2 in product.base2.indices.map { i2 in .init(i1: i1, i2: i2) }
.init(i1: i1, i2: i2)
}
} + [.init(i1: product.base1.endIndex, i2: product.base2.startIndex)] } + [.init(i1: product.base1.endIndex, i2: product.base2.startIndex)]
}) })
} }
@@ -10,20 +10,16 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
func validateRandomSamples<S: Sequence>( func validateRandomSamples<S: Sequence>(
_ samples: [Int: Int], _ samples: [Int: Int], elements: S, expectedValue: Int, file: StaticString = #file,
elements: S, line: UInt = #line
expectedValue: Int,
file: StaticString = #file, line: UInt = #line
) where S.Element == Int { ) where S.Element == Int {
let expectedRange = ((expectedValue / 3) * 2) ... ((expectedValue / 3) * 4) let expectedRange = ((expectedValue / 3) * 2)...((expectedValue / 3) * 4)
XCTAssertEqualSequences(samples.keys.sorted(), elements, XCTAssertEqualSequences(samples.keys.sorted(), elements, file: file, line: line)
file: file, line: line) for v in samples.values { XCTAssert(expectedRange.contains(v), file: file, line: line) }
for v in samples.values {
XCTAssert(expectedRange.contains(v), file: file, line: line)
}
} }
private let n = 100 private let n = 100
@@ -37,31 +33,25 @@ final class RandomSampleTests: XCTestCase {
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
let sample = c.randomStableSample(count: k) let sample = c.randomStableSample(count: k)
XCTAssert(sample.isSorted()) XCTAssert(sample.isSorted())
for x in sample { for x in sample { result[x, default: 0] += 1 }
result[x, default: 0] += 1
}
} }
validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n) validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
} }
func testRandomSampleCollection() { func testRandomSampleCollection() {
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
for x in c.randomSample(count: k) { for x in c.randomSample(count: k) { result[x, default: 0] += 1 }
result[x, default: 0] += 1
}
} }
validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n) validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
} }
func testRandomSampleSequence() { func testRandomSampleSequence() {
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
for x in s.randomSample(count: k) { for x in s.randomSample(count: k) { result[x, default: 0] += 1 }
result[x, default: 0] += 1
}
} }
validateRandomSamples(samples, elements: s, expectedValue: (k * iterations) / n) validateRandomSamples(samples, elements: s, expectedValue: (k * iterations) / n)
} }
func testRandomSampleEdgeCases() { func testRandomSampleEdgeCases() {
XCTAssert(c.randomStableSample(count: 0).isEmpty) XCTAssert(c.randomStableSample(count: 0).isEmpty)
XCTAssertEqualSequences(c.randomStableSample(count: n), c) XCTAssertEqualSequences(c.randomStableSample(count: n), c)
@@ -70,12 +60,12 @@ final class RandomSampleTests: XCTestCase {
XCTAssert(c.randomSample(count: 0).isEmpty) XCTAssert(c.randomSample(count: 0).isEmpty)
XCTAssertEqualSequences(c.randomSample(count: n).sorted(), c) XCTAssertEqualSequences(c.randomSample(count: n).sorted(), c)
XCTAssertEqualSequences(c.randomSample(count: n * 2).sorted(), c) XCTAssertEqualSequences(c.randomSample(count: n * 2).sorted(), c)
XCTAssert(s.randomSample(count: 0).isEmpty) XCTAssert(s.randomSample(count: 0).isEmpty)
XCTAssertEqualSequences(s.randomSample(count: n).sorted(), c) XCTAssertEqualSequences(s.randomSample(count: n).sorted(), c)
XCTAssertEqualSequences(s.randomSample(count: n * 2).sorted(), c) XCTAssertEqualSequences(s.randomSample(count: n * 2).sorted(), c)
} }
func testRandomSampleRepeatable() { func testRandomSampleRepeatable() {
var generator = SplitMix64(seed: 0) var generator = SplitMix64(seed: 0)
let sample1a = c.randomSample(count: k, using: &generator) let sample1a = c.randomSample(count: k, using: &generator)
@@ -88,7 +78,7 @@ final class RandomSampleTests: XCTestCase {
generator = SplitMix64(seed: 0) generator = SplitMix64(seed: 0)
let sample2b = s.randomSample(count: k, using: &generator) let sample2b = s.randomSample(count: k, using: &generator)
XCTAssertEqual(sample1b, sample2b) XCTAssertEqual(sample1b, sample2b)
generator = SplitMix64(seed: 0) generator = SplitMix64(seed: 0)
let sample1c = c.randomStableSample(count: k, using: &generator) let sample1c = c.randomStableSample(count: k, using: &generator)
generator = SplitMix64(seed: 0) generator = SplitMix64(seed: 0)
@@ -97,19 +87,15 @@ final class RandomSampleTests: XCTestCase {
} }
func testRandomSampleRandomEdgeCasesInternal() { func testRandomSampleRandomEdgeCasesInternal() {
struct ZeroGenerator: RandomNumberGenerator { struct ZeroGenerator: RandomNumberGenerator { mutating func next() -> UInt64 { 0 } }
mutating func next() -> UInt64 { 0 }
}
var zero = ZeroGenerator() var zero = ZeroGenerator()
_ = nextOffset(w: 1, using: &zero) // must not crash _ = nextOffset(w: 1, using: &zero) // must not crash
struct AlmostAllZeroGenerator: RandomNumberGenerator { struct AlmostAllZeroGenerator: RandomNumberGenerator {
private var forward: SplitMix64 private var forward: SplitMix64
private var count: Int = 0 private var count: Int = 0
init(seed: UInt64) { init(seed: UInt64) { forward = SplitMix64(seed: seed) }
forward = SplitMix64(seed: seed)
}
mutating func next() -> UInt64 { mutating func next() -> UInt64 {
defer { count &+= 1 } defer { count &+= 1 }
@@ -119,8 +105,8 @@ final class RandomSampleTests: XCTestCase {
} }
var almostAllZero = AlmostAllZeroGenerator(seed: 0) var almostAllZero = AlmostAllZeroGenerator(seed: 0)
_ = s.randomSample(count: k, using: &almostAllZero) // must not crash _ = s.randomSample(count: k, using: &almostAllZero) // must not crash
almostAllZero = AlmostAllZeroGenerator(seed: 0) almostAllZero = AlmostAllZeroGenerator(seed: 0)
_ = c.randomSample(count: k, using: &almostAllZero) // must not crash _ = c.randomSample(count: k, using: &almostAllZero) // must not crash
} }
} }
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest
import Algorithms import Algorithms
import XCTest
final class ReductionsTests: XCTestCase { final class ReductionsTests: XCTestCase {
+10 -8
View File
@@ -10,6 +10,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
final class RotateTests: XCTestCase { final class RotateTests: XCTestCase {
@@ -17,20 +18,21 @@ final class RotateTests: XCTestCase {
func testUnderscoreReverse() { func testUnderscoreReverse() {
var input = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"] var input = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]
let limit: Int = 4 let limit: Int = 4
let (lower, upper) = input._reverse(subrange: input.startIndex..<input.endIndex, until: input.startIndex.advanced(by: limit)) let (lower, upper) = input._reverse(
subrange: input.startIndex..<input.endIndex, until: input.startIndex.advanced(by: limit))
let expected = ["p", "o", "n", "m", "e", "f", "g", "h", "i", "j", "k", "l", "d", "c", "b", "a"] let expected = ["p", "o", "n", "m", "e", "f", "g", "h", "i", "j", "k", "l", "d", "c", "b", "a"]
XCTAssertEqual(input, expected) XCTAssertEqual(input, expected)
XCTAssertEqual(lower, input.startIndex.advanced(by: limit)) XCTAssertEqual(lower, input.startIndex.advanced(by: limit))
XCTAssertEqual(upper, input.endIndex.advanced(by: -limit)) XCTAssertEqual(upper, input.endIndex.advanced(by: -limit))
} }
/// Tests the example given in `reverse(subrange:)`’s documentation /// Tests the example given in `reverse(subrange:)`’s documentation
func testReverse() { func testReverse() {
var numbers = [10, 20, 30, 40, 50, 60, 70, 80] var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
numbers.reverse(subrange: 0..<4) numbers.reverse(subrange: 0..<4)
XCTAssertEqual(numbers, [40, 30, 20, 10, 50, 60, 70, 80]) XCTAssertEqual(numbers, [40, 30, 20, 10, 50, 60, 70, 80])
} }
/// Tests `rotate(subrange:toStartAt:)` with an empty subrange /// Tests `rotate(subrange:toStartAt:)` with an empty subrange
/// The order of elements are unchanged /// The order of elements are unchanged
func testRotateEmptySubrange() { func testRotateEmptySubrange() {
@@ -39,7 +41,7 @@ final class RotateTests: XCTestCase {
XCTAssertEqual(numbers, [10, 20, 30, 40, 50, 60, 70, 80]) XCTAssertEqual(numbers, [10, 20, 30, 40, 50, 60, 70, 80])
XCTAssertEqual(numbers[oldStart], 40) XCTAssertEqual(numbers[oldStart], 40)
} }
/// Tests `rotate(subrange:toStartAt:)` with an empty collection /// Tests `rotate(subrange:toStartAt:)` with an empty collection
func testRotateSubrangeOnEmptyCollection() { func testRotateSubrangeOnEmptyCollection() {
var numbers = [Int]() var numbers = [Int]()
@@ -47,7 +49,7 @@ final class RotateTests: XCTestCase {
XCTAssertEqual(numbers, []) XCTAssertEqual(numbers, [])
XCTAssertEqual(oldStart, numbers.startIndex) XCTAssertEqual(oldStart, numbers.startIndex)
} }
/// Tests `rotate(subrange:toStartAt:)` with the full range of the collection /// Tests `rotate(subrange:toStartAt:)` with the full range of the collection
func testRotateFullRange() { func testRotateFullRange() {
var numbers = [10, 20, 30, 40, 50, 60, 70, 80] var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
@@ -55,7 +57,7 @@ final class RotateTests: XCTestCase {
XCTAssertEqual(numbers, [20, 30, 40, 50, 60, 70, 80, 10]) XCTAssertEqual(numbers, [20, 30, 40, 50, 60, 70, 80, 10])
XCTAssertEqual(numbers[oldStart], 10) XCTAssertEqual(numbers[oldStart], 10)
} }
/// Tests the example given in `rotate(subrange:toStartAt:)`’s documentation /// Tests the example given in `rotate(subrange:toStartAt:)`’s documentation
func testRotateSubrange() { func testRotateSubrange() {
var numbers = [10, 20, 30, 40, 50, 60, 70, 80] var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
@@ -63,7 +65,7 @@ final class RotateTests: XCTestCase {
XCTAssertEqual(numbers, [30, 40, 10, 20, 50, 60, 70, 80]) XCTAssertEqual(numbers, [30, 40, 10, 20, 50, 60, 70, 80])
XCTAssertEqual(numbers[oldStart], 10) XCTAssertEqual(numbers[oldStart], 10)
} }
/// Tests the example given in `rotate(toStartAt:)`’s documentation /// Tests the example given in `rotate(toStartAt:)`’s documentation
func testRotateExample() { func testRotateExample() {
var numbers = [10, 20, 30, 40, 50, 60, 70, 80] var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
@@ -71,7 +73,7 @@ final class RotateTests: XCTestCase {
XCTAssertEqual(numbers, [40, 50, 60, 70, 80, 10, 20, 30]) XCTAssertEqual(numbers, [40, 50, 60, 70, 80, 10, 20, 30])
XCTAssertEqual(numbers[oldStart], 10) XCTAssertEqual(numbers[oldStart], 10)
} }
/// Tests `rotate(toStartAt:)` on collections of varying lengths, at different /// Tests `rotate(toStartAt:)` on collections of varying lengths, at different
/// starting points /// starting points
func testRotate() { func testRotate() {
+28 -42
View File
@@ -9,11 +9,11 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest
import Algorithms import Algorithms
import XCTest
final class StridingTests: XCTestCase { final class StridingTests: XCTestCase {
func testStride() { func testStride() {
let a = 0...10 let a = 0...10
XCTAssertEqualSequences(a.striding(by: 1), (0...10)) XCTAssertEqualSequences(a.striding(by: 1), (0...10))
@@ -23,7 +23,7 @@ final class StridingTests: XCTestCase {
XCTAssertEqualSequences(a.striding(by: 5), [0, 5, 10]) XCTAssertEqualSequences(a.striding(by: 5), [0, 5, 10])
XCTAssertEqualSequences(a.striding(by: 10), [0, 10]) XCTAssertEqualSequences(a.striding(by: 10), [0, 10])
XCTAssertEqualSequences(a.striding(by: 11), [0]) XCTAssertEqualSequences(a.striding(by: 11), [0])
let s = (0...).prefix(11) let s = (0...).prefix(11)
XCTAssertEqualSequences(s.striding(by: 1), (0...10)) XCTAssertEqualSequences(s.striding(by: 1), (0...10))
XCTAssertEqualSequences(s.striding(by: 2), [0, 2, 4, 6, 8, 10]) XCTAssertEqualSequences(s.striding(by: 2), [0, 2, 4, 6, 8, 10])
@@ -32,22 +32,22 @@ final class StridingTests: XCTestCase {
XCTAssertEqualSequences(s.striding(by: 5), [0, 5, 10]) XCTAssertEqualSequences(s.striding(by: 5), [0, 5, 10])
XCTAssertEqualSequences(s.striding(by: 10), [0, 10]) XCTAssertEqualSequences(s.striding(by: 10), [0, 10])
XCTAssertEqualSequences(s.striding(by: 11), [0]) XCTAssertEqualSequences(s.striding(by: 11), [0])
let empty = (0...).prefix(0) let empty = (0...).prefix(0)
XCTAssertEqualSequences(empty.striding(by: 2), []) XCTAssertEqualSequences(empty.striding(by: 2), [])
} }
func testStrideString() { func testStrideString() {
let s = "swift" let s = "swift"
XCTAssertEqualSequences(s.striding(by: 2), ["s", "i", "t"]) XCTAssertEqualSequences(s.striding(by: 2), ["s", "i", "t"])
} }
func testStrideReversed() { func testStrideReversed() {
let a = [0, 1, 2, 3, 4, 5] let a = [0, 1, 2, 3, 4, 5]
XCTAssertEqualSequences(a.striding(by: 3).reversed(), [3, 0]) XCTAssertEqualSequences(a.striding(by: 3).reversed(), [3, 0])
XCTAssertEqualSequences(a.reversed().striding(by: 2), [5, 3, 1]) XCTAssertEqualSequences(a.reversed().striding(by: 2), [5, 3, 1])
} }
func testStrideIndexes() { func testStrideIndexes() {
let a = [0, 1, 2, 3, 4, 5].striding(by: 2) let a = [0, 1, 2, 3, 4, 5].striding(by: 2)
var i = a.startIndex var i = a.startIndex
@@ -60,20 +60,20 @@ final class StridingTests: XCTestCase {
XCTAssertEqual(a[i], 2) XCTAssertEqual(a[i], 2)
a.formIndex(before: &i) a.formIndex(before: &i)
XCTAssertEqual(a[i], 0) XCTAssertEqual(a[i], 0)
// a.formIndex(before: &i) // Precondition failed: Incrementing past start index // a.formIndex(before: &i) // Precondition failed: Incrementing past start index
// a.index(after: a.endIndex) // Precondition failed: Advancing past end index // a.index(after: a.endIndex) // Precondition failed: Advancing past end index
} }
func testStrideLast() { func testStrideLast() {
XCTAssertEqual((1...10).striding(by: 2).last, 9) // 1, 3, 5, 7, 9 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: 3).last, 10) // 1, 4, 7, 10
XCTAssertEqual((1...10).striding(by: 4).last, 9) // 1, 5, 9 XCTAssertEqual((1...10).striding(by: 4).last, 9) // 1, 5, 9
XCTAssertEqual((1...10).striding(by: 5).last, 6) // 1, 6 XCTAssertEqual((1...10).striding(by: 5).last, 6) // 1, 6
XCTAssertEqual((1...100).striding(by: 50).last, 51) // 1, 51 XCTAssertEqual((1...100).striding(by: 50).last, 51) // 1, 51
XCTAssertEqual((1...5).striding(by: 2).last, 5) // 1, 3, 5 XCTAssertEqual((1...5).striding(by: 2).last, 5) // 1, 3, 5
XCTAssertEqual([Int]().striding(by: 2).last, nil) // empty XCTAssertEqual([Int]().striding(by: 2).last, nil) // empty
} }
func testCount() { func testCount() {
let empty = [Int]().striding(by: 2) let empty = [Int]().striding(by: 2)
XCTAssertEqual(empty.count, 0) XCTAssertEqual(empty.count, 0)
@@ -86,45 +86,31 @@ final class StridingTests: XCTestCase {
XCTAssertEqual(a.striding(by: 10).count, [0, 10].count) XCTAssertEqual(a.striding(by: 10).count, [0, 10].count)
XCTAssertEqual(a.striding(by: 11).count, [0].count) XCTAssertEqual(a.striding(by: 11).count, [0].count)
} }
func testIndexTraversals() { func testIndexTraversals() {
let empty = [Int]() let empty = [Int]()
validateIndexTraversals( validateIndexTraversals(empty.striding(by: 1), empty.striding(by: 2))
empty.striding(by: 1),
empty.striding(by: 2)
)
let zero_to_one_hundered_range = 0...100 let zero_to_one_hundered_range = 0...100
validateIndexTraversals( validateIndexTraversals(
zero_to_one_hundered_range.striding(by: 10), zero_to_one_hundered_range.striding(by: 10), zero_to_one_hundered_range.striding(by: 11),
zero_to_one_hundered_range.striding(by: 11), zero_to_one_hundered_range.striding(by: 101))
zero_to_one_hundered_range.striding(by: 101)
)
let zero_to_one_hundered_array = Array(zero_to_one_hundered_range) let zero_to_one_hundered_array = Array(zero_to_one_hundered_range)
validateIndexTraversals( validateIndexTraversals(
zero_to_one_hundered_array.striding(by: 10), zero_to_one_hundered_array.striding(by: 10), zero_to_one_hundered_array.striding(by: 11),
zero_to_one_hundered_array.striding(by: 11), zero_to_one_hundered_array.striding(by: 101))
zero_to_one_hundered_array.striding(by: 101)
)
let string = "swift rocks".map(String.init) let string = "swift rocks".map(String.init)
validateIndexTraversals( validateIndexTraversals(string.striding(by: 1), string.striding(by: 2), string.striding(by: 10))
string.striding(by: 1),
string.striding(by: 2),
string.striding(by: 10)
)
} }
func testOffsetBy() { func testOffsetBy() {
let a = (0...100).striding(by: 22) let a = (0...100).striding(by: 22)
let b = [0, 22, 44, 66, 88] let b = [0, 22, 44, 66, 88]
for i in 0..<a.count { for i in 0..<a.count { XCTAssertEqual(a[a.index(a.startIndex, offsetBy: i)], b[i]) }
XCTAssertEqual(a[a.index(a.startIndex, offsetBy: i)], b[i])
}
} }
func testOffsetByEndIndex() { func testOffsetByEndIndex() {
let a = 1...5 let a = 1...5
let b = a.striding(by: 3) // [1, 4] let b = a.striding(by: 3) // [1, 4]
let i = b.index(b.startIndex, offsetBy: 2) let i = b.index(b.startIndex, offsetBy: 2)
XCTAssertEqual(i, b.endIndex) XCTAssertEqual(i, b.endIndex)
} }
+6 -5
View File
@@ -10,6 +10,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
final class SuffixTests: XCTestCase { final class SuffixTests: XCTestCase {
@@ -19,29 +20,29 @@ final class SuffixTests: XCTestCase {
XCTAssertEqualSequences(a.suffix(while: { $0 > 10 }), []) XCTAssertEqualSequences(a.suffix(while: { $0 > 10 }), [])
XCTAssertEqualSequences(a.suffix(while: { $0 > 9 }), [10]) XCTAssertEqualSequences(a.suffix(while: { $0 > 9 }), [10])
XCTAssertEqualSequences(a.suffix(while: { $0 > -1 }), (0...10)) XCTAssertEqualSequences(a.suffix(while: { $0 > -1 }), (0...10))
let empty: [Int] = [] let empty: [Int] = []
XCTAssertEqualSequences(empty.suffix(while: { $0 > 10 }), []) XCTAssertEqualSequences(empty.suffix(while: { $0 > 10 }), [])
} }
func testEndOfPrefix() { func testEndOfPrefix() {
let array = Array(0..<10) let array = Array(0..<10)
XCTAssertEqual(array.endOfPrefix(while: { $0 < 3 }), 3) XCTAssertEqual(array.endOfPrefix(while: { $0 < 3 }), 3)
XCTAssertEqual(array.endOfPrefix(while: { _ in false }), array.startIndex) XCTAssertEqual(array.endOfPrefix(while: { _ in false }), array.startIndex)
XCTAssertEqual(array.endOfPrefix(while: { _ in true }), array.endIndex) XCTAssertEqual(array.endOfPrefix(while: { _ in true }), array.endIndex)
let empty = [Int]() let empty = [Int]()
XCTAssertEqual(empty.endOfPrefix(while: { $0 < 3 }), 0) XCTAssertEqual(empty.endOfPrefix(while: { $0 < 3 }), 0)
XCTAssertEqual(empty.endOfPrefix(while: { _ in false }), empty.startIndex) XCTAssertEqual(empty.endOfPrefix(while: { _ in false }), empty.startIndex)
XCTAssertEqual(empty.endOfPrefix(while: { _ in true }), empty.endIndex) XCTAssertEqual(empty.endOfPrefix(while: { _ in true }), empty.endIndex)
} }
func testStartOfSuffix() { func testStartOfSuffix() {
let array = Array(0..<10) let array = Array(0..<10)
XCTAssertEqual(array.startOfSuffix(while: { $0 >= 3 }), 3) XCTAssertEqual(array.startOfSuffix(while: { $0 >= 3 }), 3)
XCTAssertEqual(array.startOfSuffix(while: { _ in false }), array.endIndex) XCTAssertEqual(array.startOfSuffix(while: { _ in false }), array.endIndex)
XCTAssertEqual(array.startOfSuffix(while: { _ in true }), array.startIndex) XCTAssertEqual(array.startOfSuffix(while: { _ in true }), array.startIndex)
let empty = [Int]() let empty = [Int]()
XCTAssertEqual(empty.startOfSuffix(while: { $0 < 3 }), 0) XCTAssertEqual(empty.startOfSuffix(while: { $0 < 3 }), 0)
XCTAssertEqual(empty.startOfSuffix(while: { _ in false }), empty.endIndex) XCTAssertEqual(empty.startOfSuffix(while: { _ in false }), empty.endIndex)
+62 -104
View File
@@ -17,11 +17,7 @@ extension Sequence {
} }
} }
extension Sequence where Element: Comparable { extension Sequence where Element: Comparable { func isSorted() -> Bool { isSorted(by: <) } }
func isSorted() -> Bool {
isSorted(by: <)
}
}
extension Numeric { extension Numeric {
func factorial() -> Self { func factorial() -> Self {
@@ -32,35 +28,29 @@ extension Numeric {
struct SplitMix64: RandomNumberGenerator { struct SplitMix64: RandomNumberGenerator {
private var state: UInt64 private var state: UInt64
init(seed: UInt64) { init(seed: UInt64) { self.state = seed }
self.state = seed
}
mutating func next() -> UInt64 { mutating func next() -> UInt64 {
self.state &+= 0x9e3779b97f4a7c15 self.state &+= 0x9e37_79b9_7f4a_7c15
var z: UInt64 = self.state var z: UInt64 = self.state
z = (z ^ (z &>> 30)) &* 0xbf58476d1ce4e5b9 z = (z ^ (z &>> 30)) &* 0xbf58_476d_1ce4_e5b9
z = (z ^ (z &>> 27)) &* 0x94d049bb133111eb z = (z ^ (z &>> 27)) &* 0x94d0_49bb_1331_11eb
return z ^ (z &>> 31) return z ^ (z &>> 31)
} }
} }
// An eraser helper to any mutable collection // An eraser helper to any mutable collection
struct AnyMutableCollection<Base> where Base: MutableCollection { struct AnyMutableCollection<Base> where Base: MutableCollection { var base: Base }
var base: Base
}
extension AnyMutableCollection: MutableCollection { extension AnyMutableCollection: MutableCollection {
typealias Index = Base.Index typealias Index = Base.Index
typealias Element = Base.Element typealias Element = Base.Element
var startIndex: Base.Index { base.startIndex } var startIndex: Base.Index { base.startIndex }
var endIndex: Base.Index { base.endIndex } var endIndex: Base.Index { base.endIndex }
func index(after i: Index) -> Index { func index(after i: Index) -> Index { return base.index(after: i) }
return base.index(after: i)
}
subscript(position: Base.Index) -> Base.Element { subscript(position: Base.Index) -> Base.Element {
_read { yield base[position] } _read { yield base[position] }
@@ -75,19 +65,16 @@ extension MutableCollection {
} }
func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>( func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1, _ expression1: @autoclosure () throws -> S1, _ expression2: @autoclosure () throws -> S2,
_ expression2: @autoclosure () throws -> S2, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
) rethrows where S1.Element: Equatable, S1.Element == S2.Element { ) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
try XCTAssertEqualSequences(expression1(), expression2(), by: ==, try XCTAssertEqualSequences(
message(), file: file, line: line) expression1(), expression2(), by: ==, message(), file: file, line: line)
} }
// Two sequences contains exactly the same element but not necessarily in the same order. // Two sequences contains exactly the same element but not necessarily in the same order.
func XCTAssertUnorderedEqualSequences<S1: Sequence, S2: Sequence>( func XCTAssertUnorderedEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1, _ expression1: @autoclosure () throws -> S1, _ expression2: @autoclosure () throws -> S2,
_ expression2: @autoclosure () throws -> S2,
file: StaticString = #file, line: UInt = #line file: StaticString = #file, line: UInt = #line
) rethrows where S1.Element: Equatable, S1.Element == S2.Element { ) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
var s1 = Array(try expression1()) var s1 = Array(try expression1())
@@ -99,30 +86,25 @@ func XCTAssertUnorderedEqualSequences<S1: Sequence, S2: Sequence>(
} }
s1.remove(at: idx) s1.remove(at: idx)
} }
XCTAssertTrue(
missing.isEmpty, "first sequence missing '\(missing)' elements from second sequence",
file: file, line: line
)
XCTAssertTrue( XCTAssertTrue(
s1.isEmpty, "first sequence contains \(s1) missing from second sequence", missing.isEmpty, "first sequence missing '\(missing)' elements from second sequence",
file: file, line: line file: file, line: line)
XCTAssertTrue(
s1.isEmpty, "first sequence contains \(s1) missing from second sequence", file: file, line: line
) )
} }
func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>( func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1, _ expression1: @autoclosure () throws -> S1, _ expression2: @autoclosure () throws -> S2,
_ expression2: @autoclosure () throws -> S2, by areEquivalent: (S1.Element, S1.Element) -> Bool, _ message: @autoclosure () -> String = "",
by areEquivalent: (S1.Element, S1.Element) -> Bool,
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line file: StaticString = #file, line: UInt = #line
) rethrows where S1.Element == S2.Element { ) rethrows where S1.Element == S2.Element {
func fail(_ reason: String) { func fail(_ reason: String) {
let message = message() let message = message()
XCTFail(message.isEmpty ? reason : "\(message) - \(reason)", XCTFail(message.isEmpty ? reason : "\(message) - \(reason)", file: file, line: line)
file: file, line: line)
} }
var iter1 = try expression1().makeIterator() var iter1 = try expression1().makeIterator()
@@ -134,11 +116,11 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
idx += 1 idx += 1
continue continue
case let (e1?, e2?): case let (e1?, e2?):
fail("element \(e1) on first sequence does not match element \(e2) on second sequence at position \(idx)") fail(
case (_?, nil): "element \(e1) on first sequence does not match element \(e2) on second sequence at position \(idx)"
fail("second sequence shorter than first") )
case (nil, _?): case (_?, nil): fail("second sequence shorter than first")
fail("first sequence shorter than second") case (nil, _?): fail("first sequence shorter than second")
case (nil, nil): break case (nil, nil): break
} }
return return
@@ -150,10 +132,8 @@ func XCTAssertLazyCollection<S: LazyCollectionProtocol>(_: S) {}
/// Asserts two collections are equal by using their indices to access elements. /// Asserts two collections are equal by using their indices to access elements.
func XCTAssertEqualCollections<C1: Collection, C2: Collection>( func XCTAssertEqualCollections<C1: Collection, C2: Collection>(
_ expression1: @autoclosure () throws -> C1, _ expression1: @autoclosure () throws -> C1, _ expression2: @autoclosure () throws -> C2,
_ expression2: @autoclosure () throws -> C2, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
) rethrows where C1.Element: Equatable, C1.Element == C2.Element { ) rethrows where C1.Element: Equatable, C1.Element == C2.Element {
let c1 = try expression1() let c1 = try expression1()
let c2 = try expression2() let c2 = try expression2()
@@ -183,35 +163,26 @@ func XCTAssertEqualCollections<C1: Collection, C2: Collection>(
/// - Complexity: O(*n*^3) for each collection, where *n* is the length of the /// - Complexity: O(*n*^3) for each collection, where *n* is the length of the
/// collection. /// collection.
func validateIndexTraversals<C>( func validateIndexTraversals<C>(
_ collections: C..., _ collections: C..., indices: ((C) -> [C.Index])? = nil, file: StaticString = #file,
indices: ((C) -> [C.Index])? = nil, line: UInt = #line
file: StaticString = #file, line: UInt = #line
) where C: BidirectionalCollection { ) where C: BidirectionalCollection {
for c in collections { for c in collections {
let indicesIncludingEnd = indices?(c) ?? (c.indices + [c.endIndex]) let indicesIncludingEnd = indices?(c) ?? (c.indices + [c.endIndex])
let count = indicesIncludingEnd.count - 1 let count = indicesIncludingEnd.count - 1
XCTAssertEqual(c.count, count, "Count mismatch", file: file, line: line)
XCTAssertEqual(c.isEmpty, count == 0, "Emptiness mismatch", file: file, line: line)
XCTAssertEqual( XCTAssertEqual(
c.count, count, c.startIndex, indicesIncludingEnd.first, "`startIndex` does not equal the first index",
"Count mismatch",
file: file, line: line) file: file, line: line)
XCTAssertEqual( XCTAssertEqual(
c.isEmpty, count == 0, c.endIndex, indicesIncludingEnd.last, "`endIndex` does not equal the last index", file: file,
"Emptiness mismatch", line: line)
file: file, line: line)
XCTAssertEqual(
c.startIndex, indicesIncludingEnd.first,
"`startIndex` does not equal the first index",
file: file, line: line)
XCTAssertEqual(
c.endIndex, indicesIncludingEnd.last,
"`endIndex` does not equal the last index",
file: file, line: line)
// `index(after:)` // `index(after:)`
do { do {
var index = c.startIndex var index = c.startIndex
for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() { for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() {
c.formIndex(after: &index) c.formIndex(after: &index)
XCTAssertEqual( XCTAssertEqual(
@@ -219,11 +190,10 @@ func validateIndexTraversals<C>(
""" """
`startIndex` incremented \(offset) times does not equal index at \ `startIndex` incremented \(offset) times does not equal index at \
offset \(offset) offset \(offset)
""", """, file: file, line: line)
file: file, line: line)
} }
} }
// `index(before:)` // `index(before:)`
do { do {
var index = c.endIndex var index = c.endIndex
@@ -235,67 +205,57 @@ func validateIndexTraversals<C>(
""" """
`endIndex` decremented \(count - offset) times does not equal index \ `endIndex` decremented \(count - offset) times does not equal index \
at offset \(offset) at offset \(offset)
""", """, file: file, line: line)
file: file, line: line)
} }
} }
// `indices` // `indices`
XCTAssertEqual(c.indices.count, count) XCTAssertEqual(c.indices.count, count)
for (offset, index) in c.indices.enumerated() { for (offset, index) in c.indices.enumerated() {
XCTAssertEqual( XCTAssertEqual(
index, indicesIncludingEnd[offset], index, indicesIncludingEnd[offset], "Index mismatch at offset \(offset) in `indices`",
"Index mismatch at offset \(offset) in `indices`",
file: file, line: line) file: file, line: line)
} }
// index comparison // index comparison
for (offsetA, a) in indicesIncludingEnd.enumerated() { for (offsetA, a) in indicesIncludingEnd.enumerated() {
XCTAssertEqual( XCTAssertEqual(
a, a, a, a, "Index at offset \(offsetA) does not equal itself", file: file, line: line)
"Index at offset \(offsetA) does not equal itself",
file: file, line: line)
XCTAssertFalse( XCTAssertFalse(
a < a, a < a, "Index at offset \(offsetA) is less than itself", file: file, line: line)
"Index at offset \(offsetA) is less than itself",
file: file, line: line)
for (offsetB, b) in indicesIncludingEnd[..<offsetA].enumerated() { for (offsetB, b) in indicesIncludingEnd[..<offsetA].enumerated() {
XCTAssertNotEqual( XCTAssertNotEqual(
a, b, a, b, "Index at offset \(offsetA) equals index at offset \(offsetB)", file: file,
"Index at offset \(offsetA) equals index at offset \(offsetB)", line: line)
file: file, line: line)
XCTAssertLessThan( XCTAssertLessThan(
b, a, b, a,
""" """
Index at offset \(offsetB) is not less than index at offset \(offsetA) Index at offset \(offsetB) is not less than index at offset \(offsetA)
""", """, file: file, line: line)
file: file, line: line)
} }
} }
// `index(_:offsetBy:)` and `distance(from:to:)` // `index(_:offsetBy:)` and `distance(from:to:)`
for (startOffset, start) in indicesIncludingEnd.enumerated() { for (startOffset, start) in indicesIncludingEnd.enumerated() {
for (endOffset, end) in indicesIncludingEnd.enumerated() { for (endOffset, end) in indicesIncludingEnd.enumerated() {
let distance = endOffset - startOffset let distance = endOffset - startOffset
XCTAssertEqual( XCTAssertEqual(
c.index(start, offsetBy: distance), end, c.index(start, offsetBy: distance), end,
""" """
Index at offset \(startOffset) offset by \(distance) does not equal \ Index at offset \(startOffset) offset by \(distance) does not equal \
index at offset \(endOffset) index at offset \(endOffset)
""", """, file: file, line: line)
file: file, line: line)
XCTAssertEqual( XCTAssertEqual(
c.distance(from: start, to: end), distance, c.distance(from: start, to: end), distance,
""" """
Distance from index at offset \(startOffset) to index at offset \ Distance from index at offset \(startOffset) to index at offset \
\(endOffset) does not equal \(distance) \(endOffset) does not equal \(distance)
""", """, file: file, line: line)
file: file, line: line)
} }
} }
// `index(_:offsetBy:limitedBy:)` // `index(_:offsetBy:limitedBy:)`
for (startOffset, start) in indicesIncludingEnd.enumerated() { for (startOffset, start) in indicesIncludingEnd.enumerated() {
for (limitOffset, limit) in indicesIncludingEnd.enumerated() { for (limitOffset, limit) in indicesIncludingEnd.enumerated() {
@@ -307,15 +267,14 @@ func validateIndexTraversals<C>(
for targetOffset in range { for targetOffset in range {
let distance = targetOffset - startOffset let distance = targetOffset - startOffset
let end = c.index(start, offsetBy: distance, limitedBy: limit) let end = c.index(start, offsetBy: distance, limitedBy: limit)
if pastLimit { if pastLimit {
XCTAssertNil( XCTAssertNil(
end, end,
""" """
Index at offset \(startOffset) offset by \(distance) limited \ Index at offset \(startOffset) offset by \(distance) limited \
by index at offset \(limitOffset) does not equal `nil` by index at offset \(limitOffset) does not equal `nil`
""", """, file: file, line: line)
file: file, line: line)
} else { } else {
XCTAssertEqual( XCTAssertEqual(
end, indicesIncludingEnd[targetOffset], end, indicesIncludingEnd[targetOffset],
@@ -323,12 +282,11 @@ func validateIndexTraversals<C>(
Index at offset \(startOffset) offset by \(distance) limited \ Index at offset \(startOffset) offset by \(distance) limited \
by index at offset \(limitOffset) does not equal index at \ by index at offset \(limitOffset) does not equal index at \
offset \(targetOffset) offset \(targetOffset)
""", """, file: file, line: line)
file: file, line: line)
} }
} }
} }
// forward offsets // forward offsets
if limit >= start { if limit >= start {
// the limit has an effect // the limit has an effect
@@ -338,7 +296,7 @@ func validateIndexTraversals<C>(
// the limit has no effect // the limit has no effect
checkTargetRange(startOffset...count, pastLimit: false) checkTargetRange(startOffset...count, pastLimit: false)
} }
// backward offsets // backward offsets
if limit <= start { if limit <= start {
// the limit has an effect // the limit has an effect
+1 -3
View File
@@ -21,9 +21,7 @@ final class TrimTests: XCTestCase {
func testNoMatch() { func testNoMatch() {
// No match (nothing trimmed). // No match (nothing trimmed).
let results_nomatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { let results_nomatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0.isMultiple(of: 2) }
$0.isMultiple(of: 2)
}
XCTAssertEqual(results_nomatch, [1, 3, 5, 7, 9, 11, 13, 15]) XCTAssertEqual(results_nomatch, [1, 3, 5, 7, 9, 11, 13, 15])
} }
@@ -9,12 +9,12 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest
import Algorithms import Algorithms
import XCTest
final class UniquePermutationsTests: XCTestCase { final class UniquePermutationsTests: XCTestCase {
static let numbers = [1, 1, 1, 2, 3] static let numbers = [1, 1, 1, 2, 3]
static let numbersPermutations: [[[Int]]] = [ static let numbersPermutations: [[[Int]]] = [
// k = 0 // k = 0
[[]], [[]],
@@ -23,26 +23,24 @@ final class UniquePermutationsTests: XCTestCase {
// 2 // 2
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]], [[1, 1], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]],
// 3 // 3
[[1, 1, 1], [1, 1, 2], [1, 1, 3], [
[1, 2, 1], [1, 2, 3], [1, 3, 1], [1, 3, 2], [1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 3], [1, 3, 1], [1, 3, 2], [2, 1, 1],
[2, 1, 1], [2, 1, 3], [2, 3, 1], [2, 1, 3], [2, 3, 1], [3, 1, 1], [3, 1, 2], [3, 2, 1],
[3, 1, 1], [3, 1, 2], [3, 2, 1]], ],
// 4 // 4
[[1, 1, 1, 2], [1, 1, 1, 3], [
[1, 1, 2, 1], [1, 1, 2, 3], [1, 1, 1, 2], [1, 1, 1, 3], [1, 1, 2, 1], [1, 1, 2, 3], [1, 1, 3, 1], [1, 1, 3, 2],
[1, 1, 3, 1], [1, 1, 3, 2], [1, 2, 1, 1], [1, 2, 1, 3], [1, 2, 3, 1], [1, 3, 1, 1], [1, 3, 1, 2], [1, 3, 2, 1],
[1, 2, 1, 1], [1, 2, 1, 3], [1, 2, 3, 1], [2, 1, 1, 1], [2, 1, 1, 3], [2, 1, 3, 1], [2, 3, 1, 1], [3, 1, 1, 1], [3, 1, 1, 2],
[1, 3, 1, 1], [1, 3, 1, 2], [1, 3, 2, 1], [3, 1, 2, 1], [3, 2, 1, 1],
[2, 1, 1, 1], [2, 1, 1, 3], [2, 1, 3, 1], [2, 3, 1, 1], ],
[3, 1, 1, 1], [3, 1, 1, 2], [3, 1, 2, 1], [3, 2, 1, 1]],
// 5 // 5
[[1, 1, 1, 2, 3], [1, 1, 1, 3, 2], [
[1, 1, 2, 1, 3], [1, 1, 2, 3, 1], [1, 1, 1, 2, 3], [1, 1, 1, 3, 2], [1, 1, 2, 1, 3], [1, 1, 2, 3, 1], [1, 1, 3, 1, 2],
[1, 1, 3, 1, 2], [1, 1, 3, 2, 1], [1, 1, 3, 2, 1], [1, 2, 1, 1, 3], [1, 2, 1, 3, 1], [1, 2, 3, 1, 1], [1, 3, 1, 1, 2],
[1, 2, 1, 1, 3], [1, 2, 1, 3, 1], [1, 2, 3, 1, 1], [1, 3, 1, 2, 1], [1, 3, 2, 1, 1], [2, 1, 1, 1, 3], [2, 1, 1, 3, 1], [2, 1, 3, 1, 1],
[1, 3, 1, 1, 2], [1, 3, 1, 2, 1], [1, 3, 2, 1, 1], [2, 3, 1, 1, 1], [3, 1, 1, 1, 2], [3, 1, 1, 2, 1], [3, 1, 2, 1, 1], [3, 2, 1, 1, 1],
[2, 1, 1, 1, 3], [2, 1, 1, 3, 1], [2, 1, 3, 1, 1], [2, 3, 1, 1, 1], ],
[3, 1, 1, 1, 2], [3, 1, 1, 2, 1], [3, 1, 2, 1, 1], [3, 2, 1, 1, 1]]
] ]
} }
@@ -51,29 +49,24 @@ extension UniquePermutationsTests {
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(), [[]]) XCTAssertEqualSequences(([] as [Int]).uniquePermutations(), [[]])
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 0), [[]]) XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 0), [[]])
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 1), []) XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 1), [])
XCTAssertEqualSequences( XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 1...3), [])
([] as [Int]).uniquePermutations(ofCount: 1...3), [])
} }
func testSingleCounts() { func testSingleCounts() {
for (k, expectation) in Self.numbersPermutations.enumerated() { for (k, expectation) in Self.numbersPermutations.enumerated() {
XCTAssertEqualSequences( XCTAssertEqualSequences(expectation, Self.numbers.uniquePermutations(ofCount: k))
expectation,
Self.numbers.uniquePermutations(ofCount: k))
} }
XCTAssertEqualSequences( XCTAssertEqualSequences(Self.numbersPermutations[5], Self.numbers.uniquePermutations())
Self.numbersPermutations[5],
Self.numbers.uniquePermutations())
} }
func testRanges() { func testRanges() {
for lower in Self.numbersPermutations.indices { for lower in Self.numbersPermutations.indices {
// upper bounded // upper bounded
XCTAssertEqualSequences( XCTAssertEqualSequences(
Self.numbersPermutations[...lower].joined(), Self.numbersPermutations[...lower].joined(),
Self.numbers.uniquePermutations(ofCount: ...lower)) Self.numbers.uniquePermutations(ofCount: ...lower))
// lower bounded // lower bounded
XCTAssertEqualSequences( XCTAssertEqualSequences(
Self.numbersPermutations[lower...].joined(), Self.numbersPermutations[lower...].joined(),
@@ -91,18 +84,12 @@ extension UniquePermutationsTests {
extension UniquePermutationsTests { extension UniquePermutationsTests {
private final class IntBox: Hashable { private final class IntBox: Hashable {
var value: Int var value: Int
init(_ value: Int) {
self.value = value
}
static func == (lhs: IntBox, rhs: IntBox) -> Bool {
lhs.value == rhs.value
}
func hash(into hasher: inout Hasher) { init(_ value: Int) { self.value = value }
hasher.combine(value)
} static func == (lhs: IntBox, rhs: IntBox) -> Bool { lhs.value == rhs.value }
func hash(into hasher: inout Hasher) { hasher.combine(value) }
} }
func testFirstUnique() { func testFirstUnique() {
@@ -115,8 +102,6 @@ extension UniquePermutationsTests {
} }
} }
} }
func testLaziness() { func testLaziness() { XCTAssertLazySequence("ABCD".lazy.uniquePermutations()) }
XCTAssertLazySequence("ABCD".lazy.uniquePermutations())
}
} }
+8 -8
View File
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest
import Algorithms import Algorithms
import XCTest
final class UniqueTests: XCTestCase { final class UniqueTests: XCTestCase {
func testUnique() { func testUnique() {
@@ -18,26 +18,26 @@ final class UniqueTests: XCTestCase {
let b = a.uniqued() let b = a.uniqued()
XCTAssertEqual(b.sorted(), Set(a).sorted()) XCTAssertEqual(b.sorted(), Set(a).sorted())
XCTAssertEqual(10, Array(b).count) XCTAssertEqual(10, Array(b).count)
let c: [Int] = [] let c: [Int] = []
XCTAssertEqualSequences(c.uniqued(), []) XCTAssertEqualSequences(c.uniqued(), [])
let d = Array(repeating: 1, count: 10) let d = Array(repeating: 1, count: 10)
XCTAssertEqualSequences(d.uniqued(), [1]) XCTAssertEqualSequences(d.uniqued(), [1])
} }
func testUniqueOn() { func testUniqueOn() {
let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"] let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
let b = a.uniqued(on: { $0.first }) let b = a.uniqued(on: { $0.first })
XCTAssertEqual(["Albemarle", "Brandywine"], b) XCTAssertEqual(["Albemarle", "Brandywine"], b)
let c: [Int] = [] let c: [Int] = []
XCTAssertEqual(c.uniqued(on: { $0.bitWidth }), []) XCTAssertEqual(c.uniqued(on: { $0.bitWidth }), [])
let d = Array(repeating: "Andromeda", count: 10) let d = Array(repeating: "Andromeda", count: 10)
XCTAssertEqualSequences(d.uniqued(on: { $0.first }), ["Andromeda"]) XCTAssertEqualSequences(d.uniqued(on: { $0.first }), ["Andromeda"])
} }
func testLazyUniqueOn() { func testLazyUniqueOn() {
let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"] let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
let b = a.lazy.uniqued(on: { $0.first }) let b = a.lazy.uniqued(on: { $0.first })
@@ -46,7 +46,7 @@ final class UniqueTests: XCTestCase {
let c: [Int] = [] let c: [Int] = []
XCTAssertEqualSequences(c.lazy.uniqued(on: { $0.bitWidth }), []) XCTAssertEqualSequences(c.lazy.uniqued(on: { $0.bitWidth }), [])
let d = Array(repeating: "Andromeda", count: 10) let d = Array(repeating: "Andromeda", count: 10)
XCTAssertEqualSequences(d.lazy.uniqued(on: { $0.first }), ["Andromeda"]) XCTAssertEqualSequences(d.lazy.uniqued(on: { $0.first }), ["Andromeda"])
} }
+30 -39
View File
@@ -10,10 +10,11 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
final class windowsTests: XCTestCase { final class windowsTests: XCTestCase {
func testWindowsOfString() { func testWindowsOfString() {
let s = "swift" let s = "swift"
let w = s.windows(ofCount: 2) let w = s.windows(ofCount: 2)
@@ -27,56 +28,54 @@ final class windowsTests: XCTestCase {
w.formIndex(after: &i) w.formIndex(after: &i)
XCTAssertEqualSequences(w[i], "ft") XCTAssertEqualSequences(w[i], "ft")
// w.index(after: w.endIndex) // ← Precondition failed: windows 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.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 // w.formIndex(after: &i); w[i] // ← Precondition failed: windows index is out of range
} }
func testWindowsOfRange() { func testWindowsOfRange() {
let a = 0...100 let a = 0...100
XCTAssertTrue(a.windows(ofCount: 200).isEmpty) XCTAssertTrue(a.windows(ofCount: 200).isEmpty)
let w = a.windows(ofCount: 10) let w = a.windows(ofCount: 10)
XCTAssertEqualSequences(w.first!, 0..<10) XCTAssertEqualSequences(w.first!, 0..<10)
XCTAssertEqualSequences(w.last!, 91..<101) XCTAssertEqualSequences(w.last!, 91..<101)
} }
func testWindowsOfInt() { func testWindowsOfInt() {
let a = [ 0, 1, 0, 1 ].windows(ofCount: 2) let a = [0, 1, 0, 1].windows(ofCount: 2)
XCTAssertEqual(a.count, 3) XCTAssertEqual(a.count, 3)
XCTAssertEqual(a.map { $0.reduce(0, +) }, [1, 1, 1]) XCTAssertEqual(a.map { $0.reduce(0, +) }, [1, 1, 1])
let a2 = [0, 1, 2, 3, 4, 5, 6].windows(ofCount: 3).map { let a2 = [0, 1, 2, 3, 4, 5, 6].windows(ofCount: 3).map { $0.reduce(0, +) }.reduce(0, +)
$0.reduce(0, +)
}.reduce(0, +)
XCTAssertEqual(a2, 3 + 6 + 9 + 12 + 15) XCTAssertEqual(a2, 3 + 6 + 9 + 12 + 15)
} }
func testWindowsCount() { func testWindowsCount() {
let a = [0, 1, 2, 3, 4, 5] let a = [0, 1, 2, 3, 4, 5]
XCTAssertEqual(a.windows(ofCount: 3).count, 4) XCTAssertEqual(a.windows(ofCount: 3).count, 4)
let a2 = [0, 1, 2, 3, 4] let a2 = [0, 1, 2, 3, 4]
XCTAssertEqual(a2.windows(ofCount: 6).count, 0) XCTAssertEqual(a2.windows(ofCount: 6).count, 0)
let a3 = [Int]() let a3 = [Int]()
XCTAssertEqual(a3.windows(ofCount: 2).count, 0) XCTAssertEqual(a3.windows(ofCount: 2).count, 0)
} }
func testWindowsSecondAndLast() { func testWindowsSecondAndLast() {
let a = [0, 1, 2, 3, 4, 5] let a = [0, 1, 2, 3, 4, 5]
let w = a.windows(ofCount: 4) let w = a.windows(ofCount: 4)
let snd = w[w.index(after: w.startIndex)] let snd = w[w.index(after: w.startIndex)]
XCTAssertEqualSequences(snd, [1, 2, 3, 4]) XCTAssertEqualSequences(snd, [1, 2, 3, 4])
let w2 = a.windows(ofCount: 3) let w2 = a.windows(ofCount: 3)
XCTAssertEqualSequences(w2.last!, [3, 4, 5]) XCTAssertEqualSequences(w2.last!, [3, 4, 5])
} }
func testWindowsIndexAfterAndBefore() { func testWindowsIndexAfterAndBefore() {
let a = [0, 1, 2, 3, 4, 5].windows(ofCount: 2) let a = [0, 1, 2, 3, 4, 5].windows(ofCount: 2)
var i = a.startIndex var i = a.startIndex
@@ -85,27 +84,19 @@ final class windowsTests: XCTestCase {
a.formIndex(before: &i) a.formIndex(before: &i)
XCTAssertEqualSequences(a[i], [1, 2]) XCTAssertEqualSequences(a[i], [1, 2])
} }
func testWindowsIndexTraversals() { func testWindowsIndexTraversals() {
validateIndexTraversals( validateIndexTraversals(
"".windows(ofCount: 1), "".windows(ofCount: 1), "a".windows(ofCount: 1), "ab".windows(ofCount: 1),
"a".windows(ofCount: 1), "abc".windows(ofCount: 1), "".windows(ofCount: 3), "a".windows(ofCount: 3),
"ab".windows(ofCount: 1), "abc".windows(ofCount: 3), "abcdefgh".windows(ofCount: 3),
"abc".windows(ofCount: 1), indices: { windows in let endIndex = windows.base.endIndex
"".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] let indices = windows.base.indices + [endIndex]
return zip(indices, indices.dropFirst(windows.size)) return zip(indices, indices.dropFirst(windows.size)).map {
.map { .init(lowerBound: $0, upperBound: $1) } .init(lowerBound: $0, upperBound: $1)
+ [.init(lowerBound: endIndex, upperBound: endIndex)] } + [.init(lowerBound: endIndex, upperBound: endIndex)]
}) })
} }
func testWindowsLazy() { func testWindowsLazy() { XCTAssertLazyCollection([0, 1, 2, 3].lazy.windows(ofCount: 2)) }
XCTAssertLazyCollection([0, 1, 2, 3].lazy.windows(ofCount: 2))
}
} }