Download swift_algorithms.jsonl from WeirdRunner/ncm-code-curated: direct link, hf CLI and curl.
- Browser
- Download file 298 kB
-
https://huggingface.co/datasets/WeirdRunner/ncm-code-curated/resolve/main/swift_algorithms.jsonl
- Command line
-
hf download hf://datasets/WeirdRunner/ncm-code-curated/swift_algorithms.jsonl
-
curl -L -o swift_algorithms.jsonl https://huggingface.co/datasets/WeirdRunner/ncm-code-curated/resolve/main/swift_algorithms.jsonl
298 kB
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Package.swift", "content": "// swift-tools-version:5.7\n//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageDescription\n\nlet package = Package(\n name: \"swift-algorithms\",\n products: [\n .library(\n name: \"Algorithms\",\n targets: [\"Algorithms\"])\n ],\n dependencies: [\n .package(url: \"https://github.com/apple/swift-numerics.git\", from: \"1.0.0\")\n ],\n targets: [\n .target(\n name: \"Algorithms\",\n dependencies: [\n .product(name: \"RealModule\", package: \"swift-numerics\")\n ]),\n .testTarget(\n name: \"SwiftAlgorithmsTests\",\n dependencies: [\"Algorithms\"]),\n ]\n)"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "FlattenCollection.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// A collection consisting of all the elements contained in a collection of\n/// collections.\n@usableFromInline\ninternal struct FlattenCollection<Base: Collection>\nwhere Base.Element: Collection {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let indexOfFirstNonEmptyElement: Base.Index\n\n @inlinable\n internal init(base: Base) {\n self.base = base\n self.indexOfFirstNonEmptyElement = base.endOfPrefix(while: { $0.isEmpty })\n }\n}\n\nextension FlattenCollection: Collection {\n @usableFromInline\n internal struct Index: Comparable {\n @usableFromInline\n internal let outer: Base.Index\n\n @usableFromInline\n internal let inner: Base.Element.Index?\n\n @inlinable\n init(outer: Base.Index, inner: Base.Element.Index?) {\n self.outer = outer\n self.inner = inner\n }\n\n @inlinable\n internal static func < (lhs: Self, rhs: Self) -> Bool {\n guard lhs.outer == rhs.outer else { return lhs.outer < rhs.outer }\n // swift-format-ignore: NeverForceUnwrap\n // `inner` is nil iff `outer` is `base.endIndex`, and the\n // previous line established that the two outer indices are equal.\n // Thus, either both inner indices are nil or neither are.\n return lhs.inner == nil ? false : lhs.inner! < rhs.inner!\n }\n }\n\n @inlinable\n internal var startIndex: Index {\n let outer = indexOfFirstNonEmptyElement\n let inner = outer == base.endIndex ? nil : base[outer].startIndex\n return Index(outer: outer, inner: inner)\n }\n\n @inlinable\n internal var endIndex: Index {\n Index(outer: base.endIndex, inner: nil)\n }\n\n /// Forms an index from a pair of base indices, normalizing\n /// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if\n /// necessary.\n @inlinable\n internal func normalizeIndex(\n outer: Base.Index,\n inner: Base.Element.Index\n ) -> Index {\n guard inner == base[outer].endIndex else {\n return Index(outer: outer, inner: inner)\n }\n let outer = base[base.index(after: outer)...]\n .endOfPrefix(while: { $0.isEmpty })\n let inner = outer == base.endIndex ? nil : base[outer].startIndex\n return Index(outer: outer, inner: inner)\n }\n\n @inlinable\n internal func index(after index: Index) -> Index {\n let element = base[index.outer]\n // swift-format-ignore: NeverForceUnwrap\n // This unwrap, like the unchecked subscript above, enforces the\n // precondition that you can't advance past `endIndex`.\n let nextInner = element.index(after: index.inner!)\n return normalizeIndex(outer: index.outer, inner: nextInner)\n }\n\n @inlinable\n internal subscript(position: Index) -> Base.Element.Element {\n // swift-format-ignore: NeverForceUnwrap\n // This unwrap, along with the unchecked subscript, enforces the\n // precondition that you can't subscript at `endIndex`.\n base[position.outer][position.inner!]\n }\n\n @inlinable\n internal func distance(from start: Index, to end: Index) -> Int {\n guard start.outer <= end.outer\n else { return -distance(from: end, to: start) }\n guard let startInner = start.inner\n else { return 0 }\n guard start.outer != end.outer\n else {\n // swift-format-ignore: NeverForceUnwrap\n // Established via guards that outer indices are equal and `start.inner`\n // is non-nil, so `end.inner` must also be non-`nil`.\n return base[start.outer].distance(from: startInner, to: end.inner!)\n }\n\n let firstPart = base[start.outer][startInner...].count\n let middlePart = base[start.outer..<end.outer].dropFirst()\n .reduce(0, { $0 + $1.count })\n let lastPart = end.inner.map { base[end.outer][..<$0].count } ?? 0\n\n return firstPart + middlePart + lastPart\n }\n\n @inlinable\n internal func index(_ index: Index, offsetBy distance: Int) -> Index {\n guard distance != 0 else { return index }\n\n return distance > 0\n ? offsetForward(index, by: distance)\n : offsetBackward(index, by: -distance)\n }\n\n @inlinable\n internal func index(\n _ index: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n guard distance != 0 else { return index }\n\n if distance > 0 {\n return limit >= index\n ? offsetForward(index, by: distance, limitedBy: limit)\n : offsetForward(index, by: distance)\n } else {\n return limit <= index\n ? offsetBackward(index, by: -distance, limitedBy: limit)\n : offsetBackward(index, by: -distance)\n }\n }\n\n @inlinable\n internal func offsetForward(_ i: Index, by distance: Int) -> Index {\n guard let index = offsetForward(i, by: distance, limitedBy: endIndex)\n else { fatalError(\"Index is out of bounds\") }\n return index\n }\n\n @inlinable\n internal func offsetBackward(_ i: Index, by distance: Int) -> Index {\n guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)\n else { fatalError(\"Index is out of bounds\") }\n return index\n }\n\n @inlinable\n internal func offsetForward(\n _ index: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance > 0)\n assert(limit >= index)\n\n if index.outer == limit.outer {\n guard let indexInner = index.inner, let limitInner = limit.inner else {\n // `index` and `limit` are both `endIndex`\n return nil\n }\n return base[index.outer]\n .index(indexInner, offsetBy: distance, limitedBy: limitInner)\n .map { inner in Index(outer: index.outer, inner: inner) }\n }\n\n // swift-format-ignore: NeverForceUnwrap\n // `index <= limit` and `index.outer != limit.outer`, so `index != endIndex`\n let indexInner = index.inner!\n let element = base[index.outer]\n\n if let inner = element.index(\n indexInner,\n offsetBy: distance,\n limitedBy: element.endIndex\n ) {\n return normalizeIndex(outer: index.outer, inner: inner)\n }\n\n var remainder = distance - element[indexInner...].count\n var outer = base.index(after: index.outer)\n\n while outer != limit.outer {\n let element = base[outer]\n\n if let inner = element.index(\n element.startIndex,\n offsetBy: remainder,\n limitedBy: element.endIndex\n ) {\n return normalizeIndex(outer: outer, inner: inner)\n }\n\n remainder -= element.count\n base.formIndex(after: &outer)\n }\n\n if let limitInner = limit.inner {\n let element = base[outer]\n return element.index(\n element.startIndex,\n offsetBy: remainder,\n limitedBy: limitInner\n )\n .map { inner in Index(outer: outer, inner: inner) }\n }\n return nil\n }\n\n @inlinable\n internal func offsetBackward(\n _ index: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance > 0)\n assert(limit <= index)\n\n if index.outer == limit.outer {\n guard let indexInner = index.inner, let limitInner = limit.inner else {\n // `index` and `limit` are both `endIndex`\n return nil\n }\n return base[index.outer]\n .index(indexInner, offsetBy: -distance, limitedBy: limitInner)\n .map { inner in Index(outer: index.outer, inner: inner) }\n }\n\n var remainder = distance\n\n if let indexInner = index.inner {\n let element = base[index.outer]\n\n if let inner = element.index(\n indexInner,\n offsetBy: -remainder,\n limitedBy: element.startIndex\n ) {\n return Index(outer: index.outer, inner: inner)\n }\n\n remainder -= element[..<indexInner].count\n }\n\n var outer = base.index(index.outer, offsetBy: -1)\n\n while outer != limit.outer {\n let element = base[outer]\n\n if let inner = element.index(\n element.endIndex,\n offsetBy: -remainder,\n limitedBy: element.startIndex\n ) {\n return Index(outer: outer, inner: inner)\n }\n\n remainder -= element.count\n base.formIndex(&outer, offsetBy: -1)\n }\n\n let element = base[outer]\n // swift-format-ignore: NeverForceUnwrap\n // At start of function, `limit <= index`, and checked for\n // `limit == endIndex`.\n return element.index(\n element.endIndex,\n offsetBy: -remainder,\n limitedBy: limit.inner!\n ).map { inner in Index(outer: outer, inner: inner) }\n }\n}\n\nextension FlattenCollection: BidirectionalCollection\nwhere Base: BidirectionalCollection, Base.Element: BidirectionalCollection {\n @inlinable\n internal func index(before index: Index) -> Index {\n if let inner = index.inner {\n let element = base[index.outer]\n\n if inner != element.startIndex {\n let previousInner = element.index(before: inner)\n return Index(outer: index.outer, inner: previousInner)\n }\n }\n\n guard\n let previousOuter = base[..<index.outer]\n .lastIndex(where: { !$0.isEmpty })\n else {\n fatalError(\"Can't move before startIndex.\")\n }\n let element = base[previousOuter]\n let previousInner = element.index(before: element.endIndex)\n return Index(outer: previousOuter, inner: previousInner)\n }\n}\n\nextension FlattenCollection: LazySequenceProtocol, LazyCollectionProtocol\nwhere Base: LazySequenceProtocol, Base.Element: LazySequenceProtocol {}\n\n//===----------------------------------------------------------------------===//\n// joined()\n//===----------------------------------------------------------------------===//\n\nextension Collection where Element: Collection {\n /// Returns the concatenation of the elements in this collection of\n /// collections.\n @inlinable\n internal func joined() -> FlattenCollection<Self> {\n FlattenCollection(base: self)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "EndsWith.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// EndsWith\n//===----------------------------------------------------------------------===//\n\nextension BidirectionalCollection where Element: Equatable {\n /// Returns a Boolean value indicating whether the final elements of the\n /// collection are the same as the elements in another collection.\n ///\n /// This example tests whether one countable range ends with the elements\n /// of another countable range.\n ///\n /// let a = 8...10\n /// let b = 1...10\n ///\n /// print(b.ends(with: a))\n /// // Prints \"true\"\n ///\n /// Passing a collection with no elements or an empty collection as\n /// `possibleSuffix` always results in `true`.\n ///\n /// print(b.ends(with: []))\n /// // Prints \"true\"\n ///\n /// - Parameter possibleSuffix: A collection to compare to this collection.\n /// - Returns: `true` if the initial elements of the collection are the same as\n /// the elements of `possibleSuffix`; otherwise, `false`. If\n /// `possibleSuffix` has no elements, the return value is `true`.\n ///\n /// - Complexity: O(*m*), where *m* is the lesser of the length of the\n /// collection and the length of `possibleSuffix`.\n @inlinable\n public func ends<PossibleSuffix: BidirectionalCollection>(\n with possibleSuffix: PossibleSuffix\n ) -> Bool where PossibleSuffix.Element == Element {\n self.ends(with: possibleSuffix, by: ==)\n }\n}\n\nextension BidirectionalCollection {\n /// Returns a Boolean value indicating whether the final elements of the\n /// collection are equivalent to the elements in another collection, using\n /// the given predicate as the equivalence test.\n ///\n /// The predicate must be an *equivalence relation* over the elements. That\n /// is, for any elements `a`, `b`, and `c`, the following conditions must\n /// hold:\n ///\n /// - `areEquivalent(a, a)` is always `true`. (Reflexivity)\n /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)\n /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then\n /// `areEquivalent(a, c)` is also `true`. (Transitivity)\n ///\n /// - Parameters:\n /// - possibleSuffix: A collection to compare to this collection.\n /// - areEquivalent: A predicate that returns `true` if its two arguments\n /// are equivalent; otherwise, `false`.\n /// - Returns: `true` if the initial elements of the collection are equivalent\n /// to the elements of `possibleSuffix`; otherwise, `false`. If\n /// `possibleSuffix` has no elements, the return value is `true`.\n ///\n /// - Complexity: O(*m*), where *m* is the lesser of the length of the\n /// collection and the length of `possibleSuffix`.\n @inlinable\n public func ends<PossibleSuffix: BidirectionalCollection>(\n with possibleSuffix: PossibleSuffix,\n by areEquivalent: (Element, PossibleSuffix.Element) throws -> Bool\n ) rethrows -> Bool {\n try self\n .reversed()\n .starts(with: possibleSuffix.reversed(), by: areEquivalent)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Chunked.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// A collection wrapper that breaks a collection into chunks based on a\n/// predicate.\n///\n/// Call `lazy.chunked(by:)` on a collection to create an instance of this type.\npublic struct ChunkedByCollection<Base: Collection, Subject> {\n /// The collection that this instance provides a view onto.\n @usableFromInline\n internal let base: Base\n\n /// The projection function.\n @usableFromInline\n internal let projection: (Base.Element) -> Subject\n\n /// The predicate.\n @usableFromInline\n internal let belongInSameGroup: (Subject, Subject) -> Bool\n\n /// The end index of the first chunk.\n @usableFromInline\n internal var endOfFirstChunk: Base.Index\n\n @inlinable\n internal init(\n base: Base,\n projection: @escaping (Base.Element) -> Subject,\n belongInSameGroup: @escaping (Subject, Subject) -> Bool\n ) {\n self.base = base\n self.projection = projection\n self.belongInSameGroup = belongInSameGroup\n self.endOfFirstChunk = base.startIndex\n\n if !base.isEmpty {\n endOfFirstChunk = endOfChunk(startingAt: base.startIndex)\n }\n }\n}\n\nextension ChunkedByCollection: Collection {\n /// A position in a chunked collection.\n public struct Index: Comparable {\n /// The range corresponding to the chunk at this position.\n @usableFromInline\n internal var baseRange: Range<Base.Index>\n\n @inlinable\n internal init(_ baseRange: Range<Base.Index>) {\n self.baseRange = baseRange\n }\n\n @inlinable\n public static func == (lhs: Index, rhs: Index) -> Bool {\n // Since each index represents the range of a disparate chunk, no two\n // unique indices will have the same lower bound.\n lhs.baseRange.lowerBound == rhs.baseRange.lowerBound\n }\n\n @inlinable\n public static func < (lhs: Index, rhs: Index) -> Bool {\n // Only use the lower bound to test for ordering, as above.\n lhs.baseRange.lowerBound < rhs.baseRange.lowerBound\n }\n }\n\n /// Returns the index in the base collection of the end of the chunk starting\n /// at the given index.\n @inlinable\n internal func endOfChunk(startingAt start: Base.Index) -> Base.Index {\n var subject = projection(base[start])\n\n return base[base.index(after: start)...].endOfPrefix(while: { element in\n let nextSubject = projection(element)\n defer { subject = nextSubject }\n return belongInSameGroup(subject, nextSubject)\n })\n }\n\n @inlinable\n public var startIndex: Index {\n Index(base.startIndex..<endOfFirstChunk)\n }\n\n @inlinable\n public var endIndex: Index {\n Index(base.endIndex..<base.endIndex)\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n precondition(i != endIndex, \"Can't advance past endIndex\")\n let upperBound = i.baseRange.upperBound\n guard upperBound != base.endIndex else { return endIndex }\n let end = endOfChunk(startingAt: upperBound)\n return Index(upperBound..<end)\n }\n\n @inlinable\n public subscript(position: Index) -> Base.SubSequence {\n precondition(position != endIndex, \"Can't subscript using endIndex\")\n return base[position.baseRange]\n }\n}\n\nextension ChunkedByCollection.Index: Hashable where Base.Index: Hashable {}\n\nextension ChunkedByCollection: BidirectionalCollection\nwhere Base: BidirectionalCollection {\n /// Returns the index in the base collection of the start of the chunk ending\n /// at the given index.\n @inlinable\n internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {\n let indexBeforeEnd = base.index(before: end)\n var subject = projection(base[indexBeforeEnd])\n\n return base[..<indexBeforeEnd].startOfSuffix(while: { element in\n let nextSubject = projection(element)\n defer { subject = nextSubject }\n return belongInSameGroup(nextSubject, subject)\n })\n }\n\n @inlinable\n public func index(before i: Index) -> Index {\n precondition(i != startIndex, \"Can't advance before startIndex\")\n let start = startOfChunk(endingAt: i.baseRange.lowerBound)\n return Index(start..<i.baseRange.lowerBound)\n }\n}\n\nextension ChunkedByCollection: LazyCollectionProtocol {}\n\n/// A collection wrapper that breaks a collection into chunks based on a\n/// predicate.\n///\n/// Call `lazy.chunked(on:)` on a collection to create an instance of this type.\npublic struct ChunkedOnCollection<Base: Collection, Subject: Equatable> {\n @usableFromInline\n internal var chunked: ChunkedByCollection<Base, Subject>\n\n @inlinable\n internal init(\n base: Base,\n projection: @escaping (Base.Element) -> Subject\n ) {\n self.chunked = ChunkedByCollection(\n base: base,\n projection: projection,\n belongInSameGroup: ==)\n }\n}\n\nextension ChunkedOnCollection: Collection {\n public typealias Index = ChunkedByCollection<Base, Subject>.Index\n\n @inlinable\n public var startIndex: Index {\n chunked.startIndex\n }\n\n @inlinable\n public var endIndex: Index {\n chunked.endIndex\n }\n\n @inlinable\n public subscript(position: Index) -> (Subject, Base.SubSequence) {\n let subsequence = chunked[position]\n // swift-format-ignore: NeverForceUnwrap\n // Chunks are never empty, so `.first!` is safe.\n let subject = chunked.projection(subsequence.first!)\n return (subject, subsequence)\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n chunked.index(after: i)\n }\n}\n\nextension ChunkedOnCollection: BidirectionalCollection\nwhere Base: BidirectionalCollection {\n @inlinable\n public func index(before i: Index) -> Index {\n chunked.index(before: i)\n }\n}\n\nextension ChunkedOnCollection: LazyCollectionProtocol {}\n\n/// A collection wrapper that evenly breaks a collection into a given number of\n/// chunks.\npublic struct EvenlyChunkedCollection<Base: Collection> {\n /// The base collection.\n @usableFromInline\n internal let base: Base\n\n /// The number of equal chunks the base collection is divided into.\n @usableFromInline\n internal let numberOfChunks: Int\n\n /// The count of the base collection.\n @usableFromInline\n internal let baseCount: Int\n\n /// The upper bound of the first chunk.\n @usableFromInline\n internal var firstUpperBound: Base.Index\n\n @inlinable\n internal init(base: Base, numberOfChunks: Int) {\n self.base = base\n self.numberOfChunks = numberOfChunks\n self.baseCount = base.count\n self.firstUpperBound = base.startIndex\n\n if numberOfChunks > 0 {\n firstUpperBound = endOfChunk(startingAt: base.startIndex, offset: 0)\n }\n }\n}\n\nextension EvenlyChunkedCollection {\n /// Returns the number of chunks with size `smallChunkSize + 1` at the start\n /// of this collection.\n @inlinable\n internal var numberOfLargeChunks: Int {\n baseCount % numberOfChunks\n }\n\n /// Returns the size of a chunk at a given offset.\n @inlinable\n internal func sizeOfChunk(offset: Int) -> Int {\n let isLargeChunk = offset < numberOfLargeChunks\n return baseCount / numberOfChunks + (isLargeChunk ? 1 : 0)\n }\n\n /// Returns the index in the base collection of the end of the chunk starting\n /// at the given index.\n @inlinable\n internal func endOfChunk(startingAt start: Base.Index, offset: Int)\n -> Base.Index\n {\n base.index(start, offsetBy: sizeOfChunk(offset: offset))\n }\n\n /// Returns the index in the base collection of the start of the chunk ending\n /// at the given index.\n @inlinable\n internal func startOfChunk(endingAt end: Base.Index, offset: Int)\n -> Base.Index\n {\n base.index(end, offsetBy: -sizeOfChunk(offset: offset))\n }\n\n /// Returns the index that corresponds to the chunk that starts at the given\n /// base index.\n @inlinable\n internal func indexOfChunk(startingAt start: Base.Index, offset: Int) -> Index\n {\n guard offset != numberOfChunks else { return endIndex }\n let end = endOfChunk(startingAt: start, offset: offset)\n return Index(start..<end, offset: offset)\n }\n\n /// Returns the index that corresponds to the chunk that ends at the given\n /// base index.\n @inlinable\n internal func indexOfChunk(endingAt end: Base.Index, offset: Int) -> Index {\n let start = startOfChunk(endingAt: end, offset: offset)\n return Index(start..<end, offset: offset)\n }\n}\n\nextension EvenlyChunkedCollection: Collection {\n public struct Index: Comparable {\n /// The range corresponding to the chunk at this position.\n @usableFromInline\n internal var baseRange: Range<Base.Index>\n\n /// The offset corresponding to the chunk at this position.\n ///\n /// The first chunk has offset `0` and all other chunks have an offset\n /// `1` greater than the previous.\n @usableFromInline\n internal var offset: Int\n\n @inlinable\n internal init(_ baseRange: Range<Base.Index>, offset: Int) {\n self.baseRange = baseRange\n self.offset = offset\n }\n\n @inlinable\n public static func == (lhs: Self, rhs: Self) -> Bool {\n lhs.offset == rhs.offset\n }\n\n @inlinable\n public static func < (lhs: Self, rhs: Self) -> Bool {\n lhs.offset < rhs.offset\n }\n }\n\n public typealias Element = Base.SubSequence\n\n @inlinable\n public var startIndex: Index {\n Index(base.startIndex..<firstUpperBound, offset: 0)\n }\n\n @inlinable\n public var endIndex: Index {\n Index(base.endIndex..<base.endIndex, offset: numberOfChunks)\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n precondition(i != endIndex, \"Can't advance past endIndex\")\n let start = i.baseRange.upperBound\n return indexOfChunk(startingAt: start, offset: i.offset + 1)\n }\n\n @inlinable\n public subscript(position: Index) -> Element {\n precondition(position != endIndex)\n return base[position.baseRange]\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n /// Returns the base distance between two `EvenChunksCollection` indices\n /// from the end of one to the start of the other, when given their offsets.\n func baseDistance(from offsetA: Int, to offsetB: Int) -> Int {\n let smallChunkSize = baseCount / numberOfChunks\n let numberOfChunks = (offsetB - offsetA) - 1\n\n let largeChunksEnd = Swift.min(self.numberOfLargeChunks, offsetB)\n let largeChunksStart = Swift.min(self.numberOfLargeChunks, offsetA + 1)\n let numberOfLargeChunks = largeChunksEnd - largeChunksStart\n\n return smallChunkSize * numberOfChunks + numberOfLargeChunks\n }\n\n if distance == 0 {\n return i\n } else if distance > 0 {\n let offset = i.offset + distance\n let baseOffset = baseDistance(from: i.offset, to: offset)\n let start = base.index(i.baseRange.upperBound, offsetBy: baseOffset)\n return indexOfChunk(startingAt: start, offset: offset)\n } else {\n let offset = i.offset + distance\n let baseOffset = baseDistance(from: offset, to: i.offset)\n let end = base.index(i.baseRange.lowerBound, offsetBy: -baseOffset)\n return indexOfChunk(endingAt: end, offset: offset)\n }\n }\n\n @inlinable\n public func index(\n _ i: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n if distance >= 0 {\n if (0..<distance).contains(self.distance(from: i, to: limit)) {\n return nil\n }\n } else {\n if (0..<(-distance)).contains(self.distance(from: limit, to: i)) {\n return nil\n }\n }\n return index(i, offsetBy: distance)\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n end.offset - start.offset\n }\n}\n\nextension EvenlyChunkedCollection.Index: Hashable where Base.Index: Hashable {}\n\nextension EvenlyChunkedCollection: BidirectionalCollection\nwhere Base: BidirectionalCollection {\n @inlinable\n public func index(before i: Index) -> Index {\n precondition(i != startIndex, \"Can't advance before startIndex\")\n return indexOfChunk(endingAt: i.baseRange.lowerBound, offset: i.offset - 1)\n }\n}\n\nextension EvenlyChunkedCollection: RandomAccessCollection\nwhere Base: RandomAccessCollection {}\n\nextension EvenlyChunkedCollection: LazySequenceProtocol\nwhere Base: LazySequenceProtocol {}\n\nextension EvenlyChunkedCollection: LazyCollectionProtocol\nwhere Base: LazyCollectionProtocol {}\n\n//===----------------------------------------------------------------------===//\n// lazy.chunked(by:) / lazy.chunked(on:)\n//===----------------------------------------------------------------------===//\n\nextension LazySequenceProtocol where Self: Collection, Elements: Collection {\n /// Returns a lazy collection of subsequences of this collection, chunked by\n /// the given predicate.\n ///\n /// - Parameter belongInSameGroup: A closure that takes two adjacent elements\n /// of the sequence and returns whether or not they belong in the same\n /// group.\n /// - Returns: A collection of subsequences, with every pairwise group of\n /// elements in each chunk returning `true` for `belongInSameGroup`.\n ///\n /// - Complexity: O(*n*), because the start index is pre-computed.\n @inlinable\n public func chunked(\n by belongInSameGroup: @escaping (Element, Element) -> Bool\n ) -> ChunkedByCollection<Elements, Element> {\n ChunkedByCollection(\n base: elements,\n projection: { $0 },\n belongInSameGroup: belongInSameGroup)\n }\n\n /// Returns a lazy collection of subsequences of this collection, chunked by\n /// grouping elements that project to equal values.\n ///\n /// - Parameter projection: A closure that takes an element in the sequence\n /// and returns an `Equatable` value that can be used to determine if\n /// adjacent elements belong in the same group.\n /// - Returns: A collection of subsequences, with every element in each chunk\n /// returning the same value for `projection`.\n ///\n /// - Complexity: O(*n*), because the start index is pre-computed.\n @inlinable\n public func chunked<Subject>(\n on projection: @escaping (Element) -> Subject\n ) -> ChunkedOnCollection<Elements, Subject> {\n ChunkedOnCollection(\n base: elements,\n projection: projection\n )\n }\n}\n\n//===----------------------------------------------------------------------===//\n// chunked(by:) / chunked(on:)\n//===----------------------------------------------------------------------===//\n\nextension Collection {\n /// Returns a collection of subsequences of this collection, chunked by the\n /// given predicate.\n ///\n /// - Parameter belongInSameGroup: A closure that takes two adjacent elements\n /// of the collection and returns whether or not they belong in the same\n /// group.\n /// - Returns: A collection of subsequences, with every pairwise group of\n /// elements in each chunk returning `true` for `belongInSameGroup`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of this collection.\n @inlinable\n public func chunked(\n by belongInSameGroup: (Element, Element) throws -> Bool\n ) rethrows -> [SubSequence] {\n guard !isEmpty else { return [] }\n var result: [SubSequence] = []\n\n var start = startIndex\n var current = self[start]\n\n for (index, element) in indexed().dropFirst() {\n if try !belongInSameGroup(current, element) {\n result.append(self[start..<index])\n start = index\n }\n current = element\n }\n\n if start != endIndex {\n result.append(self[start...])\n }\n\n return result\n }\n\n /// Returns a collection of subsequences of this collection, chunked by\n /// grouping elements that project to equal values.\n ///\n /// - Parameter projection: A closure that takes an element in the collection\n /// and returns an `Equatable` value that can be used to determine if\n /// adjacent elements belong in the same group.\n /// - Returns: A collection of subsequences, with every element in each chunk\n /// returning the same value for `projection`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of this collection.\n @inlinable\n public func chunked<Subject: Equatable>(\n on projection: (Element) throws -> Subject\n ) rethrows -> [(Subject, SubSequence)] {\n guard !isEmpty else { return [] }\n var result: [(Subject, SubSequence)] = []\n\n var start = startIndex\n var subject = try projection(self[start])\n\n for (index, element) in indexed().dropFirst() {\n let nextSubject = try projection(element)\n if subject != nextSubject {\n result.append((subject, self[start..<index]))\n start = index\n subject = nextSubject\n }\n }\n\n if start != endIndex {\n result.append((subject, self[start...]))\n }\n\n return result\n }\n}\n\n//===----------------------------------------------------------------------===//\n// chunks(ofCount:)\n//===----------------------------------------------------------------------===//\n\n/// A collection that presents the elements of its base collection in\n/// `SubSequence` chunks of any given count.\n///\n/// A `ChunksOfCountCollection` is a lazy view on the base `Collection`, but it\n/// does not implicitly confer laziness on algorithms applied to its result. In\n/// other words, for ordinary collections `c`:\n///\n/// * `c.chunks(ofCount: 3)` does not create new storage\n/// * `c.chunks(ofCount: 3).map(f)` maps eagerly and returns a new array\n/// * `c.lazy.chunks(ofCount: 3).map(f)` maps lazily and returns a\n/// `LazyMapCollection`\npublic struct ChunksOfCountCollection<Base: Collection> {\n public typealias Element = Base.SubSequence\n\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let chunkCount: Int\n\n @usableFromInline\n internal var endOfFirstChunk: Base.Index\n\n /// Creates a view instance that presents the elements of `base` in\n /// `SubSequence` chunks of the given count.\n ///\n /// - Complexity: O(*n*), because the start index is pre-computed.\n @inlinable\n internal init(_base: Base, _chunkCount: Int) {\n self.base = _base\n self.chunkCount = _chunkCount\n\n // Compute the start index upfront in order to make start index a O(1)\n // lookup.\n self.endOfFirstChunk =\n _base.index(\n _base.startIndex,\n offsetBy: _chunkCount,\n limitedBy: _base.endIndex\n ) ?? _base.endIndex\n }\n}\n\nextension ChunksOfCountCollection: Collection {\n public struct Index {\n @usableFromInline\n internal let baseRange: Range<Base.Index>\n\n @inlinable\n internal init(_baseRange: Range<Base.Index>) {\n self.baseRange = _baseRange\n }\n }\n\n /// - Complexity: O(1)\n @inlinable\n public var startIndex: Index {\n Index(_baseRange: base.startIndex..<endOfFirstChunk)\n }\n\n @inlinable\n public var endIndex: Index {\n Index(_baseRange: base.endIndex..<base.endIndex)\n }\n\n /// - Complexity: O(1)\n @inlinable\n public subscript(i: Index) -> Element {\n precondition(i != endIndex, \"Index out of range\")\n return base[i.baseRange]\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n precondition(i != endIndex, \"Advancing past end index\")\n let baseIdx =\n base.index(\n i.baseRange.upperBound,\n offsetBy: chunkCount,\n limitedBy: base.endIndex\n ) ?? base.endIndex\n return Index(_baseRange: i.baseRange.upperBound..<baseIdx)\n }\n}\n\nextension ChunksOfCountCollection.Index: Comparable {\n @inlinable\n public static func == (\n lhs: ChunksOfCountCollection.Index,\n rhs: ChunksOfCountCollection.Index\n ) -> Bool {\n lhs.baseRange.lowerBound == rhs.baseRange.lowerBound\n }\n\n @inlinable\n public static func < (\n lhs: ChunksOfCountCollection.Index,\n rhs: ChunksOfCountCollection.Index\n ) -> Bool {\n lhs.baseRange.lowerBound < rhs.baseRange.lowerBound\n }\n}\n\nextension ChunksOfCountCollection:\n BidirectionalCollection, RandomAccessCollection\nwhere Base: RandomAccessCollection {\n @inlinable\n public func index(before i: Index) -> Index {\n precondition(i != startIndex, \"Advancing past start index\")\n\n var offset = chunkCount\n if i.baseRange.lowerBound == base.endIndex {\n let remainder = base.count % chunkCount\n if remainder != 0 {\n offset = remainder\n }\n }\n\n let baseIdx =\n base.index(\n i.baseRange.lowerBound,\n offsetBy: -offset,\n limitedBy: base.startIndex\n ) ?? base.startIndex\n return Index(_baseRange: baseIdx..<i.baseRange.lowerBound)\n }\n}\n\nextension ChunksOfCountCollection {\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n let distance =\n base\n .distance(from: start.baseRange.lowerBound, to: end.baseRange.lowerBound)\n let (quotient, remainder) =\n distance\n .quotientAndRemainder(dividingBy: chunkCount)\n return quotient + remainder.signum()\n }\n\n @inlinable\n public var count: Int {\n let (quotient, remainder) =\n base.count.quotientAndRemainder(dividingBy: chunkCount)\n return quotient + remainder.signum()\n }\n\n @inlinable\n public func index(\n _ i: Index,\n offsetBy offset: Int,\n limitedBy limit: Index\n ) -> Index? {\n guard offset != 0 else { return i }\n guard limit != i else { return nil }\n\n if offset > 0 {\n return limit > i\n ? offsetForward(i, offsetBy: offset, limit: limit)\n : offsetForward(i, offsetBy: offset)\n } else {\n return limit < i\n ? offsetBackward(i, offsetBy: offset, limit: limit)\n : offsetBackward(i, offsetBy: offset)\n }\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n guard distance != 0 else { return i }\n\n let idx =\n distance > 0\n ? offsetForward(i, offsetBy: distance)\n : offsetBackward(i, offsetBy: distance)\n guard let index = idx else {\n fatalError(\"Out of bounds\")\n }\n return index\n }\n\n @inlinable\n internal func offsetForward(\n _ i: Index,\n offsetBy distance: Int,\n limit: Index? = nil\n ) -> Index? {\n assert(distance > 0)\n\n return makeOffsetIndex(\n from: i,\n baseBound: base.endIndex,\n distance: distance,\n baseDistance: distance * chunkCount,\n limit: limit,\n by: >\n )\n }\n\n // Convenience to compute offset backward base distance.\n @inlinable\n internal func computeOffsetBackwardBaseDistance(\n _ i: Index,\n _ distance: Int\n ) -> Int {\n if i == endIndex {\n let remainder = base.count % chunkCount\n // We have to take it into account when calculating offsets.\n if remainder != 0 {\n // Distance \"minus\" one (at this point distance is negative) because we\n // need to adjust for the last position that have a variadic (remainder)\n // number of elements.\n return ((distance + 1) * chunkCount) - remainder\n }\n }\n return distance * chunkCount\n }\n\n @inlinable\n internal func offsetBackward(\n _ i: Index,\n offsetBy distance: Int,\n limit: Index? = nil\n ) -> Index? {\n assert(distance < 0)\n let baseDistance = computeOffsetBackwardBaseDistance(i, distance)\n return makeOffsetIndex(\n from: i,\n baseBound: base.startIndex,\n distance: distance,\n baseDistance: baseDistance,\n limit: limit,\n by: <\n )\n }\n\n // Helper to compute `index(offsetBy:)` index.\n @inlinable\n internal func makeOffsetIndex(\n from i: Index,\n baseBound: Base.Index,\n distance: Int,\n baseDistance: Int,\n limit: Index?,\n by limitFn: (Base.Index, Base.Index) -> Bool\n ) -> Index? {\n let baseIdx = base.index(\n i.baseRange.lowerBound,\n offsetBy: baseDistance,\n limitedBy: baseBound\n )\n\n if let limit = limit {\n if baseIdx == nil {\n // If we passed the bounds while advancing forward, and the limit is the\n // `endIndex`, since the computation on `base` don't take into account\n // the remainder, we have to make sure that passing the bound was\n // because of the distance not just because of a remainder. Special\n // casing is less expensive than always using `count` (which could be\n // O(n) for non-random access collection base) to compute the base\n // distance taking remainder into account.\n if baseDistance > 0 && limit == endIndex {\n if self.distance(from: i, to: limit) < distance {\n return nil\n }\n } else {\n return nil\n }\n }\n\n // Checks for the limit.\n let baseStartIdx = baseIdx ?? baseBound\n if limitFn(baseStartIdx, limit.baseRange.lowerBound) {\n return nil\n }\n }\n\n let baseStartIdx = baseIdx ?? baseBound\n let baseEndIdx =\n base.index(\n baseStartIdx,\n offsetBy: chunkCount,\n limitedBy: base.endIndex\n )\n ?? base.endIndex\n\n return Index(_baseRange: baseStartIdx..<baseEndIdx)\n }\n}\n\nextension Collection {\n /// Returns a collection of subsequences, each with up to the specified\n /// length.\n ///\n /// If the number of elements in the collection is evenly divided by `count`,\n /// then every chunk will have a length equal to `count`. Otherwise, every\n /// chunk but the last will have a length equal to `count`, with the\n /// remaining elements in the last chunk.\n ///\n /// let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n /// for chunk in numbers.chunks(ofCount: 5) {\n /// print(chunk)\n /// }\n /// // [1, 2, 3, 4, 5]\n /// // [6, 7, 8, 9, 10]\n ///\n /// for chunk in numbers.chunks(ofCount: 3) {\n /// print(chunk)\n /// }\n /// // [1, 2, 3]\n /// // [4, 5, 5]\n /// // [7, 8, 9]\n /// // [10]\n ///\n /// - Parameter count: The desired size of each chunk.\n /// - Returns: A collection of consescutive, non-overlapping subseqeunces of\n /// this collection, where each subsequence (except possibly the last) has\n /// the length `count`.\n ///\n /// - Complexity: O(1) if the collection conforms to `RandomAccessCollection`;\n /// otherwise, O(*k*), where *k* is equal to `count`.\n ///\n @inlinable\n public func chunks(ofCount count: Int) -> ChunksOfCountCollection<Self> {\n precondition(count > 0, \"Cannot chunk with count <= 0!\")\n return ChunksOfCountCollection(_base: self, _chunkCount: count)\n }\n}\n\nextension ChunksOfCountCollection.Index: Hashable where Base.Index: Hashable {}\n\nextension ChunksOfCountCollection: LazySequenceProtocol\nwhere Base: LazySequenceProtocol {}\n\nextension ChunksOfCountCollection: LazyCollectionProtocol\nwhere Base: LazyCollectionProtocol {}\n\n//===----------------------------------------------------------------------===//\n// evenlyChunked(in:)\n//===----------------------------------------------------------------------===//\n\nextension Collection {\n /// Returns a collection of evenly divided consecutive subsequences of this\n /// collection.\n ///\n /// This method divides the collection into a given number of evenly sized\n /// chunks. If the length of the collection is not divisible by `count`, the\n /// chunks at the start will be longer than the chunks at the end, like in\n /// this example:\n ///\n /// for chunk in \"Hello, world!\".evenlyChunked(in: 5) {\n /// print(chunk)\n /// }\n /// // \"Hel\"\n /// // \"lo,\"\n /// // \" wo\"\n /// // \"rl\"\n /// // \"d!\"\n ///\n /// If the number passed as `count` is greater than the number of elements in\n /// the collection, the result will include one or more empty subsequences.\n ///\n /// for chunk in \"Hi!\".evenlyChunked(in: 5) {\n /// print(chunk)\n /// }\n /// // \"H\"\n /// // \"i\"\n /// // \"!\"\n /// // \"\"\n /// // \"\"\n ///\n /// - Parameter count: The number of chunks to evenly divide this collection\n /// into. If this collection is non-empty, `count` must be greater than\n /// zero; otherwise, `count` may be zero or greater.\n /// - Returns: A collection of `count` subsequences of this collection,\n /// divided as evenly as possible.\n ///\n /// - Complexity: O(1) if the collection conforms to `RandomAccessCollection`;\n /// otherwise, O(*n*), where *n* is the length of the collection.\n @inlinable\n public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection<Self> {\n precondition(count >= 0, \"Can't divide into a negative number of chunks\")\n precondition(\n count > 0 || isEmpty,\n \"Can't divide a non-empty collection into 0 chunks\"\n )\n return EvenlyChunkedCollection(base: self, numberOfChunks: count)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Split.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// SplitSequence\n//===----------------------------------------------------------------------===//\n\n/// A sequence that lazily splits a base sequence into subsequences separated by\n/// elements that satisfy the given `whereSeparator` predicate.\n///\n/// - Note: This type is the result of\n///\n/// x.split(maxSplits:omittingEmptySubsequences:whereSeparator)\n/// x.split(separator:maxSplits:omittingEmptySubsequences)\n///\n/// where `x` conforms to `LazySequenceProtocol`.\npublic struct SplitSequence<Base: Sequence> {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let isSeparator: (Base.Element) -> Bool\n\n @usableFromInline\n internal let maxSplits: Int\n\n @usableFromInline\n internal let omittingEmptySubsequences: Bool\n\n @inlinable\n internal init(\n base: Base,\n isSeparator: @escaping (Base.Element) -> Bool,\n maxSplits: Int,\n omittingEmptySubsequences: Bool\n ) {\n self.base = base\n self.isSeparator = isSeparator\n self.maxSplits = maxSplits\n self.omittingEmptySubsequences = omittingEmptySubsequences\n }\n}\n\nextension SplitSequence: Sequence {\n public struct Iterator {\n public typealias Element = [Base.Element]\n\n @usableFromInline\n internal var base: Base.Iterator\n\n @usableFromInline\n internal let isSeparator: (Base.Element) -> Bool\n\n @usableFromInline\n internal let maxSplits: Int\n\n @usableFromInline\n internal let omittingEmptySubsequences: Bool\n\n /// The number of splits performed.\n @usableFromInline\n internal var splitCount = 0\n\n /// The number of subsequences returned.\n @usableFromInline\n internal var sequenceLength = 0\n\n @inlinable\n internal init(\n base: Base.Iterator,\n whereSeparator: @escaping (Base.Element) -> Bool,\n maxSplits: Int,\n omittingEmptySubsequences: Bool\n ) {\n self.base = base\n self.isSeparator = whereSeparator\n self.maxSplits = maxSplits\n self.omittingEmptySubsequences = omittingEmptySubsequences\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(\n base: base.makeIterator(),\n whereSeparator: self.isSeparator,\n maxSplits: self.maxSplits,\n omittingEmptySubsequences: self.omittingEmptySubsequences\n )\n }\n}\n\nextension SplitSequence.Iterator: IteratorProtocol {\n @inlinable\n public mutating func next() -> Element? {\n var nextElement = base.next()\n var subsequence: Element = []\n\n // Add the next elements of the base sequence to this subsequence, until we\n // reach a separator, unless we've already split the maximum number of\n // times. In all cases, stop at the end of the base sequence.\n while let currentElement = nextElement {\n if splitCount < maxSplits && isSeparator(currentElement) {\n if omittingEmptySubsequences && subsequence.isEmpty {\n // Keep going if we don't want to return an empty subsequence.\n nextElement = base.next()\n continue\n } else {\n splitCount += 1\n break\n }\n } else {\n subsequence.append(currentElement)\n nextElement = base.next()\n }\n }\n\n // We're done iterating when we've reached the end of the base sequence,\n // and we've either returned the maximum number of subsequences (one more\n // than the number of separators), or the only subsequence left to return is\n // empty and we're omitting those.\n if nextElement == nil\n && (sequenceLength == splitCount + 1\n || omittingEmptySubsequences && subsequence.isEmpty)\n {\n return nil\n } else {\n sequenceLength += 1\n return subsequence\n }\n }\n}\n\nextension SplitSequence: LazySequenceProtocol {}\n\nextension LazySequenceProtocol {\n /// Lazily returns the longest possible subsequences of the sequence, in\n /// order, that don't contain elements satisfying the given predicate.\n ///\n /// The resulting lazy sequence consists of at most `maxSplits + 1`\n /// subsequences. Elements that are used to split the sequence are not\n /// returned as part of any subsequence (except possibly the last one, in the\n /// case where `maxSplits` is less than the number of separators in the\n /// sequence).\n ///\n /// The following examples show the effects of the `maxSplits` and\n /// `omittingEmptySubsequences` parameters when lazily splitting a sequence of\n /// integers using a closure that matches numbers evenly divisible by 3 or 5.\n /// The first use of `split` returns each subsequence that was originally\n /// separated by one or more such numbers.\n ///\n /// let numbers = stride(from: 1, through: 16, by: 1)\n /// for subsequence in numbers.lazy.split(\n /// whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 }\n /// ) {\n /// print(subsequence)\n /// }\n /// /* Prints:\n /// [1, 2]\n /// [4]\n /// [7, 8]\n /// [11]\n /// [13, 14]\n /// [16]\n /// */\n ///\n /// The second example passes `1` for the `maxSplits` parameter, so the\n /// original sequence is split just once, into two subsequences.\n ///\n /// for subsequence in numbers.lazy.split(\n /// maxSplits: 1,\n /// whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 }\n /// ) {\n /// print(subsequence)\n /// }\n /// /* Prints:\n /// [1, 2]\n /// [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\n /// */\n ///\n /// The final example passes `false` for the `omittingEmptySubsequences`\n /// parameter, so the sequence of returned subsequences contains empty\n /// subsequences where numbers evenly divisible by 3 or 5 were repeated.\n ///\n /// for subsequence in numbers.lazy.split(\n /// omittingEmptySubsequences: false,\n /// whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 }\n /// ) {\n /// print(subsequence)\n /// }\n /// /* Prints:\n /// [1, 2]\n /// [4]\n /// []\n /// [7, 8]\n /// []\n /// [11]\n /// [13, 14]\n /// [16]\n /// */\n ///\n /// - Parameters:\n /// - maxSplits: The maximum number of times to split the sequence, or\n /// one less than the number of subsequences to return. If\n /// `maxSplits + 1` subsequences are returned, the last one is a suffix\n /// of the original sequence containing the remaining elements.\n /// `maxSplits` must be greater than or equal to zero. The default value\n /// is `Int.max`.\n /// - omittingEmptySubsequences: If `false`, an empty subsequence is\n /// returned in the result for each pair of consecutive elements\n /// satisfying the `isSeparator` predicate and for each element at the\n /// start or end of the sequence satisfying the `isSeparator`\n /// predicate. The default value is `true`.\n /// - isSeparator: A closure that takes an element as an argument and\n /// returns a Boolean value indicating whether the sequence should be\n /// split at that element.\n /// - Returns: A lazy sequence of subsequences, split from this sequence's\n /// elements.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public func split(\n maxSplits: Int = Int.max,\n omittingEmptySubsequences: Bool = true,\n whereSeparator isSeparator: @escaping (Element) -> Bool\n ) -> SplitSequence<Elements> {\n precondition(maxSplits >= 0, \"Must take zero or more splits\")\n\n return SplitSequence(\n base: elements,\n isSeparator: isSeparator,\n maxSplits: maxSplits,\n omittingEmptySubsequences: omittingEmptySubsequences\n )\n }\n}\n\nextension LazySequenceProtocol where Element: Equatable {\n /// Lazily returns the longest possible subsequences of the sequence, in\n /// order, around elements equal to the given element.\n ///\n /// The resulting lazy sequence consists of at most `maxSplits + 1`\n /// subsequences. Elements that are used to split the sequence are not\n /// returned as part of any subsequence (except possibly the last one, in the\n /// case where `maxSplits` is less than the number of separators in the\n /// sequence).\n ///\n /// The following examples show the effects of the `maxSplits` and\n /// `omittingEmptySubsequences` parameters when splitting a sequence of\n /// integers at each zero (`0`). The first use of `split` returns each\n /// subsequence that was originally separated by one or more zeros.\n ///\n /// let numbers = AnySequence([1, 2, 0, 3, 4, 0, 0, 5])\n /// for subsequence in numbers.lazy.split(separator: 0) {\n /// print(subsequence)\n /// }\n /// /* Prints:\n /// [1, 2]\n /// [3, 4]\n /// [5]\n /// */\n ///\n /// The second example passes `1` for the `maxSplits` parameter, so the\n /// original sequence is split just once, into two subsequences.\n ///\n /// for subsequence in numbers.lazy.split(\n /// separator: 0,\n /// maxSplits: 1\n /// ) {\n /// print(subsequence)\n /// }\n /// /* Prints:\n /// [1, 2]\n /// [3, 4, 0, 0, 5]\n /// */\n ///\n /// The final example passes `false` for the `omittingEmptySubsequences`\n /// parameter, so the sequence of returned subsequences contains empty\n /// subsequences where zeros were repeated.\n ///\n /// for subsequence in numbers.lazy.split(\n /// separator: 0,\n /// omittingEmptySubsequences: false\n /// ) {\n /// print(subsequence)\n /// }\n /// /* Prints:\n /// [1, 2]\n /// [3, 4]\n /// []\n /// [5]\n /// */\n ///\n /// - Parameters:\n /// - separator: The element that should be split upon.\n /// - maxSplits: The maximum number of times to split the sequence, or\n /// one less than the number of subsequences to return. If\n /// `maxSplits + 1` subsequences are returned, the last one is a suffix\n /// of the original sequence containing the remaining elements.\n /// `maxSplits` must be greater than or equal to zero. The default value\n /// is `Int.max`.\n /// - omittingEmptySubsequences: If `false`, an empty subsequence is\n /// returned in the result for each consecutive pair of `separator`\n /// elements in the sequence and for each instance of `separator` at\n /// the start or end of the sequence. If `true`, only nonempty\n /// subsequences are returned. The default value is `true`.\n /// - Returns: A lazy sequence of subsequences, split from this sequence's\n /// elements.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public func split(\n separator: Element,\n maxSplits: Int = Int.max,\n omittingEmptySubsequences: Bool = true\n ) -> SplitSequence<Elements> {\n precondition(maxSplits >= 0, \"Must take zero or more splits\")\n\n return SplitSequence(\n base: elements,\n isSeparator: { $0 == separator },\n maxSplits: maxSplits,\n omittingEmptySubsequences: omittingEmptySubsequences\n )\n }\n}\n\n//===----------------------------------------------------------------------===//\n// SplitCollection\n//===----------------------------------------------------------------------===//\n\n/// A collection that lazily splits a base collection into subsequences\n/// separated by elements that satisfy the given `whereSeparator` predicate.\n///\n/// - Note: This type is the result of\n///\n/// x.split(maxSplits:omittingEmptySubsequences:whereSeparator)\n/// x.split(separator:maxSplits:omittingEmptySubsequences)\n///\n/// where `x` conforms to `LazySequenceProtocol` and `Collection`.\npublic struct SplitCollection<Base: Collection> {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let isSeparator: (Base.Element) -> Bool\n\n @usableFromInline\n internal let maxSplits: Int\n\n @usableFromInline\n internal let omittingEmptySubsequences: Bool\n\n @usableFromInline\n internal var _startIndex: Index\n\n @inlinable\n internal init(\n base: Base,\n isSeparator: @escaping (Base.Element) -> Bool,\n maxSplits: Int,\n omittingEmptySubsequences: Bool\n ) {\n self.base = base\n self.isSeparator = isSeparator\n self.maxSplits = maxSplits\n self.omittingEmptySubsequences = omittingEmptySubsequences\n\n // We precalculate `startIndex`. There are three possibilities:\n // 1. `base` is empty and we're _not_ omitting empty subsequences, in which\n // case the following index describes the sole element of this collection;\n self._startIndex = Index(\n baseRange: base.startIndex..<base.startIndex,\n sequenceLength: 1,\n splitCount: 0\n )\n if base.isEmpty {\n if omittingEmptySubsequences {\n // 2. `base` is empty and we _are_ omitting empty subsequences, so this\n // collection has no elements;\n _startIndex = endIndex\n }\n } else {\n // 3. `base` isn't empty, so we must iterate it to determine the start\n // index.\n _startIndex = indexForSubsequence(\n atOrAfter: base.startIndex,\n sequenceLength: 0,\n splitCount: 0\n )\n }\n }\n}\n\nextension SplitCollection: Collection {\n /// Position of a subsequence in a split collection.\n public struct Index: Comparable {\n /// The range corresponding to the subsequence at this position.\n @usableFromInline\n internal let baseRange: Range<Base.Index>\n\n /// The number of subsequences up to and including this position in the\n /// collection.\n @usableFromInline\n internal let sequenceLength: Int\n\n /// The number splits performed up to and including this position in the\n /// collection.\n @usableFromInline\n internal let splitCount: Int\n\n @inlinable\n internal init(\n baseRange: Range<Base.Index>,\n sequenceLength: Int,\n splitCount: Int\n ) {\n self.baseRange = baseRange\n self.sequenceLength = sequenceLength\n self.splitCount = splitCount\n }\n\n @inlinable\n public static func == (lhs: Index, rhs: Index) -> Bool {\n // `sequenceLength` is equivalent to the index's 1-based position in the\n // collection of indices.\n lhs.sequenceLength == rhs.sequenceLength\n }\n\n @inlinable\n public static func < (lhs: Index, rhs: Index) -> Bool {\n lhs.sequenceLength < rhs.sequenceLength\n }\n }\n\n /// Returns the index of the subsequence starting at or after the given base\n /// collection index.\n @inlinable\n internal func indexForSubsequence(\n atOrAfter lowerBound: Base.Index,\n sequenceLength: Int,\n splitCount: Int\n ) -> Index {\n var start = lowerBound\n // If we don't have any more splits to do (which we'll determine shortly),\n // the end of this subsequence will be the end of the base collection.\n var end = base.endIndex\n\n if splitCount < maxSplits {\n // The non-inclusive end of this subsequence is marked by the next\n // separator, or the end of the base collection.\n end =\n base[start...].firstIndex(where: isSeparator)\n ?? base.endIndex\n\n if base[start..<end].isEmpty {\n if omittingEmptySubsequences {\n // Find the next subsequence of non-separators.\n start =\n base[end...].firstIndex(where: { !isSeparator($0) })\n ?? base.endIndex\n if start == base.endIndex {\n // No non-separators left in the base collection. We're done.\n return endIndex\n }\n end = base[start...].firstIndex(where: isSeparator) ?? base.endIndex\n }\n }\n }\n\n var updatedSplitCount = splitCount\n if end != base.endIndex {\n // This subsequence ends on a separator (and perhaps includes other\n // separators, if we're omitting empty subsequences), so we've performed\n // another split.\n updatedSplitCount += 1\n }\n\n return Index(\n baseRange: start..<end,\n sequenceLength: sequenceLength + 1,\n splitCount: updatedSplitCount\n )\n }\n\n @inlinable\n public var startIndex: Index {\n _startIndex\n }\n\n @inlinable\n public var endIndex: Index {\n Index(\n baseRange: base.endIndex..<base.endIndex,\n sequenceLength: Int.max,\n splitCount: Int.max\n )\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n precondition(i != endIndex, \"Can't advance past endIndex\")\n\n var subsequenceStart = i.baseRange.upperBound\n if subsequenceStart < base.endIndex {\n // If we're not already at the end of the base collection, the previous\n // subsequence ended with a separator. Start searching for the next\n // subsequence at the following element.\n subsequenceStart = base.index(after: i.baseRange.upperBound)\n }\n\n guard subsequenceStart != base.endIndex else {\n if !omittingEmptySubsequences\n && i.sequenceLength < i.splitCount + 1\n {\n // The base collection ended with a separator, so we need to emit one\n // more empty subsequence. This one differs from `endIndex` in its\n // `sequenceLength` (except in an extreme edge case!), which is the\n // sole property tested for equality and comparison.\n return Index(\n baseRange: base.endIndex..<base.endIndex,\n sequenceLength: i.sequenceLength + 1,\n splitCount: i.splitCount\n )\n } else {\n return endIndex\n }\n }\n\n return indexForSubsequence(\n atOrAfter: subsequenceStart,\n sequenceLength: i.sequenceLength,\n splitCount: i.splitCount\n )\n }\n\n @inlinable\n public subscript(position: Index) -> Base.SubSequence {\n precondition(position != endIndex, \"Can't subscript using endIndex\")\n return base[position.baseRange]\n }\n}\n\nextension SplitCollection.Index: Hashable {\n @inlinable\n public func hash(into hasher: inout Hasher) {\n hasher.combine(sequenceLength)\n }\n}\n\nextension SplitCollection: LazyCollectionProtocol {}\n\nextension LazySequenceProtocol where Self: Collection, Elements: Collection {\n /// Lazily returns the longest possible subsequences of the collection, in\n /// order, that don't contain elements satisfying the given predicate.\n ///\n /// The resulting lazy collection consists of at most `maxSplits + 1`\n /// subsequences. Elements that are used to split the collection are not\n /// returned as part of any subsequence (except possibly the last one, in the\n /// case where `maxSplits` is less than the number of separators in the\n /// collection).\n ///\n /// The following examples show the effects of the `maxSplits` and\n /// `omittingEmptySubsequences` parameters when lazily splitting a string\n /// using a closure that matches spaces. The first use of `split` returns each\n /// word that was originally separated by one or more spaces.\n ///\n /// let line = \"BLANCHE: I don't want realism. I want magic!\"\n /// for spaceless in line.lazy.split(whereSeparator: { $0 == \" \" }) {\n /// print(spaceless)\n /// }\n /// // Prints\n /// // BLANCHE:\n /// // I\n /// // don't\n /// // want\n /// // realism.\n /// // I\n /// // want\n /// // magic!\n ///\n /// The second example passes `1` for the `maxSplits` parameter, so the\n /// original string is split just once, into two new strings.\n ///\n /// for spaceless in line.lazy.split(\n /// maxSplits: 1,\n /// whereSeparator: { $0 == \" \" }\n /// ) {\n /// print(spaceless)\n /// }\n /// // Prints\n /// // BLANCHE:\n /// // I don't want realism. I want magic!\n ///\n /// The final example passes `false` for the `omittingEmptySubsequences`\n /// parameter, so the returned array contains empty strings where spaces\n /// were repeated.\n ///\n /// for spaceless in line.lazy.split(\n /// omittingEmptySubsequences: false,\n /// whereSeparator: { $0 == \" \" }\n /// ) {\n /// print(spaceless)\n /// }\n /// // Prints\n /// // BLANCHE:\n /// //\n /// //\n /// // I\n /// // don't\n /// // want\n /// // realism.\n /// // I\n /// // want\n /// // magic!\n ///\n /// - Parameters:\n /// - maxSplits: The maximum number of times to split the collection, or\n /// one less than the number of subsequences to return. If\n /// `maxSplits + 1` subsequences are returned, the last one is a suffix\n /// of the original collection containing the remaining elements.\n /// `maxSplits` must be greater than or equal to zero. The default value\n /// is `Int.max`.\n /// - omittingEmptySubsequences: If `false`, an empty subsequence is\n /// returned in the result for each pair of consecutive elements\n /// satisfying the `isSeparator` predicate and for each element at the\n /// start or end of the collection satisfying the `isSeparator`\n /// predicate. The default value is `true`.\n /// - isSeparator: A closure that takes an element as an argument and\n /// returns a Boolean value indicating whether the collection should be\n /// split at that element.\n /// - Returns: A lazy collection of subsequences, split from this collection's\n /// elements.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public func split(\n maxSplits: Int = Int.max,\n omittingEmptySubsequences: Bool = true,\n whereSeparator isSeparator: @escaping (Element) -> Bool\n ) -> SplitCollection<Elements> {\n precondition(maxSplits >= 0, \"Must take zero or more splits\")\n\n return SplitCollection(\n base: elements,\n isSeparator: isSeparator,\n maxSplits: maxSplits,\n omittingEmptySubsequences: omittingEmptySubsequences\n )\n }\n}\n\nextension LazySequenceProtocol\nwhere Self: Collection, Elements: Collection, Element: Equatable {\n /// Lazily returns the longest possible subsequences of the collection, in\n /// order, around elements equal to the given element.\n ///\n /// The resulting lazy collection consists of at most `maxSplits + 1`\n /// subsequences. Elements that are used to split the collection are not\n /// returned as part of any subsequence (except possibly the last one, in the\n /// case where `maxSplits` is less than the number of separators in the\n /// collection).\n ///\n /// The following examples show the effects of the `maxSplits` and\n /// `omittingEmptySubsequences` parameters when splitting a string at each\n /// space character (\" \"). The first use of `split` returns each word that\n /// was originally separated by one or more spaces.\n ///\n /// let line = \"BLANCHE: I don't want realism. I want magic!\"\n /// for spaceless in line.lazy.split(separator: \" \") {\n /// print(spaceless)\n /// }\n /// // Prints\n /// // BLANCHE:\n /// // I\n /// // don't\n /// // want\n /// // realism.\n /// // I\n /// // want\n /// // magic!\n ///\n /// The second example passes `1` for the `maxSplits` parameter, so the\n /// original string is split just once, into two new strings.\n ///\n /// for spaceless in line.lazy.split(separator: \" \", maxSplits: 1) {\n /// print(spaceless)\n /// }\n /// // Prints\n /// // BLANCHE:\n /// // I don't want realism. I want magic!\n ///\n /// The final example passes `false` for the `omittingEmptySubsequences`\n /// parameter, so the returned array contains empty strings where spaces\n /// were repeated.\n ///\n /// for spaceless in line.lazy.split(\n /// separator: \" \",\n /// omittingEmptySubsequences: false\n /// ) {\n /// print(spaceless)\n /// }\n /// // Prints\n /// // BLANCHE:\n /// //\n /// //\n /// // I\n /// // don't\n /// // want\n /// // realism.\n /// // I\n /// // want\n /// // magic!\n ///\n /// - Parameters:\n /// - separator: The element that should be split upon.\n /// - maxSplits: The maximum number of times to split the collection, or\n /// one less than the number of subsequences to return. If\n /// `maxSplits + 1` subsequences are returned, the last one is a suffix\n /// of the original collection containing the remaining elements.\n /// `maxSplits` must be greater than or equal to zero. The default value\n /// is `Int.max`.\n /// - omittingEmptySubsequences: If `false`, an empty subsequence is\n /// returned in the result for each consecutive pair of `separator`\n /// elements in the collection and for each instance of `separator` at\n /// the start or end of the collection. If `true`, only nonempty\n /// subsequences are returned. The default value is `true`.\n /// - Returns: A lazy collection of subsequences split from this collection's\n /// elements.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public func split(\n separator: Element,\n maxSplits: Int = Int.max,\n omittingEmptySubsequences: Bool = true\n ) -> SplitCollection<Elements> {\n precondition(maxSplits >= 0, \"Must take zero or more splits\")\n\n return SplitCollection(\n base: elements,\n isSeparator: { $0 == separator },\n maxSplits: maxSplits,\n omittingEmptySubsequences: omittingEmptySubsequences\n )\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Trim.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// trimmingPrefix(while:)\n//===----------------------------------------------------------------------===//\n\nextension Collection {\n /// Returns a `SubSequence` formed by discarding all elements at the start of\n /// the collection that satisfy the given predicate.\n ///\n /// This example uses `trimmingPrefix(while:)` to get a substring without the\n /// white space at the beginning of the string:\n ///\n /// let myString = \" hello, world \"\n /// print(myString.trimmingPrefix(while: \\.isWhitespace))\n /// // Prints \"hello, world \"\n ///\n /// - Parameter predicate: A closure that determines if the element should be\n /// omitted from the result.\n /// - Returns: A subsequence of this collection, starting at the first element\n /// for which `predicate` returns `false`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of this collection.\n @inlinable\n public func trimmingPrefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> SubSequence {\n let start = try endOfPrefix(while: predicate)\n return self[start..<endIndex]\n }\n}\n\n//===----------------------------------------------------------------------===//\n// trimPrefix(while:)\n//===----------------------------------------------------------------------===//\n\nextension Collection where Self: RangeReplaceableCollection {\n /// Mutates the collection by discarding all elements at the start that\n /// satisfy the given predicate.\n ///\n /// This example uses `trimPrefix(while:)` to remove the white space at the\n /// beginning of the string:\n ///\n /// let myString = \" hello, world \"\n /// myString.trimPrefix(while: \\.isWhitespace)\n /// print(myString)\n /// // Prints \"hello, world \"\n ///\n /// - Parameter predicate: A closure that determines if the element should be\n /// removed from the result.\n ///\n /// - Complexity: O(*n*), where *n* is the length of this collection.\n @inlinable\n @_disfavoredOverload\n public mutating func trimPrefix(\n while predicate: (Element) throws -> Bool\n ) rethrows {\n let startOfResult = try endOfPrefix(while: predicate)\n removeSubrange(startIndex..<startOfResult)\n }\n}\n\nextension Collection where Self == Self.SubSequence {\n /// Mutates the collection by discarding all elements at the start that\n /// satisfy the given predicate.\n ///\n /// This example uses `trimPrefix(while:)` to remove the white space at the\n /// beginning of the string:\n ///\n /// let myString = \" hello, world \"\n /// myString.trimPrefix(while: \\.isWhitespace)\n /// print(myString) // \"hello, world \"\n ///\n /// - Parameters predicate: A closure that determines if the element should\n /// be removed from the string.\n ///\n /// - Complexity: O(*n*), where *n* is the length of this collection.\n @inlinable\n public mutating func trimPrefix(\n while predicate: (Element) throws -> Bool\n ) rethrows {\n self = try trimmingPrefix(while: predicate)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// trimming(while:) / trimmingSuffix(while:)\n//===----------------------------------------------------------------------===//\n\nextension BidirectionalCollection {\n /// Returns a `SubSequence` formed by discarding all elements at the start and\n /// end of the collection that satisfy the given predicate.\n ///\n /// This example uses `trimming(while:)` to get a substring without the white\n /// space at the beginning and end of the string:\n ///\n /// let myString = \" hello, world \"\n /// print(myString.trimming(while: \\.isWhitespace))\n /// // Prints \"hello, world\"\n ///\n /// - Parameter predicate: A closure that determines if the element should be\n /// omitted from the resulting slice.\n /// - Returns: A subsequence of this collection, starting at the first element\n /// for which `predicate` returns `false` and ending at the last element for\n /// which `predicate` returns `true`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of this collection.\n @inlinable\n public func trimming(\n while predicate: (Element) throws -> Bool\n ) rethrows -> SubSequence {\n try trimmingPrefix(while: predicate).trimmingSuffix(while: predicate)\n }\n\n /// Returns a `SubSequence` formed by discarding all elements at the end of\n /// the collection that satisfy the given predicate.\n ///\n /// This example uses `trimmingSuffix(while:)` to get a substring without the\n /// white space at the end of the string:\n ///\n /// let myString = \" hello, world \"\n /// print(myString.trimmingSuffix(while: \\.isWhitespace)) // \" hello, world\"\n ///\n /// - Parameter predicate: A closure that determines if the element should be\n /// omitted from the resulting slice.\n /// - Returns: A subsequence of this collection, ending at the last element\n /// for which `predicate` returns `true`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of this collection.\n @inlinable\n public func trimmingSuffix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> SubSequence {\n let end = try startOfSuffix(while: predicate)\n return self[startIndex..<end]\n }\n}\n\n//===----------------------------------------------------------------------===//\n// trim(while:) / trimSuffix(while:)\n//===----------------------------------------------------------------------===//\n\nextension BidirectionalCollection where Self: RangeReplaceableCollection {\n /// Mutates a `BidirectionalCollection` by discarding all elements at the\n /// start and at the end of it that satisfy the given predicate.\n ///\n /// This example uses `trim(while:)` to remove the white space at the\n /// beginning of the string:\n ///\n /// let myString = \" hello, world \"\n /// myString.trim(while: \\.isWhitespace)\n /// print(myString) // \"hello, world\"\n ///\n /// - Parameter predicate: A closure that determines if the element should be\n /// removed from the string.\n ///\n /// - Complexity: O(*n*), where *n* is the length of this collection.\n @inlinable\n @_disfavoredOverload\n public mutating func trim(\n while predicate: (Element) throws -> Bool\n ) rethrows {\n try trimSuffix(while: predicate)\n try trimPrefix(while: predicate)\n }\n\n /// Mutates a `BidirectionalCollection` by discarding all elements at the end\n /// of it that satisfy the given predicate.\n ///\n /// This example uses `trimSuffix(while:)` to remove the white space at the\n /// beginning of the string:\n ///\n /// let myString = \" hello, world \"\n /// myString.trimSuffix(while: \\.isWhitespace)\n /// print(myString) // \" hello, world\"\n ///\n /// - Parameter predicate: A closure that determines if the element should be\n /// removed from the string.\n ///\n /// - Complexity: O(*n*), where *n* is the length of this collection.\n @inlinable\n @_disfavoredOverload\n public mutating func trimSuffix(\n while predicate: (Element) throws -> Bool\n ) rethrows {\n let endOfResult = try startOfSuffix(while: predicate)\n removeSubrange(endOfResult..<endIndex)\n }\n}\n\nextension BidirectionalCollection where Self == Self.SubSequence {\n /// Mutates a `BidirectionalCollection` by discarding all elements at the\n /// start and at the end of it that satisfy the given predicate.\n ///\n /// This example uses `trim(while:)` to remove the white space at the\n /// beginning of the string:\n ///\n /// let myString = \" hello, world \"\n /// myString.trim(while: \\.isWhitespace)\n /// print(myString) // \"hello, world\"\n ///\n /// - Parameter predicate: A closure that determines if the element should be\n /// removed from the string.\n ///\n /// - Complexity: O(*n*), where *n* is the length of this collection.\n @inlinable\n public mutating func trim(\n while predicate: (Element) throws -> Bool\n ) rethrows {\n self = try trimming(while: predicate)\n }\n\n /// Mutates a `BidirectionalCollection` by discarding all elements at the end\n /// of it that satisfy the given predicate.\n ///\n /// This example uses `trimSuffix(while:)` to remove the white space at the\n /// beginning of the string:\n ///\n /// let myString = \" hello, world \"\n /// myString.trimSuffix(while: \\.isWhitespace)\n /// print(myString) // \" hello, world\"\n ///\n /// - Parameter predicate: A closure that determines if the element should be\n /// removed from the string.\n ///\n /// - Complexity: O(*n*), where *n* is the length of this collection.\n @inlinable\n public mutating func trimSuffix(\n while predicate: (Element) throws -> Bool\n ) rethrows {\n self = try trimmingSuffix(while: predicate)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Permutations.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// nextPermutation()\n//===----------------------------------------------------------------------===//\n\nextension MutableCollection\nwhere Self: BidirectionalCollection, Element: Comparable {\n /// Permutes this collection's elements through all the lexical orderings.\n ///\n /// Call `nextPermutation()` repeatedly starting with the collection in sorted\n /// order. When the full cycle of all permutations has been completed, the\n /// collection will be back in sorted order and this method will return\n /// `false`.\n ///\n /// - Returns: A Boolean value indicating whether the collection still has\n /// remaining permutations. When this method returns `false`, the collection\n /// is in ascending order according to `areInIncreasingOrder`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n internal mutating func nextPermutation(upperBound: Index? = nil) -> Bool {\n // Ensure we have > 1 element in the collection.\n guard !isEmpty else { return false }\n var i = index(before: endIndex)\n if i == startIndex { return false }\n\n let upperBound = upperBound ?? endIndex\n\n while true {\n let ip1 = i\n formIndex(before: &i)\n\n // Find the last ascending pair (ie. ..., a, b, ... where a < b)\n if self[i] < self[ip1] {\n // Find the last element greater than self[i]\n // swift-format-ignore: NeverForceUnwrap\n // This is _always_ at most `ip1` due to if statement above\n let j = lastIndex(where: { self[i] < $0 })!\n\n // At this point we have something like this:\n // 0, 1, 4, 3, 2\n // ^ ^\n // i j\n swapAt(i, j)\n self.reverse(subrange: ip1..<endIndex)\n\n // Only return if we've made a change within ..<upperBound region\n if i < upperBound {\n return true\n } else {\n i = index(before: endIndex)\n continue\n }\n }\n\n if i == startIndex {\n self.reverse()\n return false\n }\n }\n }\n}\n\n//===----------------------------------------------------------------------===//\n// struct Permutations<Base>\n//===----------------------------------------------------------------------===//\n\n/// A sequence of all the permutations of a collection's elements.\npublic struct PermutationsSequence<Base: Collection> {\n /// The base collection to iterate over for permutations.\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let baseCount: Int\n\n /// The range of accepted sizes of permutations.\n ///\n /// - Note: This may be empty if the attempted range entirely exceeds the\n /// bounds of the size of the `base` collection.\n @usableFromInline\n internal let kRange: Range<Int>\n\n /// Initializes a `PermutationsSequence` for all permutations of `base` of\n /// size `k`.\n ///\n /// - Parameters:\n /// - base: The collection to iterate over for permutations\n /// - k: The expected size of each permutation, or `nil` (default) to\n /// iterate over all permutations of the same size as the base collection.\n @inlinable\n internal init(_ base: Base, k: Int? = nil) {\n let kRange: ClosedRange<Int>?\n if let countToChoose = k {\n kRange = countToChoose...countToChoose\n } else {\n kRange = nil\n }\n self.init(base, kRange: kRange)\n }\n\n /// Initializes a `PermutationsSequence` for all combinations of `base` of\n /// sizes within a given range.\n ///\n /// - Parameters:\n /// - base: The collection to iterate over for permutations.\n /// - kRange: The range of accepted sizes of permutations, or `nil` to\n /// iterate over all permutations of the same size as the base collection.\n @inlinable\n internal init<R: RangeExpression>(\n _ base: Base,\n kRange: R?\n ) where R.Bound == Int {\n self.base = base\n let baseCount = base.count\n self.baseCount = baseCount\n let upperBound = baseCount + 1\n self.kRange =\n kRange?.relative(to: 0 ..< .max)\n .clamped(to: 0..<upperBound) ?? baseCount..<upperBound\n }\n\n /// The total number of permutations.\n @inlinable\n public var count: Int {\n kRange.map {\n stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *)\n }.reduce(0, +)\n }\n}\n\nextension PermutationsSequence: Sequence {\n /// The iterator for a `PermutationsSequence` instance.\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let baseCount: Int\n\n /// The current range of accepted sizes of permutations.\n /// - Note: The range is contracted until empty while iterating over\n /// permutations of different sizes. When the range is empty, iteration is\n /// finished.\n @usableFromInline\n internal var kRange: Range<Int>\n\n /// Whether or not iteration is finished (`kRange` is empty).\n @inlinable\n internal var isFinished: Bool {\n kRange.isEmpty\n }\n\n @usableFromInline\n internal var indexes: [Base.Index]\n\n @inlinable\n internal init(_ permutations: PermutationsSequence) {\n self.base = permutations.base\n self.baseCount = permutations.baseCount\n self.kRange = permutations.kRange\n self.indexes = Array(permutations.base.indices)\n }\n\n /// Advances the `indexes` array such that the first `countToChoose`\n /// elements contain the next lexicographic ordering of elements.\n ///\n /// Uses the SEP(n,k) algorithm, as described in:\n /// https://alistairisrael.wordpress.com/2009/09/22/simple-efficient-pnk-algorithm/\n ///\n /// - Returns: A Boolean value indicating whether `indexes` still has\n /// remaining permutations. When this method returns `false`, `indexes`\n /// is in ascending order.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n internal mutating func nextState() -> Bool {\n let countToChoose = self.kRange.lowerBound\n let edge = countToChoose - 1\n\n // Find first index greater than the one at `edge`.\n if let i = indexes[countToChoose...]\n .firstIndex(where: { indexes[edge] < $0 })\n {\n indexes.swapAt(edge, i)\n } else {\n indexes.reverse(subrange: countToChoose..<indexes.endIndex)\n\n // Find last increasing pair below `edge`.\n // TODO: This could be indexes[..<edge].adjacentPairs().lastIndex(where: ...)\n var lastAscent = edge - 1\n while lastAscent >= 0 && indexes[lastAscent] >= indexes[lastAscent + 1]\n {\n lastAscent -= 1\n }\n if lastAscent < 0 {\n return false\n }\n\n // Find rightmost index less than that at `lastAscent`.\n if let i = indexes[lastAscent...]\n .lastIndex(where: { indexes[lastAscent] < $0 })\n {\n indexes.swapAt(lastAscent, i)\n }\n indexes.reverse(subrange: (lastAscent + 1)..<indexes.endIndex)\n }\n\n return true\n }\n\n @inlinable\n public mutating func next() -> [Base.Element]? {\n guard !isFinished else { return nil }\n\n /// Advances `kRange` by incrementing its `lowerBound` until the range is\n /// empty, when iteration is finished.\n func advanceKRange() {\n kRange.removeFirst()\n indexes = Array(base.indices)\n }\n\n let countToChoose = self.kRange.lowerBound\n if countToChoose == 0 {\n defer {\n advanceKRange()\n }\n return []\n }\n\n let permutesFullCollection = (countToChoose == baseCount)\n if permutesFullCollection {\n // If we're permuting the full collection, each iteration is just a\n // call to `nextPermutation` on `indexes`.\n defer {\n let hasMorePermutations = indexes.nextPermutation()\n if !hasMorePermutations {\n advanceKRange()\n }\n }\n return indexes.map { base[$0] }\n } else {\n // Otherwise, return the items at the first `countToChoose` indices and\n // advance the state.\n defer {\n let hasMorePermutations = nextState()\n if !hasMorePermutations {\n advanceKRange()\n }\n }\n return indexes.prefix(countToChoose).map { base[$0] }\n }\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(self)\n }\n}\n\nextension PermutationsSequence: LazySequenceProtocol\nwhere Base: LazySequenceProtocol {}\n\n//===----------------------------------------------------------------------===//\n// permutations(ofCount:)\n//===----------------------------------------------------------------------===//\n\nextension Collection {\n /// Returns a collection of the permutations of this collection with lengths\n /// in the specified range.\n ///\n /// This example prints the different permutations of one to two elements from\n /// an array of three names:\n ///\n /// let names = [\"Alex\", \"Celeste\", \"Davide\"]\n /// for perm in names.permutations(ofCount: 1...2) {\n /// print(perm.joined(separator: \", \"))\n /// }\n /// // Alex\n /// // Celeste\n /// // Davide\n /// // Alex, Celeste\n /// // Alex, Davide\n /// // Celeste, Alex\n /// // Celeste, Davide\n /// // Davide, Alex\n /// // Davide, Celeste\n ///\n /// This example prints _all_ the permutations (including an empty array) from\n /// an array of numbers:\n ///\n /// let numbers = [10, 20, 30]\n /// for perm in numbers.permutations(ofCount: 0...) {\n /// print(perm)\n /// }\n /// // []\n /// // [10]\n /// // [20]\n /// // [30]\n /// // [10, 20]\n /// // [10, 30]\n /// // [20, 10]\n /// // [20, 30]\n /// // [30, 10]\n /// // [30, 20]\n /// // [10, 20, 30]\n /// // [10, 30, 20]\n /// // [20, 10, 30]\n /// // [20, 30, 10]\n /// // [30, 10, 20]\n /// // [30, 20, 10]\n ///\n /// The returned permutations are in ascending order by length, and then\n /// lexicographically within each group of the same length.\n ///\n /// - Parameter kRange: A range of the number of elements to include in each\n /// permutation. `kRange` can be any integer range expression, and is\n /// clamped to the number of elements in this collection. Passing a range\n /// covering sizes greater than the number of elements in this collection\n /// results in an empty sequence.\n /// - Returns: A sequence of the permutations of this collection's elements,\n /// for all sizes in `kRange`, from smallest to largest.\n ///\n /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*\n /// is the number of elements in the base collection, since\n /// `PermutationsSequence` accesses the `count` of the base collection.\n @inlinable\n public func permutations<R: RangeExpression>(\n ofCount kRange: R\n ) -> PermutationsSequence<Self> where R.Bound == Int {\n PermutationsSequence(self, kRange: kRange)\n }\n\n /// Returns a collection of the permutations of this collection of the\n /// specified length.\n ///\n /// This example prints the different permutations of two elements from an\n /// array of three names:\n ///\n /// let names = [\"Alex\", \"Celeste\", \"Davide\"]\n /// for perm in names.permutations(ofCount: 2) {\n /// print(perm.joined(separator: \", \"))\n /// }\n /// // Alex, Celeste\n /// // Alex, Davide\n /// // Celeste, Alex\n /// // Celeste, Davide\n /// // Davide, Alex\n /// // Davide, Celeste\n ///\n /// The permutations present the elements in increasing lexicographic order\n /// of the collection's original ordering (rather than the order of the\n /// elements themselves). The first permutation will always consist of\n /// elements in their original order, and the last will have the elements in\n /// the reverse of their original order.\n ///\n /// Values that are repeated in the original collection are always treated as\n /// separate values in the resulting permutations:\n ///\n /// let numbers = [20, 10, 10]\n /// for perm in numbers.permutations() {\n /// print(perm)\n /// }\n /// // [20, 10, 10]\n /// // [20, 10, 10]\n /// // [10, 20, 10]\n /// // [10, 10, 20]\n /// // [10, 20, 10]\n /// // [10, 10, 20]\n ///\n /// If `k` is zero, the resulting sequence has exactly one element, an\n /// empty array. If `k` is greater than the number of elements in this\n /// sequence, the resulting sequence has no elements.\n ///\n /// - Parameter k: The number of elements to include in each permutation.\n /// If `k` is `nil`, the resulting sequence represents permutations of this\n /// entire collection. If `k` is greater than the number of elements in\n /// this collection, the resulting sequence is empty.\n /// - Returns: A sequence of the permutations of this collection's elements.\n ///\n /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*\n /// is the number of elements in the base collection, since\n /// `PermutationsSequence` accesses the `count` of the base collection.\n @inlinable\n public func permutations(\n ofCount k: Int? = nil\n ) -> PermutationsSequence<Self> {\n precondition(\n k ?? 0 >= 0,\n \"Can't have permutations with a negative number of elements.\")\n return PermutationsSequence(self, k: k)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// uniquePermutations()\n//===----------------------------------------------------------------------===//\n\n/// A sequence of the unique permutations of the elements of a sequence or\n/// collection.\n///\n/// To create a `UniquePermutationsSequence` instance, call one of the\n/// `uniquePermutations` methods on your collection.\npublic struct UniquePermutationsSequence<Base: Collection> {\n /// The base collection to iterate over for permutations.\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal var indexes: [Base.Index]\n\n @usableFromInline\n internal let kRange: Range<Int>\n}\n\nextension UniquePermutationsSequence where Base.Element: Hashable {\n @inlinable\n internal static func _indexes(_ base: Base) -> [Base.Index] {\n let firstIndexesAndCountsByElement = Dictionary(\n base.indices.lazy.map { (base[$0], ($0, 1)) },\n uniquingKeysWith: { indexAndCount, _ in\n (indexAndCount.0, indexAndCount.1 + 1)\n })\n\n return firstIndexesAndCountsByElement\n .values.sorted(by: { $0.0 < $1.0 })\n .flatMap { index, count in repeatElement(index, count: count) }\n }\n\n @inlinable\n internal init(_ elements: Base) {\n self.indexes = Self._indexes(elements)\n self.base = elements\n self.kRange = self.indexes.count..<(self.indexes.count + 1)\n }\n\n @inlinable\n internal init<R: RangeExpression>(_ base: Base, _ range: R)\n where R.Bound == Int {\n self.indexes = Self._indexes(base)\n self.base = base\n\n let upperBound = self.indexes.count + 1\n self.kRange = range.relative(to: 0 ..< .max)\n .clamped(to: 0..<upperBound)\n }\n}\n\nextension UniquePermutationsSequence: Sequence {\n /// The iterator for a `UniquePermutationsSequence` instance.\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal var indexes: [Base.Index]\n\n @usableFromInline\n internal var lengths: Range<Int>\n\n @usableFromInline\n internal var initial = true\n\n @inlinable\n internal init(_ elements: Base, indexes: [Base.Index], lengths: Range<Int>)\n {\n self.base = elements\n self.indexes = indexes\n self.lengths = lengths\n }\n\n @inlinable\n public mutating func next() -> [Base.Element]? {\n // In the end case, `lengths` is an empty range.\n if lengths.isEmpty {\n return nil\n }\n\n // The first iteration must produce the original sorted array, before any\n // permutations. We skip the permutation the first time so that we can\n // always mutate the array _before_ returning a slice, which avoids\n // copying when possible.\n if initial {\n initial = false\n return indexes[..<lengths.lowerBound].map { base[$0] }\n }\n\n if !indexes.nextPermutation(upperBound: lengths.lowerBound) {\n lengths.removeFirst()\n\n if lengths.isEmpty {\n return nil\n }\n }\n\n return indexes[..<lengths.lowerBound].map { base[$0] }\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(base, indexes: indexes, lengths: kRange)\n }\n}\n\nextension UniquePermutationsSequence: LazySequenceProtocol\nwhere Base: LazySequenceProtocol {}\n\nextension Collection where Element: Hashable {\n /// Returns a sequence of the unique permutations of this sequence of the\n /// specified length.\n ///\n /// Use this method to iterate over the unique permutations of a sequence\n /// with repeating elements. This example prints every unique two-element\n /// permutation of an array of numbers:\n ///\n /// let numbers = [1, 1, 2]\n /// for perm in numbers.uniquePermutations(ofCount: 2) {\n /// print(perm)\n /// }\n /// // [1, 1]\n /// // [1, 2]\n /// // [2, 1]\n ///\n /// By contrast, the `permutations(ofCount:)` method permutes a collection's\n /// elements by position, and can include permutations with equal elements\n /// in each permutation:\n ///\n /// for perm in numbers.permutations(ofCount: 2)\n /// print(perm)\n /// }\n /// // [1, 1]\n /// // [1, 1]\n /// // [1, 2]\n /// // [1, 2]\n /// // [2, 1]\n /// // [2, 1]\n ///\n /// The returned permutations are in lexicographically sorted order.\n ///\n /// - Parameter k: The number of elements to include in each permutation.\n /// If `k` is `nil`, the resulting sequence represents permutations of this\n /// entire collection. If `k` is greater than the number of elements in\n /// this collection, the resulting sequence is empty.\n /// - Returns: A sequence of the unique permutations of this collection's\n /// elements.\n ///\n /// - Complexity: O(*n*), where *n* is the number of elements in this\n /// collection.\n @inlinable\n public func uniquePermutations(ofCount k: Int? = nil)\n -> UniquePermutationsSequence<Self>\n {\n guard let k = k else {\n return UniquePermutationsSequence(self)\n }\n return UniquePermutationsSequence(self, k..<(k + 1))\n }\n\n /// Returns a collection of the unique permutations of this sequence with\n /// lengths in the specified range.\n ///\n /// Use this method to iterate over the unique permutations of a sequence\n /// with repeating elements. This example prints every unique permutation\n /// of an array of numbers with lengths through 2 elements:\n ///\n /// let numbers = [1, 1, 2]\n /// for perm in numbers.uniquePermutations(ofCount: ...2) {\n /// print(perm)\n /// }\n /// // []\n /// // [1]\n /// // [2]\n /// // [1, 1]\n /// // [1, 2]\n /// // [2, 1]\n ///\n /// The returned permutations are in ascending order by length, and then\n /// lexicographically within each group of the same length.\n ///\n /// - Parameter kRange: A range of the number of elements to include in each\n /// permutation. `kRange` can be any integer range expression, and is\n /// clamped to the number of elements in this collection. Passing a range\n /// covering sizes greater than the number of elements in this collection\n /// results in an empty sequence.\n /// - Returns: A sequence of the unique permutations of this collection's\n /// elements, for all sizes in `kRange`, from smallest to largest.\n ///\n /// - Complexity: O(*n*), where *n* is the number of elements in this\n /// collection.\n @inlinable\n public func uniquePermutations<R: RangeExpression>(\n ofCount kRange: R\n ) -> UniquePermutationsSequence<Self> where R.Bound == Int {\n UniquePermutationsSequence(self, kRange)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Unique.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// A sequence wrapper that leaves out duplicate elements of a base sequence.\npublic struct UniquedSequence<Base: Sequence, Subject: Hashable> {\n /// The base collection.\n @usableFromInline\n internal let base: Base\n\n /// The projection function.\n @usableFromInline\n internal let projection: (Base.Element) -> Subject\n\n @usableFromInline\n internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {\n self.base = base\n self.projection = projection\n }\n}\n\nextension UniquedSequence: Sequence {\n /// The iterator for a `UniquedSequence` instance.\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal var base: Base.Iterator\n\n @usableFromInline\n internal let projection: (Base.Element) -> Subject\n\n @usableFromInline\n internal var seen: Set<Subject> = []\n\n @usableFromInline\n internal init(\n base: Base.Iterator,\n projection: @escaping (Base.Element) -> Subject\n ) {\n self.base = base\n self.projection = projection\n }\n\n @inlinable\n public mutating func next() -> Base.Element? {\n while let element = base.next() {\n if seen.insert(projection(element)).inserted {\n return element\n }\n }\n return nil\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(base: base.makeIterator(), projection: projection)\n }\n}\n\nextension UniquedSequence: LazySequenceProtocol\nwhere Base: LazySequenceProtocol {}\n\n//===----------------------------------------------------------------------===//\n// uniqued()\n//===----------------------------------------------------------------------===//\n\nextension Sequence where Element: Hashable {\n /// Returns a sequence with only the unique elements of this sequence, in the\n /// order of the first occurrence of each unique element.\n ///\n /// let animals = [\"dog\", \"pig\", \"cat\", \"ox\", \"dog\", \"cat\"]\n /// let uniqued = animals.uniqued()\n /// print(Array(uniqued))\n /// // Prints '[\"dog\", \"pig\", \"cat\", \"ox\"]'\n ///\n /// - Returns: A sequence with only the unique elements of this sequence.\n /// .\n /// - Complexity: O(1).\n @inlinable\n public func uniqued() -> UniquedSequence<Self, Element> {\n UniquedSequence(base: self, projection: { $0 })\n }\n}\n\nextension Sequence {\n /// Returns an array with the unique elements of this sequence (as determined\n /// by the given projection), in the order of the first occurrence of each\n /// unique element.\n ///\n /// This example finds the elements of the `animals` array with unique\n /// first characters:\n ///\n /// let animals = [\"dog\", \"pig\", \"cat\", \"ox\", \"cow\", \"owl\"]\n /// let uniqued = animals.uniqued(on: { $0.first })\n /// print(uniqued)\n /// // Prints '[\"dog\", \"pig\", \"cat\", \"ox\"]'\n ///\n /// - Parameter projection: A closure that transforms an element into the\n /// value to use for uniqueness. If `projection` returns the same value for\n /// two different elements, the second element will be excluded from the\n /// resulting array.\n ///\n /// - Returns: An array with only the unique elements of this sequence, as\n /// determined by the result of `projection` for each element.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public func uniqued<Subject: Hashable>(\n on projection: (Element) throws -> Subject\n ) rethrows -> [Element] {\n var seen: Set<Subject> = []\n var result: [Element] = []\n for element in self {\n if seen.insert(try projection(element)).inserted {\n result.append(element)\n }\n }\n return result\n }\n}\n\n//===----------------------------------------------------------------------===//\n// lazy.uniqued()\n//===----------------------------------------------------------------------===//\n\nextension LazySequenceProtocol {\n /// Returns a lazy sequence with the unique elements of this sequence (as\n /// determined by the given projection), in the order of the first occurrence\n /// of each unique element.\n ///\n /// - Complexity: O(1).\n @inlinable\n public func uniqued<Subject: Hashable>(\n on projection: @escaping (Element) -> Subject\n ) -> UniquedSequence<Self, Subject> {\n UniquedSequence(base: self, projection: projection)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Chain.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// A concatenation of two sequences with the same element type.\npublic struct Chain2Sequence<Base1: Sequence, Base2: Sequence>\nwhere Base1.Element == Base2.Element {\n /// The first sequence in this chain.\n @usableFromInline\n internal let base1: Base1\n\n /// The second sequence in this chain.\n @usableFromInline\n internal let base2: Base2\n\n @inlinable\n internal init(base1: Base1, base2: Base2) {\n self.base1 = base1\n self.base2 = base2\n }\n}\n\nextension Chain2Sequence: Sequence {\n /// The iterator for a `Chain2Sequence` instance.\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal var iterator1: Base1.Iterator\n\n @usableFromInline\n internal var iterator2: Base2.Iterator\n\n @inlinable\n internal init(_ concatenation: Chain2Sequence) {\n iterator1 = concatenation.base1.makeIterator()\n iterator2 = concatenation.base2.makeIterator()\n }\n\n @inlinable\n public mutating func next() -> Base1.Element? {\n iterator1.next() ?? iterator2.next()\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(self)\n }\n}\n\nextension Chain2Sequence: Collection\nwhere Base1: Collection, Base2: Collection {\n /// A position in a `Chain2Sequence` instance.\n public struct Index: Comparable {\n // The internal index representation, which can either be an index of the\n // first collection or the second. The `endIndex` of the first collection\n // is not to be used as a value - iterating over indices should go straight\n // from the penultimate index of the first collection to the start of the\n // second.\n @usableFromInline\n internal enum Representation: Equatable {\n case first(Base1.Index)\n case second(Base2.Index)\n }\n\n @usableFromInline\n internal let position: Representation\n\n /// Creates a new index into the first underlying collection.\n @inlinable\n internal init(first i: Base1.Index) {\n position = .first(i)\n }\n\n /// Creates a new index into the second underlying collection.\n @inlinable\n internal init(second i: Base2.Index) {\n position = .second(i)\n }\n\n @inlinable\n public static func < (lhs: Index, rhs: Index) -> Bool {\n switch (lhs.position, rhs.position) {\n case (.first, .second):\n return true\n case (.second, .first):\n return false\n case (.first(let l), .first(let r)):\n return l < r\n case (.second(let l), .second(let r)):\n return l < r\n }\n }\n }\n\n /// Converts an index of `Base1` to the corresponding `Index` by mapping\n /// `base1.endIndex` to `base2.startIndex`.\n @inlinable\n internal func normalizeIndex(_ i: Base1.Index) -> Index {\n i == base1.endIndex ? Index(second: base2.startIndex) : Index(first: i)\n }\n\n @inlinable\n public var startIndex: Index {\n // if `base1` is empty, this will return `base2.startIndex` - if `base2` is\n // also empty, this will correctly equal `base2.endIndex`\n normalizeIndex(base1.startIndex)\n }\n\n @inlinable\n public var endIndex: Index {\n Index(second: base2.endIndex)\n }\n\n @inlinable\n public subscript(i: Index) -> Base1.Element {\n switch i.position {\n case .first(let i):\n return base1[i]\n case .second(let i):\n return base2[i]\n }\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n switch i.position {\n case .first(let i):\n assert(i != base1.endIndex)\n return normalizeIndex(base1.index(after: i))\n case .second(let i):\n return Index(second: base2.index(after: i))\n }\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n guard distance != 0 else { return i }\n\n return distance > 0\n ? offsetForward(i, by: distance)\n : offsetBackward(i, by: -distance)\n }\n\n @inlinable\n public func index(\n _ i: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n if distance >= 0 {\n return limit >= i\n ? offsetForward(i, by: distance, limitedBy: limit)\n : offsetForward(i, by: distance)\n } else {\n return limit <= i\n ? offsetBackward(i, by: -distance, limitedBy: limit)\n : offsetBackward(i, by: -distance)\n }\n }\n\n @inlinable\n internal func offsetForward(_ i: Index, by distance: Int) -> Index {\n guard let index = offsetForward(i, by: distance, limitedBy: endIndex)\n else { fatalError(\"Index is out of bounds\") }\n return index\n }\n\n @inlinable\n internal func offsetBackward(_ i: Index, by distance: Int) -> Index {\n guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)\n else { fatalError(\"Index is out of bounds\") }\n return index\n }\n\n @inlinable\n internal func offsetForward(\n _ i: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance >= 0)\n assert(limit >= i)\n\n switch (i.position, limit.position) {\n case (.first(let i), .first(let limit)):\n return base1.index(i, offsetBy: distance, limitedBy: limit)\n .map(Index.init(first:))\n\n case (.first(let i), .second(let limit)):\n guard\n let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex)\n else {\n // the offset overflows the bounds of `base1` by `n - d`\n let d = base1.distance(from: i, to: base1.endIndex)\n return\n base2\n .index(base2.startIndex, offsetBy: distance - d, limitedBy: limit)\n .map(Index.init(second:))\n }\n // the offset stays within the bounds of `base1`\n return normalizeIndex(j)\n\n case (.second, .first):\n // impossible because `limit >= i`\n fatalError()\n\n case (.second(let i), .second(let limit)):\n return base2.index(i, offsetBy: distance, limitedBy: limit)\n .map(Index.init(second:))\n }\n }\n\n @inlinable\n internal func offsetBackward(\n _ i: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance >= 0)\n assert(limit <= i)\n\n switch (i.position, limit.position) {\n case (.first(let i), .first(let limit)):\n return base1.index(i, offsetBy: -distance, limitedBy: limit)\n .map(Index.init(first:))\n\n case (.first, .second):\n // impossible because `limit <= i`\n fatalError()\n\n case (.second(let i), .first(let limit)):\n guard\n let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex)\n else {\n // the offset overflows the bounds of `base2` by `n - d`\n let d = base2.distance(from: base2.startIndex, to: i)\n return\n base1\n .index(base1.endIndex, offsetBy: -(distance - d), limitedBy: limit)\n .map(Index.init(first:))\n }\n // the offset stays within the bounds of `base2`\n return Index(second: j)\n\n case (.second(let i), .second(let limit)):\n // `limit` is relevant, so `base1` cannot be reached\n return base2.index(i, offsetBy: -distance, limitedBy: limit)\n .map(Index.init(second:))\n }\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n switch (start.position, end.position) {\n case (.first(let i), .first(let j)):\n return base1.distance(from: i, to: j)\n case (.second(let i), .second(let j)):\n return base2.distance(from: i, to: j)\n case (.first(let i), .second(let j)):\n return base1.distance(from: i, to: base1.endIndex)\n + base2.distance(from: base2.startIndex, to: j)\n case (.second(let i), .first(let j)):\n return base2.distance(from: i, to: base2.startIndex)\n + base1.distance(from: base1.endIndex, to: j)\n }\n }\n}\n\nextension Chain2Sequence: BidirectionalCollection\nwhere Base1: BidirectionalCollection, Base2: BidirectionalCollection {\n @inlinable\n public func index(before i: Index) -> Index {\n assert(i != startIndex, \"Can't advance before startIndex\")\n switch i.position {\n case .first(let i):\n return Index(first: base1.index(before: i))\n case .second(let i):\n return i == base2.startIndex\n ? Index(first: base1.index(before: base1.endIndex))\n : Index(second: base2.index(before: i))\n }\n }\n}\n\nextension Chain2Sequence: RandomAccessCollection\nwhere Base1: RandomAccessCollection, Base2: RandomAccessCollection {}\n\n//===----------------------------------------------------------------------===//\n// chain(_:_:)\n//===----------------------------------------------------------------------===//\n\n/// Returns a new sequence that iterates over the two given sequences, one\n/// followed by the other.\n///\n/// You can pass any two sequences or collections that have the same element\n/// type as this sequence. This example chains a closed range of `Int` with an\n/// array of `Int`:\n///\n/// let small = 1...3\n/// let big = [100, 200, 300]\n/// for num in chain(small, big) {\n/// print(num)\n/// }\n/// // 1\n/// // 2\n/// // 3\n/// // 100\n/// // 200\n/// // 300\n///\n/// - Parameters:\n/// - s1: The first sequence.\n/// - s2: The second sequence.\n/// - Returns: A sequence that iterates first over the elements of `s1`, and\n/// then over the elements of `s2`.\n///\n/// - Complexity: O(1)\n@inlinable\npublic func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2Sequence<S1, S2> {\n Chain2Sequence(base1: s1, base2: s2)\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Indexed.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// A collection wrapper that iterates over the indices and elements of a\n/// collection together.\npublic struct IndexedCollection<Base: Collection> {\n /// The base collection.\n @usableFromInline\n internal let base: Base\n\n @inlinable\n internal init(base: Base) {\n self.base = base\n }\n}\n\nextension IndexedCollection: Collection {\n /// The element type for an `IndexedCollection` collection.\n public typealias Element = (index: Base.Index, element: Base.Element)\n\n @inlinable\n public var startIndex: Base.Index {\n base.startIndex\n }\n\n @inlinable\n public var endIndex: Base.Index {\n base.endIndex\n }\n\n @inlinable\n public subscript(position: Base.Index) -> Element {\n (index: position, element: base[position])\n }\n\n @inlinable\n public func index(after i: Base.Index) -> Base.Index {\n base.index(after: i)\n }\n\n @inlinable\n public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index {\n base.index(i, offsetBy: distance)\n }\n\n @inlinable\n public func index(\n _ i: Base.Index,\n offsetBy distance: Int,\n limitedBy limit: Base.Index\n ) -> Base.Index? {\n base.index(i, offsetBy: distance, limitedBy: limit)\n }\n\n @inlinable\n public func distance(from start: Base.Index, to end: Base.Index) -> Int {\n base.distance(from: start, to: end)\n }\n\n @inlinable\n public var indices: Base.Indices {\n base.indices\n }\n}\n\nextension IndexedCollection: BidirectionalCollection\nwhere Base: BidirectionalCollection {\n @inlinable\n public func index(before i: Base.Index) -> Base.Index {\n base.index(before: i)\n }\n}\n\nextension IndexedCollection: RandomAccessCollection\nwhere Base: RandomAccessCollection {}\n\nextension IndexedCollection: LazySequenceProtocol, LazyCollectionProtocol\nwhere Base: LazySequenceProtocol {}\n\n//===----------------------------------------------------------------------===//\n// indexed()\n//===----------------------------------------------------------------------===//\n\nextension Collection {\n /// Returns a collection of pairs *(i, x)*, where *i* represents an index of\n /// the collection, and *x* represents an element.\n ///\n /// The `indexed()` method is similar to the standard library's `enumerated()`\n /// method, but provides the index with each element instead of a zero-based\n /// counter.\n ///\n /// This example iterates over the indices and elements of a set, building an\n /// array consisting of indices of names with five or fewer letters.\n ///\n /// let names: Set = [\"Sofia\", \"Camilla\", \"Martina\", \"Mateo\", \"Nicol\u00e1s\"]\n /// var shorterIndices: [Set<String>.Index] = []\n /// for (i, name) in names.indexed() {\n /// if name.count <= 5 {\n /// shorterIndices.append(i)\n /// }\n /// }\n ///\n /// - Returns: A collection of paired indices and elements of this collection.\n @inlinable\n public func indexed() -> IndexedCollection<Self> {\n IndexedCollection(base: self)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "FirstNonNil.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// firstNonNil(_:)\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns the first non-`nil` result obtained from applying the given\n /// transformation to the elements of the sequence.\n ///\n /// let strings = [\"three\", \"3.14\", \"-5\", \"2\"]\n /// if let firstInt = strings.firstNonNil({ Int($0) }) {\n /// print(firstInt)\n /// // -5\n /// }\n ///\n /// - Parameter transform: A closure that takes an element of the sequence as\n /// its argument and returns an optional transformed value.\n /// - Returns: The first non-`nil` return value of the transformation, or\n /// `nil` if no transformation is successful.\n ///\n /// - Complexity: O(*n*), where *n* is the number of elements at the start of\n /// the sequence that result in `nil` when applying the transformation.\n @inlinable\n public func firstNonNil<Result>(\n _ transform: (Element) throws -> Result?\n ) rethrows -> Result? {\n for value in self {\n if let value = try transform(value) {\n return value\n }\n }\n return nil\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Compacted.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// A `Sequence` that iterates over every non-nil element from the original\n/// `Sequence`.\npublic struct CompactedSequence<Base: Sequence, Element>: Sequence\nwhere Base.Element == Element? {\n\n @usableFromInline\n let base: Base\n\n @inlinable\n init(base: Base) {\n self.base = base\n }\n\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n var base: Base.Iterator\n\n @inlinable\n init(base: Base.Iterator) {\n self.base = base\n }\n\n @inlinable\n public mutating func next() -> Element? {\n while let wrapped = base.next() {\n guard let some = wrapped else { continue }\n return some\n }\n return nil\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(base: base.makeIterator())\n }\n}\n\nextension Sequence {\n /// Returns a new `Sequence` that iterates over every non-nil element from the\n /// original `Sequence`.\n ///\n /// Produces the same result as `c.compactMap { $0 }`.\n ///\n /// let c = [1, nil, 2, 3, nil]\n /// for num in c.compacted() {\n /// print(num)\n /// }\n /// // 1\n /// // 2\n /// // 3\n ///\n /// - Returns: A `Sequence` where the element is the unwrapped original\n /// element and iterates over every non-nil element from the original\n /// `Sequence`.\n ///\n /// Complexity: O(1)\n @inlinable\n public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>\n where Element == Unwrapped? {\n CompactedSequence(base: self)\n }\n}\n\n/// A `Collection` that iterates over every non-nil element from the original\n/// `Collection`.\npublic struct CompactedCollection<Base: Collection, Element>: Collection\nwhere Base.Element == Element? {\n\n @usableFromInline\n let base: Base\n\n @inlinable\n init(base: Base) {\n self.base = base\n let idx = base.firstIndex(where: { $0 != nil }) ?? base.endIndex\n self.startIndex = Index(base: idx)\n }\n\n public struct Index {\n @usableFromInline\n let base: Base.Index\n\n @inlinable\n init(base: Base.Index) {\n self.base = base\n }\n }\n\n public var startIndex: Index\n\n @inlinable\n public var endIndex: Index { Index(base: base.endIndex) }\n\n @inlinable\n public subscript(position: Index) -> Element {\n // swift-format-ignore: NeverForceUnwrap\n // All indices are only for non-`nil` elements.\n base[position.base]!\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n precondition(i != endIndex, \"Index out of bounds\")\n\n let baseIdx = base.index(after: i.base)\n guard let idx = base[baseIdx...].firstIndex(where: { $0 != nil })\n else { return endIndex }\n return Index(base: idx)\n }\n}\n\nextension CompactedCollection: BidirectionalCollection\nwhere Base: BidirectionalCollection {\n\n @inlinable\n public func index(before i: Index) -> Index {\n precondition(i != startIndex, \"Index out of bounds\")\n\n guard\n let idx =\n base[startIndex.base..<i.base]\n .lastIndex(where: { $0 != nil })\n else { fatalError(\"Index out of bounds\") }\n return Index(base: idx)\n }\n}\n\nextension CompactedCollection.Index: Comparable {\n @inlinable\n public static func < (\n lhs: CompactedCollection.Index,\n rhs: CompactedCollection.Index\n ) -> Bool {\n lhs.base < rhs.base\n }\n}\n\nextension CompactedCollection.Index: Hashable\nwhere Base.Index: Hashable {}\n\nextension Collection {\n /// Returns a new `Collection` that iterates over every non-nil element from\n /// the original `Collection`.\n ///\n /// Produces the same result as `c.compactMap { $0 }`.\n ///\n /// let c = [1, nil, 2, 3, nil]\n /// for num in c.compacted() {\n /// print(num)\n /// }\n /// // 1\n /// // 2\n /// // 3\n ///\n /// - Returns: A `Collection` where the element is the unwrapped original\n /// element and iterates over every non-nil element from the original\n /// `Collection`.\n ///\n /// Complexity: O(*n*) where *n* is the number of elements in the\n /// original `Collection`.\n @inlinable\n public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>\n where Element == Unwrapped? {\n CompactedCollection(base: self)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Protocol Conformances\n//===----------------------------------------------------------------------===//\n\nextension CompactedSequence: LazySequenceProtocol\nwhere Base: LazySequenceProtocol {}\n\nextension CompactedCollection: LazySequenceProtocol, LazyCollectionProtocol\nwhere Base: LazySequenceProtocol {}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Intersperse.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// Intersperse\n//===----------------------------------------------------------------------===//\n\n/// A sequence that presents the elements of a base sequence of elements with a\n/// separator between each of those elements.\npublic struct InterspersedSequence<Base: Sequence> {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let separator: Base.Element\n\n @inlinable\n internal init(base: Base, separator: Base.Element) {\n self.base = base\n self.separator = separator\n }\n}\n\nextension InterspersedSequence: Sequence {\n /// The iterator for an `InterspersedSequence` sequence.\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal enum State {\n case start\n case element(Base.Element)\n case separator\n }\n\n @usableFromInline\n internal var iterator: Base.Iterator\n\n @usableFromInline\n internal let separator: Base.Element\n\n @usableFromInline\n internal var state = State.start\n\n @inlinable\n internal init(iterator: Base.Iterator, separator: Base.Element) {\n self.iterator = iterator\n self.separator = separator\n }\n\n @inlinable\n public mutating func next() -> Base.Element? {\n // After the start, the state flips between element and separator. Before\n // returning a separator, a check is made for the next element as a\n // separator is only returned between two elements. The next element is\n // stored to allow it to be returned in the next iteration.\n switch state {\n case .start:\n state = .separator\n return iterator.next()\n case .separator:\n guard let next = iterator.next() else { return nil }\n state = .element(next)\n return separator\n case .element(let element):\n state = .separator\n return element\n }\n }\n }\n\n @inlinable\n public func makeIterator() -> InterspersedSequence<Base>.Iterator {\n Iterator(iterator: base.makeIterator(), separator: separator)\n }\n}\n\nextension InterspersedSequence: Collection where Base: Collection {\n /// A position in an `InterspersedSequence` instance.\n public struct Index: Comparable {\n @usableFromInline\n internal enum Representation: Equatable {\n case element(Base.Index)\n case separator(next: Base.Index)\n }\n\n @usableFromInline\n internal let representation: Representation\n\n @inlinable\n internal init(representation: Representation) {\n self.representation = representation\n }\n\n @inlinable\n public static func < (lhs: Index, rhs: Index) -> Bool {\n switch (lhs.representation, rhs.representation) {\n case (.element(let li), .element(let ri)),\n (.separator(next: let li), .separator(next: let ri)),\n (.element(let li), .separator(next: let ri)):\n return li < ri\n case (.separator(next: let li), .element(let ri)):\n return li <= ri\n }\n }\n\n @inlinable\n internal static func element(_ index: Base.Index) -> Self {\n Self(representation: .element(index))\n }\n\n @inlinable\n internal static func separator(next: Base.Index) -> Self {\n Self(representation: .separator(next: next))\n }\n }\n\n @inlinable\n public var startIndex: Index {\n base.startIndex == base.endIndex ? endIndex : .element(base.startIndex)\n }\n\n @inlinable\n public var endIndex: Index {\n .separator(next: base.endIndex)\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n precondition(i != endIndex, \"Can't advance past endIndex\")\n switch i.representation {\n case .element(let index):\n return .separator(next: base.index(after: index))\n case .separator(let next):\n return .element(next)\n }\n }\n\n @inlinable\n public subscript(position: Index) -> Element {\n switch position.representation {\n case .element(let index): return base[index]\n case .separator: return separator\n }\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n switch (start.representation, end.representation) {\n case (.element(let element), .separator(next: let separator)):\n return 2 * base.distance(from: element, to: separator) - 1\n case (.separator(next: let separator), .element(let element)):\n return 2 * base.distance(from: separator, to: element) + 1\n case (.element(let start), .element(let end)),\n (.separator(let start), .separator(let end)):\n return 2 * base.distance(from: start, to: end)\n }\n }\n\n @inlinable\n public func index(_ index: Index, offsetBy distance: Int) -> Index {\n distance >= 0\n ? offsetForward(index, by: distance)\n : offsetBackward(index, by: -distance)\n }\n\n @inlinable\n public func index(\n _ index: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n if distance >= 0 {\n return limit >= index\n ? offsetForward(index, by: distance, limitedBy: limit)\n : offsetForward(index, by: distance)\n } else {\n return limit <= index\n ? offsetBackward(index, by: -distance, limitedBy: limit)\n : offsetBackward(index, by: -distance)\n }\n }\n\n @inlinable\n internal func offsetForward(_ i: Index, by distance: Int) -> Index {\n guard let index = offsetForward(i, by: distance, limitedBy: endIndex)\n else { fatalError(\"Index is out of bounds\") }\n return index\n }\n\n @inlinable\n internal func offsetBackward(_ i: Index, by distance: Int) -> Index {\n guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)\n else { fatalError(\"Index is out of bounds\") }\n return index\n }\n\n @inlinable\n internal func offsetForward(\n _ index: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance >= 0)\n assert(limit >= index)\n\n switch (\n index.representation, limit.representation, distance.isMultiple(of: 2)\n ) {\n case (.element(let index), .element(let limit), true),\n (.separator(next: let index), .element(let limit), false):\n return base.index(index, offsetBy: distance / 2, limitedBy: limit)\n .map { .element($0) }\n\n case (.element(let index), .element(let limit), false),\n (.element(let index), .separator(next: let limit), false),\n (.separator(next: let index), .element(let limit), true),\n (.separator(next: let index), .separator(next: let limit), true):\n return base.index(index, offsetBy: (distance + 1) / 2, limitedBy: limit)\n .map { .separator(next: $0) }\n\n case (.element(let index), .separator(next: let limit), true),\n (.separator(next: let index), .separator(next: let limit), false):\n return base.index(index, offsetBy: distance / 2, limitedBy: limit)\n .flatMap { $0 == limit ? nil : .element($0) }\n }\n }\n\n @inlinable\n internal func offsetBackward(\n _ index: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance >= 0)\n assert(limit <= index)\n\n switch (\n index.representation, limit.representation, distance.isMultiple(of: 2)\n ) {\n case (.element(let index), .element(let limit), true),\n (.element(let index), .separator(next: let limit), true),\n (.separator(next: let index), .element(let limit), false),\n (.separator(next: let index), .separator(next: let limit), false):\n return base.index(\n index, offsetBy: -((distance + 1) / 2), limitedBy: limit\n )\n .map { .element($0) }\n\n case (.element(let index), .separator(next: let limit), false),\n (.separator(next: let index), .separator(next: let limit), true):\n return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)\n .map { .separator(next: $0) }\n\n case (.element(let index), .element(let limit), false),\n (.separator(next: let index), .element(let limit), true):\n return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)\n .flatMap { $0 == limit ? nil : .separator(next: $0) }\n }\n }\n}\n\nextension InterspersedSequence: BidirectionalCollection\nwhere Base: BidirectionalCollection {\n @inlinable\n public func index(before i: Index) -> Index {\n precondition(i != startIndex, \"Can't move before startIndex\")\n switch i.representation {\n case .element(let index):\n return .separator(next: index)\n case .separator(let next):\n return .element(base.index(before: next))\n }\n }\n}\n\nextension InterspersedSequence: RandomAccessCollection\nwhere Base: RandomAccessCollection {}\n\nextension InterspersedSequence: LazySequenceProtocol\nwhere Base: LazySequenceProtocol {}\n\nextension InterspersedSequence: LazyCollectionProtocol\nwhere Base: LazySequenceProtocol & Collection {}\n\n//===----------------------------------------------------------------------===//\n// InterspersedMap\n//===----------------------------------------------------------------------===//\n\n/// A sequence over the results of applying a closure to the sequence's\n/// elements, with a separator that separates each pair of adjacent transformed\n/// values.\n@usableFromInline\ninternal struct InterspersedMapSequence<Base: Sequence, Result> {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let transform: (Base.Element) -> Result\n\n @usableFromInline\n internal let separator: (Base.Element, Base.Element) -> Result\n}\n\nextension InterspersedMapSequence: Sequence {\n @usableFromInline\n internal struct Iterator: IteratorProtocol {\n @usableFromInline\n internal enum State {\n case start\n case element(Base.Element)\n case separator(previous: Base.Element)\n }\n\n @usableFromInline\n internal var base: Base.Iterator\n\n @usableFromInline\n internal let transform: (Base.Element) -> Result\n\n @usableFromInline\n internal let separator: (Base.Element, Base.Element) -> Result\n\n @usableFromInline\n internal var state = State.start\n\n @inlinable\n internal init(\n base: Base.Iterator,\n transform: @escaping (Base.Element) -> Result,\n separator: @escaping (Base.Element, Base.Element) -> Result\n ) {\n self.base = base\n self.transform = transform\n self.separator = separator\n }\n\n @inlinable\n internal mutating func next() -> Result? {\n switch state {\n case .start:\n guard let first = base.next() else { return nil }\n state = .separator(previous: first)\n return transform(first)\n case .separator(let previous):\n guard let next = base.next() else { return nil }\n state = .element(next)\n return separator(previous, next)\n case .element(let element):\n state = .separator(previous: element)\n return transform(element)\n }\n }\n }\n\n @inlinable\n internal func makeIterator() -> Iterator {\n Iterator(\n base: base.makeIterator(),\n transform: transform,\n separator: separator)\n }\n}\n\nextension InterspersedMapSequence: Collection where Base: Collection {\n @usableFromInline\n internal struct Index: Comparable {\n @usableFromInline\n internal enum Representation {\n case element(Base.Index)\n case separator(previous: Base.Index, next: Base.Index)\n }\n\n @usableFromInline\n internal let base: Representation\n\n @inlinable\n internal init(representation: Representation) {\n self.base = representation\n }\n\n @inlinable\n internal static func element(_ index: Base.Index) -> Self {\n Self(representation: .element(index))\n }\n\n @inlinable\n internal static func separator(\n previous: Base.Index,\n next: Base.Index\n ) -> Self {\n Self(representation: .separator(previous: previous, next: next))\n }\n\n @inlinable\n internal static func == (lhs: Self, rhs: Self) -> Bool {\n switch (lhs.base, rhs.base) {\n case (.element(let lhs), .element(let rhs)),\n (.separator(_, next: let lhs), .separator(_, next: let rhs)):\n return lhs == rhs\n case (.element, .separator), (.separator, .element):\n return false\n }\n }\n\n @inlinable\n internal static func < (lhs: Self, rhs: Self) -> Bool {\n switch (lhs.base, rhs.base) {\n case (.element(let lhs), .element(let rhs)),\n (.separator(_, next: let lhs), .separator(_, next: let rhs)),\n (.element(let lhs), .separator(_, next: let rhs)),\n (.separator(previous: let lhs, _), .element(let rhs)):\n return lhs < rhs\n }\n }\n }\n\n @inlinable\n internal var startIndex: Index {\n base.isEmpty ? endIndex : .element(base.startIndex)\n }\n\n @inlinable\n internal var endIndex: Index {\n .separator(previous: base.endIndex, next: base.endIndex)\n }\n\n @inlinable\n internal func index(after index: Index) -> Index {\n switch index.base {\n case .element(let index):\n let next = base.index(after: index)\n return .separator(previous: index, next: next)\n case .separator(_, let next):\n return .element(next)\n }\n }\n\n @inlinable\n internal subscript(position: Index) -> Result {\n switch position.base {\n case .element(let index):\n return transform(base[index])\n case .separator(let previous, let next):\n return separator(base[previous], base[next])\n }\n }\n\n @inlinable\n internal func distance(from start: Index, to end: Index) -> Int {\n switch (start.base, end.base) {\n case (.element(let lhs), .element(let rhs)),\n (.separator(_, next: let lhs), .separator(_, next: let rhs)):\n return 2 * base.distance(from: lhs, to: rhs)\n case (.element(let lhs), .separator(_, next: let rhs)):\n return 2 * base.distance(from: lhs, to: rhs) - 1\n case (.separator(_, next: let lhs), .element(let rhs)):\n return 2 * base.distance(from: lhs, to: rhs) + 1\n }\n }\n\n @inlinable\n internal func index(_ index: Index, offsetBy distance: Int) -> Index {\n guard distance != 0 else { return index }\n\n return distance > 0\n ? offsetForward(index, by: distance)\n : offsetBackward(index, by: -distance)\n }\n\n @inlinable\n internal func index(\n _ index: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n guard distance != 0 else { return index }\n\n if distance > 0 {\n return limit >= index\n ? offsetForward(index, by: distance, limitedBy: limit)\n : offsetForward(index, by: distance)\n } else {\n return limit <= index\n ? offsetBackward(index, by: -distance, limitedBy: limit)\n : offsetBackward(index, by: -distance)\n }\n }\n\n @inlinable\n internal func offsetForward(_ i: Index, by distance: Int) -> Index {\n guard let index = offsetForward(i, by: distance, limitedBy: endIndex)\n else { fatalError(\"Index is out of bounds\") }\n return index\n }\n\n @inlinable\n internal func offsetBackward(_ i: Index, by distance: Int) -> Index {\n guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)\n else { fatalError(\"Index is out of bounds\") }\n return index\n }\n\n @inlinable\n internal func offsetForward(\n _ index: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance > 0)\n assert(limit >= index)\n\n switch (index.base, limit.base, distance.isMultiple(of: 2)) {\n case (.element(let index), .element(let limit), true),\n (.separator(_, next: let index), .element(let limit), false):\n return base.index(index, offsetBy: distance / 2, limitedBy: limit)\n .map { .element($0) }\n\n case (.element(let index), .element(let limit), false),\n (.element(let index), .separator(_, next: let limit), false),\n (.separator(_, next: let index), .element(let limit), true),\n (.separator(_, next: let index), .separator(_, next: let limit), true):\n return base.index(index, offsetBy: (distance - 1) / 2, limitedBy: limit)\n .flatMap {\n guard $0 != limit else { return nil }\n let next = base.index(after: $0)\n return next == base.endIndex\n ? endIndex\n : .separator(previous: $0, next: next)\n }\n\n case (.element(let index), .separator(_, next: let limit), true),\n (.separator(_, next: let index), .separator(_, next: let limit), false):\n return base.index(index, offsetBy: distance / 2, limitedBy: limit)\n .flatMap { $0 == limit ? nil : .element($0) }\n }\n }\n\n @inlinable\n internal func offsetBackward(\n _ index: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance > 0)\n assert(limit <= index)\n\n switch (index.base, limit.base, distance.isMultiple(of: 2)) {\n case (.element(let index), .element(let limit), true),\n (.element(let index), .separator(_, next: let limit), true),\n (.separator(_, next: let index), .element(let limit), false),\n (.separator(_, next: let index), .separator(_, next: let limit), false):\n return\n base\n .index(index, offsetBy: -((distance + 1) / 2), limitedBy: limit)\n .map { .element($0) }\n\n case (.element(let index), .separator(_, next: let limit), false),\n (.separator(_, next: let index), .separator(_, next: let limit), true):\n return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)\n .map { .separator(previous: base.index($0, offsetBy: -1), next: $0) }\n\n case (.element(let index), .element(let limit), false),\n (.separator(_, next: let index), .element(let limit), true):\n return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)\n .flatMap {\n $0 == limit\n ? nil\n : .separator(previous: base.index($0, offsetBy: -1), next: $0)\n }\n }\n }\n}\n\nextension InterspersedMapSequence: BidirectionalCollection\nwhere Base: BidirectionalCollection {\n @inlinable\n internal func index(before index: Index) -> Index {\n switch index.base {\n case .element(let index):\n let previous = base.index(before: index)\n return .separator(previous: previous, next: index)\n case .separator(let previous, let next):\n let index = next == base.endIndex ? base.index(before: next) : previous\n return .element(index)\n }\n }\n}\n\nextension InterspersedMapSequence.Index: Hashable\nwhere Base.Index: Hashable {\n @inlinable\n internal func hash(into hasher: inout Hasher) {\n switch base {\n case .element(let base):\n hasher.combine(false)\n hasher.combine(base)\n case .separator(_, let next):\n hasher.combine(true)\n hasher.combine(next)\n }\n }\n}\n\nextension InterspersedMapSequence: LazySequenceProtocol {}\nextension InterspersedMapSequence: LazyCollectionProtocol\nwhere Base: Collection {}\n\n//===----------------------------------------------------------------------===//\n// interspersed(with:)\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns a sequence containing elements of this sequence with the given\n /// separator inserted in between each element.\n ///\n /// Any value of the sequence's element type can be used as the separator.\n ///\n /// ```\n /// for value in [1,2,3].interspersed(with: 0) {\n /// print(value)\n /// }\n /// // 1\n /// // 0\n /// // 2\n /// // 0\n /// // 3\n /// ```\n ///\n /// The following shows a String being interspersed with a Character:\n /// ```\n /// let result = \"ABCDE\".interspersed(with: \"-\")\n /// print(String(result))\n /// // \"A-B-C-D-E\"\n /// ```\n ///\n /// - Parameter separator: Value to insert in between each of this sequence\u2019s\n /// elements.\n /// - Returns: The interspersed sequence of elements.\n ///\n /// - Complexity: O(1)\n @inlinable\n public func interspersed(\n with separator: Element\n ) -> InterspersedSequence<Self> {\n InterspersedSequence(base: self, separator: separator)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// lazy.interspersedMap(_:with:)\n//===----------------------------------------------------------------------===//\n\nextension LazySequenceProtocol {\n /// Returns a sequence over the results of applying a closure to the\n /// sequence's elements, with a separator that separates each pair of adjacent\n /// transformed values.\n ///\n /// The transformation closure lets you intersperse a sequence using a\n /// separator of a different type than the original's sequence's elements.\n /// Each separator is produced by a closure that is given access to the\n /// two elements in the original sequence right before and after it.\n ///\n /// let strings = [1, 2, 2].interspersedMap(String.init,\n /// with: { $0 == $1 ? \" == \" : \" != \" })\n /// print(strings.joined()) // \"1 != 2 == 2\"\n ///\n @usableFromInline\n internal func interspersedMap<Result>(\n _ transform: @escaping (Element) -> Result,\n with separator: @escaping (Element, Element) -> Result\n ) -> InterspersedMapSequence<Elements, Result> {\n InterspersedMapSequence(\n base: elements,\n transform: transform,\n separator: separator)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Cycle.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// A collection wrapper that repeats the elements of a base collection.\npublic struct CycledSequence<Base: Collection> {\n /// The collection to repeat.\n @usableFromInline\n internal let base: Base\n\n @inlinable\n internal init(base: Base) {\n self.base = base\n }\n}\n\nextension CycledSequence: Sequence {\n /// The iterator for a `CycledSequence` instance.\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal var current: Base.Index\n\n @inlinable\n internal init(base: Base) {\n self.base = base\n self.current = base.startIndex\n }\n\n @inlinable\n public mutating func next() -> Base.Element? {\n guard !base.isEmpty else { return nil }\n\n if current == base.endIndex {\n current = base.startIndex\n }\n\n defer { base.formIndex(after: ¤t) }\n return base[current]\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(base: base)\n }\n}\n\nextension CycledSequence: LazySequenceProtocol\nwhere Base: LazySequenceProtocol {}\n\n/// A collection wrapper that repeats the elements of a base collection for a\n/// finite number of times.\npublic struct CycledTimesCollection<Base: Collection> {\n /// A `Product2Sequence` instance for iterating the base collection.\n @usableFromInline\n internal let product: Product2Sequence<Range<Int>, Base>\n\n @inlinable\n internal init(base: Base, times: Int) {\n self.product = Product2Sequence(0..<times, base)\n }\n}\n\nextension CycledTimesCollection: Collection {\n public typealias Element = Base.Element\n\n public struct Index: Comparable {\n /// The index corresponding to the `Product2Sequence` index at this\n /// position.\n @usableFromInline\n internal let productIndex: Product2Sequence<Range<Int>, Base>.Index\n\n @inlinable\n internal init(_ productIndex: Product2Sequence<Range<Int>, Base>.Index) {\n self.productIndex = productIndex\n }\n\n @inlinable\n public static func == (lhs: Index, rhs: Index) -> Bool {\n lhs.productIndex == rhs.productIndex\n }\n\n @inlinable\n public static func < (lhs: Index, rhs: Index) -> Bool {\n lhs.productIndex < rhs.productIndex\n }\n }\n\n @inlinable\n public var startIndex: Index {\n Index(product.startIndex)\n }\n\n @inlinable\n public var endIndex: Index {\n Index(product.endIndex)\n }\n\n @inlinable\n public subscript(_ index: Index) -> Element {\n product[index.productIndex].1\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n let productIndex = product.index(after: i.productIndex)\n return Index(productIndex)\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n product.distance(from: start.productIndex, to: end.productIndex)\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n let productIndex = product.index(i.productIndex, offsetBy: distance)\n return Index(productIndex)\n }\n\n @inlinable\n public func index(\n _ i: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n guard\n let productIndex = product.index(\n i.productIndex,\n offsetBy: distance,\n limitedBy: limit.productIndex)\n else { return nil }\n return Index(productIndex)\n }\n\n @inlinable\n public var count: Int {\n product.count\n }\n}\n\nextension CycledTimesCollection: BidirectionalCollection\nwhere Base: BidirectionalCollection {\n @inlinable\n public func index(before i: Index) -> Index {\n let productIndex = product.index(before: i.productIndex)\n return Index(productIndex)\n }\n}\n\nextension CycledTimesCollection: RandomAccessCollection\nwhere Base: RandomAccessCollection {}\n\nextension CycledTimesCollection: LazySequenceProtocol, LazyCollectionProtocol\nwhere Base: LazySequenceProtocol {}\n\n//===----------------------------------------------------------------------===//\n// cycled()\n//===----------------------------------------------------------------------===//\n\nextension Collection {\n /// Returns a sequence that repeats the elements of this collection forever.\n ///\n /// Use the `cycled()` method to repeat the elements of a sequence or\n /// collection forever. You can combine `cycled()` with another, finite\n /// sequence to iterate over the two together.\n ///\n /// for (evenOrOdd, number) in zip([\"even\", \"odd\"].cycled(), 0..<10) {\n /// print(\"\\(number) is \\(evenOrOdd)\")\n /// }\n /// // 0 is even\n /// // 1 is odd\n /// // 2 is even\n /// // 3 is odd\n /// // ...\n /// // 9 is odd\n ///\n /// - Important: When called on a non-empty collection, the resulting sequence\n /// is infinite. Do not directly call methods that require a finite\n /// sequence, like `map` or `filter`, without first constraining the length\n /// of the cycling sequence.\n ///\n /// - Returns: A sequence that repeats the elements of this collection\n /// forever.\n ///\n /// - Complexity: O(1)\n @inlinable\n public func cycled() -> CycledSequence<Self> {\n CycledSequence(base: self)\n }\n\n /// Returns a sequence that repeats the elements of this collection the\n /// specified number of times.\n ///\n /// Passing `1` as `times` results in this collection's elements being\n /// provided a single time; passing `0` results in an empty sequence. The\n /// `print(_:)` function in this example is never called:\n ///\n /// for x in [1, 2, 3].cycled(times: 0) {\n /// print(x)\n /// }\n ///\n /// - Parameter times: The number of times to repeat this sequence. `times`\n /// must be zero or greater.\n /// - Returns: A sequence that repeats the elements of this sequence `times`\n /// times.\n ///\n /// - Complexity: O(1)\n @inlinable\n public func cycled(times: Int) -> CycledTimesCollection<Self> {\n CycledTimesCollection(base: self, times: times)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Suffix.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// suffix(while:)\n//===----------------------------------------------------------------------===//\n\nextension BidirectionalCollection {\n /// Returns a subsequence containing the suffix of this collection where\n /// all elements pass the given closure.\n ///\n /// - Parameter predicate: A closure that takes an element of the sequence as\n /// its argument and returns `true` if the element should be included or\n /// `false` if it should be excluded. Once the predicate returns `false` it\n /// will not be called again.\n /// - Returns: A subsequence that is a suffix of the collection, where\n /// `predicate` returns `true` for all the elements of the returned\n /// subsequence.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public func suffix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> SubSequence {\n try self[startOfSuffix(while: predicate)...]\n }\n}\n\n//===----------------------------------------------------------------------===//\n// endOfPrefix(while:)\n//===----------------------------------------------------------------------===//\n\nextension Collection {\n /// Returns the exclusive upper bound of the prefix of elements that satisfy\n /// the predicate.\n ///\n /// - Parameter predicate: A closure that takes an element of the collection\n /// as its argument and returns `true` if the element is part of the prefix\n /// or `false` if it is not. Once the predicate returns `false` it will not\n /// be called again.\n /// - Returns: The index of the first element for which `predicate` does not\n /// succeed, or `endIndex` if all the collection's elements pass.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public func endOfPrefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> Index {\n var index = startIndex\n while try index != endIndex && predicate(self[index]) {\n formIndex(after: &index)\n }\n return index\n }\n}\n\n//===----------------------------------------------------------------------===//\n// startOfSuffix(while:)\n//===----------------------------------------------------------------------===//\n\nextension BidirectionalCollection {\n /// Returns the inclusive lower bound of the suffix of elements that satisfy\n /// the predicate.\n ///\n /// - Parameter predicate: A closure that takes an element of the collection\n /// as its argument and returns `true` if the element is part of the suffix\n /// or `false` if it is not. Once the predicate returns `false` it will not\n /// be called again.\n /// - Returns: The index of the last element for which `predicate` does not\n /// succeed, or `startIndex` if all the collection's elements pass.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public func startOfSuffix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> Index {\n var index = endIndex\n while index != startIndex {\n let after = index\n formIndex(before: &index)\n if try !predicate(self[index]) {\n return after\n }\n }\n return index\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Combinations.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// A collection wrapper that generates combinations of a base collection.\npublic struct CombinationsSequence<Base: Collection> {\n /// The collection to iterate over for combinations.\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let baseCount: Int\n\n /// The range of accepted sizes of combinations.\n ///\n /// - Note: This may be `nil` if the attempted range entirely exceeds the\n /// upper bounds of the size of the `base` collection.\n @usableFromInline\n internal let kRange: Range<Int>?\n\n /// Initializes a `CombinationsSequence` for all combinations of `base` of\n /// size `k`.\n ///\n /// - Parameters:\n /// - base: The collection to iterate over for combinations.\n /// - k: The expected size of each combination.\n @inlinable\n internal init(_ base: Base, k: Int) {\n self.init(base, kRange: k...k)\n }\n\n /// Initializes a `CombinationsSequence` for all combinations of `base` of\n /// sizes within a given range.\n ///\n /// - Parameters:\n /// - base: The collection to iterate over for combinations.\n /// - kRange: The range of accepted sizes of combinations.\n @inlinable\n internal init<R: RangeExpression>(\n _ base: Base,\n kRange: R\n ) where R.Bound == Int {\n let range = kRange.relative(to: 0 ..< .max)\n self.base = base\n let baseCount = base.count\n self.baseCount = baseCount\n let upperBound = baseCount + 1\n self.kRange =\n range.lowerBound < upperBound\n ? range.clamped(to: 0..<upperBound)\n : nil\n }\n\n /// The total number of combinations.\n @inlinable\n public var count: Int {\n guard let k = self.kRange else { return 0 }\n let n = baseCount\n if k == 0..<(n + 1) {\n return 1 << n\n }\n\n func binomial(n: Int, k: Int) -> Int {\n switch k {\n case n, 0: return 1\n case n...: return 0\n case (n / 2 + 1)...: return binomial(n: n, k: n - k)\n default: return n * binomial(n: n - 1, k: k - 1) / k\n }\n }\n\n return k.map {\n binomial(n: n, k: $0)\n }.reduce(0, +)\n }\n\n /// The total number of combinations.\n @inlinable\n public var underestimatedCount: Int { count }\n}\n\nextension CombinationsSequence: Sequence {\n /// The iterator for a `CombinationsSequence` instance.\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal let base: Base\n\n /// The current range of accepted sizes of combinations.\n ///\n /// - Note: The range is contracted until empty while iterating over\n /// combinations of different sizes. When the range is empty, iteration is\n /// finished.\n @usableFromInline\n internal var kRange: Range<Int>\n\n /// Whether or not iteration is finished (`kRange` is empty).\n @inlinable\n internal var isFinished: Bool {\n kRange.isEmpty\n }\n\n @usableFromInline\n internal var indexes: [Base.Index]\n\n @inlinable\n internal init(_ combinations: CombinationsSequence) {\n self.base = combinations.base\n self.kRange = combinations.kRange ?? 0..<0\n self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound))\n }\n\n /// Advances the current indices to the next set of combinations. If\n /// `indexes.count == 3` and `base.count == 5`, the indices advance like\n /// this:\n ///\n /// [0, 1, 2]\n /// [0, 1, 3]\n /// [0, 1, 4] *\n /// // * `base.endIndex` reached in `indexes.last`\n /// // Advance penultimate index and propagate that change\n /// [0, 2, 3]\n /// [0, 2, 4] *\n /// [0, 3, 4] *\n /// [1, 2, 3]\n /// [1, 2, 4] *\n /// [1, 3, 4] *\n /// [2, 3, 4] *\n /// // Can't advance without needing to go past `base.endIndex`,\n /// // so the iteration is finished.\n @inlinable\n internal mutating func advance() {\n /// Advances `kRange` by incrementing its `lowerBound` until the range is\n /// empty, when iteration is finished.\n func advanceKRange() {\n if kRange.lowerBound < kRange.upperBound {\n let advancedLowerBound = kRange.lowerBound + 1\n kRange = advancedLowerBound..<kRange.upperBound\n indexes.removeAll(keepingCapacity: true)\n indexes.append(contentsOf: base.indices.prefix(kRange.lowerBound))\n }\n }\n\n guard !indexes.isEmpty else {\n // Initial state for combinations of 0 elements is an empty array with\n // `finished == false`. Even though no indexes are involved, advancing\n // from that state means we are finished with iterating.\n advanceKRange()\n return\n }\n\n let i = indexes.count - 1\n base.formIndex(after: &indexes[i])\n if indexes[i] != base.endIndex { return }\n\n var j = i\n while indexes[i] == base.endIndex {\n j -= 1\n guard j >= 0 else {\n // Finished iterating over combinations of this size.\n advanceKRange()\n return\n }\n\n base.formIndex(after: &indexes[j])\n for k in indexes.indices[(j + 1)...] {\n indexes[k] = base.index(after: indexes[k - 1])\n if indexes[k] == base.endIndex {\n break\n }\n }\n }\n }\n\n @inlinable\n public mutating func next() -> [Base.Element]? {\n guard !isFinished else { return nil }\n defer { advance() }\n return indexes.map { i in base[i] }\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(self)\n }\n}\n\nextension CombinationsSequence: LazySequenceProtocol\nwhere Base: LazySequenceProtocol {}\n\n//===----------------------------------------------------------------------===//\n// combinations(ofCount:)\n//===----------------------------------------------------------------------===//\n\nextension Collection {\n /// Returns a collection of combinations of this collection's elements, with\n /// each combination having the specified number of elements.\n ///\n /// This example prints the different combinations of 1 and 2 from an array of\n /// four colors:\n ///\n /// let colors = [\"fuchsia\", \"cyan\", \"mauve\", \"magenta\"]\n /// for combo in colors.combinations(ofCount: 1...2) {\n /// print(combo.joined(separator: \", \"))\n /// }\n /// // fuchsia\n /// // cyan\n /// // mauve\n /// // magenta\n /// // fuchsia, cyan\n /// // fuchsia, mauve\n /// // fuchsia, magenta\n /// // cyan, mauve\n /// // cyan, magenta\n /// // mauve, magenta\n ///\n /// The returned collection presents combinations in a consistent order, where\n /// the indices in each combination are in ascending lexicographical order.\n /// That is, in the example above, the combinations in order are the elements\n /// at `[0]`, `[1]`, `[2]`, `[3]`, `[0, 1]`, `[0, 2]`, `[0, 3]`, `[1, 2]`,\n /// `[1, 3]`, and finally `[2, 3]`.\n ///\n /// This example prints _all_ the combinations (including an empty array and\n /// the original collection) from an array of numbers:\n ///\n /// let numbers = [10, 20, 30, 40]\n /// for combo in numbers.combinations(ofCount: 0...) {\n /// print(combo)\n /// }\n /// // []\n /// // [10]\n /// // [20]\n /// // [30]\n /// // [40]\n /// // [10, 20]\n /// // [10, 30]\n /// // [10, 40]\n /// // [20, 30]\n /// // [20, 40]\n /// // [30, 40]\n /// // [10, 20, 30]\n /// // [10, 20, 40]\n /// // [10, 30, 40]\n /// // [20, 30, 40]\n /// // [10, 20, 30, 40]\n ///\n /// If `kRange` is `0...0`, the resulting sequence has exactly one element, an\n /// empty array. The given range is limited to `0...base.count`. If the\n /// limited range is empty, the resulting sequence has no elements.\n ///\n /// - Parameter kRange: The range of numbers of elements to include in each\n /// combination.\n /// - Returns: A sequence of the combinations of this collection's\n /// elements, for all sizes in `kRange`, from smallest to largest.\n ///\n /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*\n /// is the number of elements in the base collection, since\n /// `CombinationsSequence` accesses the `count` of the base collection.\n @inlinable\n public func combinations<R: RangeExpression>(\n ofCount kRange: R\n ) -> CombinationsSequence<Self> where R.Bound == Int {\n CombinationsSequence(self, kRange: kRange)\n }\n\n /// Returns a collection of combinations of this collection's elements, with\n /// each combination having the specified number of elements.\n ///\n /// This example prints the different combinations of three from an array of\n /// four colors:\n ///\n /// let colors = [\"fuchsia\", \"cyan\", \"mauve\", \"magenta\"]\n /// for combo in colors.combinations(ofCount: 3) {\n /// print(combo.joined(separator: \", \"))\n /// }\n /// // fuchsia, cyan, mauve\n /// // fuchsia, cyan, magenta\n /// // fuchsia, mauve, magenta\n /// // cyan, mauve, magenta\n ///\n /// The returned collection presents combinations in a consistent order, where\n /// the indices in each combination are in ascending lexicographical order.\n /// That is, in the example above, the combinations in order are the elements\n /// at `[0, 1, 2]`, `[0, 1, 3]`, `[0, 2, 3]`, and finally `[1, 2, 3]`.\n ///\n /// If `k` is zero, the resulting sequence has exactly one element, an empty\n /// array. If `k` is greater than the number of elements in this sequence,\n /// the resulting sequence has no elements.\n ///\n /// - Parameter k: The number of elements to include in each combination.\n /// - Returns: A sequence of the combinations of this collection's\n /// elements.\n ///\n /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*\n /// is the number of elements in the base collection, since\n /// `CombinationsSequence` accesses the `count` of the base collection.\n @inlinable\n public func combinations(ofCount k: Int) -> CombinationsSequence<Self> {\n precondition(\n k >= 0,\n \"Can't have combinations with a negative number of elements.\")\n return CombinationsSequence(self, k: k)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Rotate.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// reverse(subrange:)\n//===----------------------------------------------------------------------===//\n\nextension MutableCollection where Self: BidirectionalCollection {\n /// Reverses the elements of the collection, moving from each end until\n /// `limit` is reached from either direction.\n ///\n /// The returned indices are the start and end of the range of unreversed\n /// elements.\n ///\n /// Input:\n /// [a b c d e f g h i j k l m n o p]\n /// ^\n /// limit\n /// Output:\n /// [p o n m e f g h i j k l d c b a]\n /// ^ ^\n /// lower upper\n ///\n /// - Postcondition: For returned indices `(lower, upper)`:\n /// `lower == limit || upper == limit`.\n @inlinable\n @discardableResult\n internal mutating func _reverse(\n subrange: Range<Index>,\n until limit: Index\n ) -> (Index, Index) {\n var lower = subrange.lowerBound\n var upper = subrange.upperBound\n while lower != limit && upper != limit {\n formIndex(before: &upper)\n swapAt(lower, upper)\n formIndex(after: &lower)\n }\n return (lower, upper)\n }\n\n /// Reverses the elements within the given subrange.\n ///\n /// This example reverses the numbers within the subrange at the start of the\n /// `numbers` array:\n ///\n /// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]\n /// numbers.reverse(subrange: 0..<4)\n /// // numbers == [40, 30, 20, 10, 50, 60, 70, 80]\n ///\n /// - Parameter subrange: The subrange of this collection to reverse.\n ///\n /// - Complexity: O(*n*), where *n* is the length of `subrange`.\n @inlinable\n public mutating func reverse(subrange: Range<Index>) {\n if subrange.isEmpty { return }\n var lower = subrange.lowerBound\n var upper = subrange.upperBound\n while lower < upper {\n formIndex(before: &upper)\n swapAt(lower, upper)\n formIndex(after: &lower)\n }\n }\n}\n\n//===----------------------------------------------------------------------===//\n// rotate(toStartAt:) / rotate(subrange:toStartAt:)\n//===----------------------------------------------------------------------===//\n\nextension MutableCollection {\n /// Swaps the elements of the two given subranges, up to the upper bound of\n /// the smaller subrange.\n ///\n /// The returned indices are the ends of the two ranges that were actually\n /// swapped.\n ///\n /// Input:\n /// [a b c d e f g h i j k l m n o p]\n /// ^^^^^^^ ^^^^^^^^^^^^^\n /// lhs rhs\n ///\n /// Output:\n /// [i j k l e f g h a b c d m n o p]\n /// ^ ^\n /// p q\n ///\n /// - Precondition: !lhs.isEmpty && !rhs.isEmpty\n /// - Postcondition: For returned indices `(p, q)`:\n ///\n /// - distance(from: lhs.lowerBound, to: p) == distance(from:\n /// rhs.lowerBound, to: q)\n /// - p == lhs.upperBound || q == rhs.upperBound\n @inlinable\n internal mutating func _swapNonemptySubrangePrefixes(\n _ lhs: Range<Index>,\n _ rhs: Range<Index>\n ) -> (Index, Index) {\n assert(!lhs.isEmpty)\n assert(!rhs.isEmpty)\n\n var p = lhs.lowerBound\n var q = rhs.lowerBound\n repeat {\n swapAt(p, q)\n formIndex(after: &p)\n formIndex(after: &q)\n } while p != lhs.upperBound && q != rhs.upperBound\n return (p, q)\n }\n\n /// Rotates the elements within the given subrange so that the element at the\n /// specified index becomes the start of the subrange.\n ///\n /// Rotating a collection is equivalent to breaking the collection into two\n /// sections at the index `newStart`, and then swapping those two sections.\n /// In this example, the `numbers` array is rotated so that the element at\n /// index `3` (`40`) is first:\n ///\n /// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]\n /// let oldStart = numbers.rotate(subrange: 0..<4, toStartAt: 2)\n /// // numbers == [30, 40, 10, 20, 50, 60, 70, 80]\n /// // numbers[oldStart] == 10\n ///\n /// - Parameters:\n /// - subrange: The subrange of this collection to rotate.\n /// - newStart: The index of the element that should be at the start of\n /// `subrange` after rotating.\n /// - Returns: The new index of the element that was at the start of\n /// `subrange` pre-rotation.\n ///\n /// - Complexity: O(*n*), where *n* is the length of `subrange`.\n @inlinable\n @discardableResult\n public mutating func rotate(\n subrange: Range<Index>,\n toStartAt newStart: Index\n ) -> Index {\n var m = newStart\n var s = subrange.lowerBound\n let e = subrange.upperBound\n\n // Handle the trivial cases\n if s == m { return e }\n if m == e { return s }\n\n // We have two regions of possibly-unequal length that need to be exchanged.\n // The return value of this method is going to be the position following\n // that of the element that is currently last (element j).\n //\n // [a b c d e f g|h i j] or [a b c|d e f g h i j]\n // ^ ^ ^ ^ ^ ^\n // s m e s m e\n //\n var ret = e // start with a known incorrect result.\n while true {\n // Exchange the leading elements of each region (up to the length of the\n // shorter region).\n //\n // [a b c d e f g|h i j] or [a b c|d e f g h i j]\n // ^^^^^ ^^^^^ ^^^^^ ^^^^^\n // [h i j d e f g|a b c] or [d e f|a b c g h i j]\n // ^ ^ ^ ^ ^ ^ ^ ^\n // s s1 m m1/e s s1/m m1 e\n //\n let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e)\n\n if m1 == e {\n // Left-hand case: we have moved element j into position. If we haven't\n // already, we can capture the return value which is in s1.\n //\n // Note: the STL breaks the loop into two just to avoid this comparison\n // once the return value is known. I'm not sure it's a worthwhile\n // optimization, though.\n if ret == e { ret = s1 }\n\n // If both regions were the same size, we're done.\n if s1 == m { break }\n }\n\n // Now we have a smaller problem that is also a rotation, so we can adjust\n // our bounds and repeat.\n //\n // h i j[d e f g|a b c] or d e f[a b c|g h i j]\n // ^ ^ ^ ^ ^ ^\n // s m e s m e\n s = s1\n if s == m { m = m1 }\n }\n\n return ret\n }\n\n /// Rotates the elements of this collection so that the element at the\n /// specified index becomes the start of the collection.\n ///\n /// Rotating a collection is equivalent to breaking the collection into two\n /// sections at the index `newStart`, and then swapping those two sections.\n /// In this example, the `numbers` array is rotated so that the element at\n /// index `3` (`40`) is first:\n ///\n /// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]\n /// let oldStart = numbers.rotate(toStartAt: 3)\n /// // numbers == [40, 50, 60, 70, 80, 10, 20, 30]\n /// // numbers[oldStart] == 10\n ///\n /// - Parameter newStart: The index of the element that should be first after\n /// rotating.\n /// - Returns: The new index of the element that was first pre-rotation.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n @discardableResult\n public mutating func rotate(toStartAt newStart: Index) -> Index {\n rotate(subrange: startIndex..<endIndex, toStartAt: newStart)\n }\n}\n\nextension MutableCollection where Self: BidirectionalCollection {\n /// Rotates the elements within the given subrange so that the element at the\n /// specified index becomes the start of the subrange.\n ///\n /// Rotating a collection is equivalent to breaking the collection into two\n /// sections at the index `newStart`, and then swapping those two sections.\n /// In this example, the `numbers` array is rotated so that the element at\n /// index `3` (`40`) is first:\n ///\n /// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]\n /// let oldStart = numbers.rotate(subrange: 0..<4, toStartAt: 2)\n /// // numbers == [30, 40, 10, 20, 50, 60, 70, 80]\n /// // numbers[oldStart] == 10\n ///\n /// - Parameters:\n /// - subrange: The subrange of this collection to rotate.\n /// - newStart: The index of the element that should be at the start of\n /// `subrange` after rotating.\n /// - Returns: The new index of the element that was at the start of\n /// `subrange` pre-rotation.\n ///\n /// - Complexity: O(*n*), where *n* is the length of `subrange`.\n @inlinable\n @discardableResult\n public mutating func rotate(\n subrange: Range<Index>,\n toStartAt newStart: Index\n ) -> Index {\n reverse(subrange: subrange.lowerBound..<newStart)\n reverse(subrange: newStart..<subrange.upperBound)\n let (p, q) = _reverse(subrange: subrange, until: newStart)\n reverse(subrange: p..<q)\n return newStart == p ? q : p\n }\n\n /// Rotates the elements of this collection so that the element at the\n /// specified index becomes the start of the collection.\n ///\n /// Rotating a collection is equivalent to breaking the collection into two\n /// sections at the index `newStart`, and then swapping those two sections. In\n /// this example, the `numbers` array is rotated so that the element at index\n /// `3` (`40`) is first:\n ///\n /// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]\n /// let oldStart = numbers.rotate(toStartAt: 3)\n /// // numbers == [40, 50, 60, 70, 80, 10, 20, 30]\n /// // numbers[oldStart] == 10\n ///\n /// - Parameter newStart: The index of the element that should be first after\n /// rotating.\n /// - Returns: The new index of the element that was first pre-rotation.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n @discardableResult\n public mutating func rotate(toStartAt newStart: Index) -> Index {\n rotate(subrange: startIndex..<endIndex, toStartAt: newStart)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "EitherSequence.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// Either\n//===----------------------------------------------------------------------===//\n\n/// A general-purpose sum type.\n@usableFromInline\ninternal enum Either<Left, Right> {\n case left(Left)\n case right(Right)\n}\n\nextension Either: Equatable where Left: Equatable, Right: Equatable {\n @usableFromInline\n internal static func == (lhs: Self, rhs: Self) -> Bool {\n switch (lhs, rhs) {\n case (.left(let lhs), .left(let rhs)):\n return lhs == rhs\n case (.right(let lhs), .right(let rhs)):\n return lhs == rhs\n case (.left, .right), (.right, .left):\n return false\n }\n }\n}\n\nextension Either: Comparable where Left: Comparable, Right: Comparable {\n @usableFromInline\n internal static func < (lhs: Self, rhs: Self) -> Bool {\n switch (lhs, rhs) {\n case (.left(let lhs), .left(let rhs)):\n return lhs < rhs\n case (.right(let lhs), .right(let rhs)):\n return lhs < rhs\n case (.left, .right):\n return true\n case (.right, .left):\n return false\n }\n }\n}\n\n//===----------------------------------------------------------------------===//\n// EitherSequence\n//===----------------------------------------------------------------------===//\n\n/// A sequence that has one of the two specified types.\n@usableFromInline\ninternal enum EitherSequence<Left: Sequence, Right: Sequence>\nwhere Left.Element == Right.Element {\n case left(Left)\n case right(Right)\n}\n\nextension EitherSequence: Sequence {\n @usableFromInline\n internal struct Iterator: IteratorProtocol {\n @usableFromInline\n internal var left: Left.Iterator?\n\n @usableFromInline\n internal var right: Right.Iterator?\n\n @inlinable\n internal mutating func next() -> Left.Element? {\n left?.next() ?? right?.next()\n }\n }\n\n @usableFromInline\n internal func makeIterator() -> Iterator {\n switch self {\n case .left(let left):\n return Iterator(left: left.makeIterator(), right: nil)\n case .right(let right):\n return Iterator(left: nil, right: right.makeIterator())\n }\n }\n}\n\nextension EitherSequence: Collection\nwhere Left: Collection, Right: Collection, Left.Element == Right.Element {\n @usableFromInline\n internal typealias Index = Either<Left.Index, Right.Index>\n\n @inlinable\n internal var startIndex: Index {\n switch self {\n case .left(let s):\n return .left(s.startIndex)\n case .right(let s):\n return .right(s.startIndex)\n }\n }\n\n @inlinable\n internal var endIndex: Index {\n switch self {\n case .left(let s):\n return .left(s.endIndex)\n case .right(let s):\n return .right(s.endIndex)\n }\n }\n\n @inlinable\n internal subscript(position: Index) -> Element {\n switch (self, position) {\n case (.left(let s), .left(let i)):\n return s[i]\n case (.right(let s), .right(let i)):\n return s[i]\n default:\n fatalError()\n }\n }\n\n @inlinable\n internal func index(after i: Index) -> Index {\n switch (self, i) {\n case (.left(let s), .left(let i)):\n return .left(s.index(after: i))\n case (.right(let s), .right(let i)):\n return .right(s.index(after: i))\n default:\n fatalError()\n }\n }\n\n @inlinable\n internal func index(\n _ i: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n switch (self, i, limit) {\n case (.left(let s), .left(let i), .left(let limit)):\n return s.index(i, offsetBy: distance, limitedBy: limit).map { .left($0) }\n case (.right(let s), .right(let i), .right(let limit)):\n return s.index(i, offsetBy: distance, limitedBy: limit).map { .right($0) }\n default:\n fatalError()\n }\n }\n\n @inlinable\n internal func index(_ i: Index, offsetBy distance: Int) -> Index {\n switch (self, i) {\n case (.left(let s), .left(let i)):\n return .left(s.index(i, offsetBy: distance))\n case (.right(let s), .right(let i)):\n return .right(s.index(i, offsetBy: distance))\n default:\n fatalError()\n }\n }\n\n @inlinable\n internal func distance(from start: Index, to end: Index) -> Int {\n switch (self, start, end) {\n case (.left(let s), .left(let i), .left(let j)):\n return s.distance(from: i, to: j)\n case (.right(let s), .right(let i), .right(let j)):\n return s.distance(from: i, to: j)\n default:\n fatalError()\n }\n }\n}\n\nextension EitherSequence: BidirectionalCollection\nwhere Left: BidirectionalCollection, Right: BidirectionalCollection {\n @inlinable\n internal func index(before i: Index) -> Index {\n switch (self, i) {\n case (.left(let s), .left(let i)):\n return .left(s.index(before: i))\n case (.right(let s), .right(let i)):\n return .right(s.index(before: i))\n default:\n fatalError()\n }\n }\n}\n\nextension EitherSequence: RandomAccessCollection\nwhere Left: RandomAccessCollection, Right: RandomAccessCollection {}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "AdjacentPairs.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns a sequence of overlapping adjacent pairs of the elements of this\n /// sequence.\n ///\n /// In the `AdjacentPairsSequence` returned by this method, the elements of\n /// the *i*th pair are the *i*th and *(i+1)*th elements of the underlying\n /// sequence. The following example uses the `adjacentPairs()` method to\n /// iterate over adjacent pairs of integers:\n ///\n /// for pair in (1...).prefix(5).adjacentPairs() {\n /// print(pair)\n /// }\n /// // Prints \"(1, 2)\"\n /// // Prints \"(2, 3)\"\n /// // Prints \"(3, 4)\"\n /// // Prints \"(4, 5)\"\n ///\n /// The resulting sequence is empty when called on an empty or single-element\n /// sequence.\n ///\n /// - Complexity: O(1)\n @inlinable\n public func adjacentPairs() -> AdjacentPairsSequence<Self> {\n AdjacentPairsSequence(base: self)\n }\n}\n\nextension Collection {\n /// Returns a collection of overlapping adjacent pairs of the elements of this\n /// collection.\n ///\n /// In an `AdjacentPairsCollection`, the elements of the *i*th pair are the\n /// *i*th and *(i+1)*th elements of the underlying sequence. The following\n /// example uses the `adjacentPairs()` method to iterate over adjacent pairs\n /// of integers:\n ///\n /// for pair in (1...5).adjacentPairs() {\n /// print(pair)\n /// }\n /// // Prints \"(1, 2)\"\n /// // Prints \"(2, 3)\"\n /// // Prints \"(3, 4)\"\n /// // Prints \"(4, 5)\"\n ///\n /// The resulting collection is empty when called on an empty or\n /// single-element collection.\n ///\n /// - Complexity: O(1)\n @inlinable\n public func adjacentPairs() -> AdjacentPairsCollection<Self> {\n AdjacentPairsCollection(base: self)\n }\n}\n\n/// A sequence of adjacent pairs of elements built from an underlying sequence.\n///\n/// Use the `adjacentPairs()` method on a sequence to create an\n/// `AdjacentPairsSequence` instance.\npublic struct AdjacentPairsSequence<Base: Sequence> {\n @usableFromInline\n internal let base: Base\n\n /// Creates an instance that makes pairs of adjacent elements from `base`.\n @inlinable\n internal init(base: Base) {\n self.base = base\n }\n}\n\nextension AdjacentPairsSequence {\n /// The iterator for an `AdjacentPairsSequence` or `AdjacentPairsCollection`\n /// instance.\n public struct Iterator {\n @usableFromInline\n internal var base: Base.Iterator\n\n @usableFromInline\n internal var previousElement: Base.Element?\n\n @inlinable\n internal init(base: Base.Iterator) {\n self.base = base\n }\n }\n}\n\nextension AdjacentPairsSequence.Iterator: IteratorProtocol {\n public typealias Element = (Base.Element, Base.Element)\n\n @inlinable\n public mutating func next() -> Element? {\n if previousElement == nil {\n previousElement = base.next()\n }\n\n guard let previous = previousElement, let next = base.next() else {\n return nil\n }\n\n previousElement = next\n return (previous, next)\n }\n}\n\nextension AdjacentPairsSequence: Sequence {\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(base: base.makeIterator())\n }\n\n @inlinable\n public var underestimatedCount: Int {\n Swift.max(0, base.underestimatedCount - 1)\n }\n}\n\nextension AdjacentPairsSequence: LazySequenceProtocol\nwhere Base: LazySequenceProtocol {}\n\n/// A collection of adjacent pairs of elements built from an underlying\n/// collection.\n///\n/// Use the `adjacentPairs()` method on a collection to create an\n/// `AdjacentPairsCollection` instance.\npublic struct AdjacentPairsCollection<Base: Collection> {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let secondBaseIndex: Base.Index\n\n @inlinable\n internal init(base: Base) {\n self.base = base\n self.secondBaseIndex =\n base.isEmpty\n ? base.endIndex\n : base.index(after: base.startIndex)\n }\n}\n\nextension AdjacentPairsCollection {\n /// A position in an `AdjacentPairsCollection` instance.\n public struct Index: Comparable {\n @usableFromInline\n internal var first: Base.Index\n\n @usableFromInline\n internal var second: Base.Index\n\n @inlinable\n internal init(first: Base.Index, second: Base.Index) {\n self.first = first\n self.second = second\n }\n\n @inlinable\n public static func == (lhs: Index, rhs: Index) -> Bool {\n lhs.first == rhs.first\n }\n\n @inlinable\n public static func < (lhs: Index, rhs: Index) -> Bool {\n lhs.first < rhs.first\n }\n }\n}\n\nextension AdjacentPairsCollection: Collection {\n @inlinable\n public var startIndex: Index {\n Index(\n first: secondBaseIndex == base.endIndex ? base.endIndex : base.startIndex,\n second: secondBaseIndex)\n }\n\n @inlinable\n public var endIndex: Index {\n Index(first: base.endIndex, second: base.endIndex)\n }\n\n @inlinable\n public subscript(position: Index) -> (Base.Element, Base.Element) {\n (base[position.first], base[position.second])\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n precondition(i != endIndex, \"Can't advance beyond endIndex\")\n let next = base.index(after: i.second)\n return next == base.endIndex\n ? endIndex\n : Index(first: i.second, second: next)\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n guard distance != 0 else { return i }\n\n guard\n let result = distance > 0\n ? offsetForward(i, by: distance, limitedBy: endIndex)\n : offsetBackward(i, by: -distance, limitedBy: startIndex)\n else { fatalError(\"Index out of bounds\") }\n return result\n }\n\n @inlinable\n public func index(\n _ i: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n guard distance != 0 else { return i }\n guard limit != i else { return nil }\n\n if distance > 0 {\n let limit = limit > i ? limit : endIndex\n return offsetForward(i, by: distance, limitedBy: limit)\n } else {\n let limit = limit < i ? limit : startIndex\n return offsetBackward(i, by: -distance, limitedBy: limit)\n }\n }\n\n @inlinable\n internal func offsetForward(\n _ i: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance > 0)\n assert(limit > i)\n\n let newFirst = base.index(\n i.second,\n offsetBy: distance - 1,\n limitedBy: limit.first)\n guard let newFirst, newFirst != base.endIndex\n else { return nil }\n\n let newSecond = base.index(after: newFirst)\n\n precondition(newSecond <= base.endIndex, \"Can't advance beyond endIndex\")\n return newSecond == base.endIndex\n ? endIndex\n : Index(first: newFirst, second: newSecond)\n }\n\n @inlinable\n internal func offsetBackward(\n _ i: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance > 0)\n assert(limit < i)\n\n let offset = i == endIndex ? 0 : 1\n let newSecond = base.index(\n i.first,\n offsetBy: -(distance - offset),\n limitedBy: limit.second)\n guard let newSecond\n else { return nil }\n\n let newFirst = base.index(newSecond, offsetBy: -1)\n precondition(newFirst >= base.startIndex, \"Can't move before startIndex\")\n return Index(first: newFirst, second: newSecond)\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n // While there's a 2-step gap between the `first` base index values in\n // `endIndex` and the penultimate index of this collection, the `second`\n // base index values are consistently one step apart throughout the\n // entire collection.\n base.distance(from: start.second, to: end.second)\n }\n\n @inlinable\n public var count: Int {\n Swift.max(0, base.count - 1)\n }\n}\n\nextension AdjacentPairsCollection: BidirectionalCollection\nwhere Base: BidirectionalCollection {\n @inlinable\n public func index(before i: Index) -> Index {\n precondition(i != startIndex, \"Can't offset before startIndex\")\n let second =\n i == endIndex\n ? base.index(before: base.endIndex)\n : i.first\n let first = base.index(before: second)\n return Index(first: first, second: second)\n }\n}\n\nextension AdjacentPairsCollection: RandomAccessCollection\nwhere Base: RandomAccessCollection {}\n\nextension AdjacentPairsCollection: LazySequenceProtocol, LazyCollectionProtocol\nwhere Base: LazySequenceProtocol {}\n\nextension AdjacentPairsCollection.Index: Hashable where Base.Index: Hashable {\n @inlinable\n public func hash(into hasher: inout Hasher) {\n hasher.combine(first)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Partition.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// stablePartition(by:)\n//===----------------------------------------------------------------------===//\n\nextension MutableCollection {\n /// Moves all elements satisfying `belongsInSecondPartition` into a suffix of\n /// the collection, preserving their relative order, and returns the start of\n /// the resulting suffix.\n ///\n /// - Complexity: O(*n* log *n*), where *n* is the number of elements.\n /// - Precondition:\n /// `n == distance(from: range.lowerBound, to: range.upperBound)`\n @inlinable\n internal mutating func stablePartition(\n count n: Int,\n subrange: Range<Index>,\n by belongsInSecondPartition: (Element) throws -> Bool\n ) rethrows -> Index {\n if n == 0 { return subrange.lowerBound }\n if n == 1 {\n return try belongsInSecondPartition(self[subrange.lowerBound])\n ? subrange.lowerBound\n : subrange.upperBound\n }\n\n let h = n / 2\n let i = index(subrange.lowerBound, offsetBy: h)\n let j = try stablePartition(\n count: h,\n subrange: subrange.lowerBound..<i,\n by: belongsInSecondPartition)\n let k = try stablePartition(\n count: n - h,\n subrange: i..<subrange.upperBound,\n by: belongsInSecondPartition)\n return rotate(subrange: j..<k, toStartAt: i)\n }\n\n /// Moves all elements satisfying the given predicate into a suffix of the\n /// given range, preserving the relative order of the elements in both\n /// partitions, and returns the start of the resulting suffix.\n ///\n /// - Parameters:\n /// - subrange: The range of elements within this collection to partition.\n /// - belongsInSecondPartition: A predicate used to partition the\n /// collection. All elements satisfying this predicate are ordered after\n /// all elements not satisfying it.\n /// - Returns: The pivot index `p`, which is the index of the first element\n /// in the reordered collection that matches `belongsInSecondPartition`.\n /// If no elements in the collection match `belongsInSecondPartition`, the\n /// returned index is equal to the collection's `endIndex`.\n ///\n /// - Complexity: O(*n* log *n*), where *n* is the length of this collection.\n @inlinable\n public mutating func stablePartition(\n subrange: Range<Index>,\n by belongsInSecondPartition: (Element) throws -> Bool\n ) rethrows -> Index {\n try stablePartition(\n count: distance(from: subrange.lowerBound, to: subrange.upperBound),\n subrange: subrange,\n by: belongsInSecondPartition)\n }\n\n /// Moves all elements satisfying the given predicate into a suffix of this\n /// collection, preserving the relative order of the elements in both\n /// partitions, and returns the start of the resulting suffix.\n ///\n /// - Parameter belongsInSecondPartition: A predicate used to partition the\n /// collection. All elements satisfying this predicate are ordered after\n /// all elements not satisfying it.\n /// - Returns: The pivot index `p`, which is the index of the first element\n /// in the reordered collection that matches `belongsInSecondPartition`.\n /// If no elements in the collection match `belongsInSecondPartition`, the\n /// returned index is equal to the collection's `endIndex`.\n ///\n /// - Complexity: O(*n* log *n*), where *n* is the length of this collection.\n @inlinable\n public mutating func stablePartition(\n by belongsInSecondPartition: (Element) throws -> Bool\n ) rethrows -> Index {\n try stablePartition(\n subrange: startIndex..<endIndex,\n by: belongsInSecondPartition)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// partition(by:)\n//===----------------------------------------------------------------------===//\n\nextension MutableCollection {\n /// Moves all elements satisfying the given closure into a suffix of the\n /// collection, returning the start position of the resulting suffix.\n ///\n /// After partitioning a collection, there is a pivot index `p` where no\n /// element before `p` satisfies the `belongsInSecondPartition` predicate and\n /// every element at or after `p` satisfies `belongsInSecondPartition`. This\n /// operation isn't guaranteed to be stable, so the relative ordering of\n /// elements within the partitions might change.\n ///\n /// - Parameters:\n /// - subrange: The range of elements within this collection to partition.\n /// - belongsInSecondPartition: A predicate used to partition the\n /// collection. All elements satisfying this predicate are ordered after\n /// all elements not satisfying it.\n /// - Returns: The pivot index `p`, which is the index of the first element\n /// in the reordered collection that matches `belongsInSecondPartition`.\n /// If no elements in the collection match `belongsInSecondPartition`, the\n /// returned index is equal to the collection's `endIndex`.\n ///\n /// - Complexity: O(*n*) where n is the length of the collection.\n @inlinable\n public mutating func partition(\n subrange: Range<Index>,\n by belongsInSecondPartition: (Element) throws -> Bool\n ) rethrows -> Index {\n // This version of `partition(subrange:)` is half stable; the elements in\n // the first partition retain their original relative order.\n guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition)\n else { return subrange.upperBound }\n\n var j = index(after: i)\n while j != subrange.upperBound {\n if try !belongsInSecondPartition(self[j]) {\n swapAt(i, j)\n formIndex(after: &i)\n }\n formIndex(after: &j)\n }\n\n return i\n }\n}\n\nextension MutableCollection where Self: BidirectionalCollection {\n /// Moves all elements satisfying the given closure into a suffix of the\n /// collection, returning the start position of the resulting suffix.\n ///\n /// After partitioning a collection, there is a pivot index `p` where no\n /// element before `p` satisfies the `belongsInSecondPartition` predicate and\n /// every element at or after `p` satisfies `belongsInSecondPartition`. This\n /// operation isn't guaranteed to be stable, so the relative ordering of\n /// elements within the partitions might change.\n ///\n /// - Parameters:\n /// - subrange: The range of elements within this collection to partition.\n /// - belongsInSecondPartition: A predicate used to partition the\n /// collection. All elements satisfying this predicate are ordered after\n /// all elements not satisfying it.\n /// - Returns: The pivot index `p`, which is the index of the first element\n /// in the reordered collection that matches `belongsInSecondPartition`.\n /// If no elements in the collection match `belongsInSecondPartition`, the\n /// returned index is equal to the collection's `endIndex`.\n ///\n /// - Complexity: O(*n*) where n is the length of the collection.\n @inlinable\n public mutating func partition(\n subrange: Range<Index>,\n by belongsInSecondPartition: (Element) throws -> Bool\n ) rethrows -> Index {\n var lo = subrange.lowerBound\n var hi = subrange.upperBound\n\n // 'Loop' invariants (at start of Loop, all are true):\n // * lo < hi\n // * predicate(self[i]) == false, for i in startIndex ..< lo\n // * predicate(self[i]) == true, for i in hi ..< endIndex\n\n Loop: while true {\n FindLo: do {\n while lo < hi {\n if try belongsInSecondPartition(self[lo]) { break FindLo }\n formIndex(after: &lo)\n }\n break Loop\n }\n\n FindHi: do {\n formIndex(before: &hi)\n while lo < hi {\n if try !belongsInSecondPartition(self[hi]) { break FindHi }\n formIndex(before: &hi)\n }\n break Loop\n }\n\n swapAt(lo, hi)\n formIndex(after: &lo)\n }\n\n return lo\n }\n}\n\n//===----------------------------------------------------------------------===//\n// partitioningIndex(where:)\n//===----------------------------------------------------------------------===//\n\nextension Collection {\n /// Returns the start index of the partition of a collection that matches\n /// the given predicate.\n ///\n /// The collection must already be partitioned according to the predicate.\n /// That is, there should be an index `i` where for every element in\n /// `collection[..<i]` the predicate is `false`, and for every element in\n /// `collection[i...]` the predicate is `true`.\n ///\n /// - Parameter belongsInSecondPartition: A predicate that partitions the\n /// collection.\n /// - Returns: The index of the first element in the collection for which\n /// `predicate` returns `true`, or `endIndex` if there are no elements\n /// for which `predicate` returns `true`.\n ///\n /// - Complexity: O(log *n*), where *n* is the length of this collection if\n /// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).\n @inlinable\n public func partitioningIndex(\n where belongsInSecondPartition: (Element) throws -> Bool\n ) rethrows -> Index {\n var n = count\n var l = startIndex\n\n while n > 0 {\n let half = n / 2\n let mid = index(l, offsetBy: half)\n if try belongsInSecondPartition(self[mid]) {\n n = half\n } else {\n l = index(after: mid)\n n -= half + 1\n }\n }\n return l\n }\n}\n\n//===----------------------------------------------------------------------===//\n// partitioned(by:)\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns two arrays containing the elements of the sequence that\n /// don\u2019t and do satisfy the given predicate, respectively.\n ///\n /// In this example, `partitioned(by:)` is used to separate the input based on\n /// whether a name is shorter than five characters:\n ///\n /// let cast = [\"Vivien\", \"Marlon\", \"Kim\", \"Karl\"]\n /// let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })\n /// print(longNames)\n /// // Prints \"[\"Vivien\", \"Marlon\"]\"\n /// print(shortNames)\n /// // Prints \"[\"Kim\", \"Karl\"]\"\n ///\n /// - Parameter predicate: A closure that takes an element of the sequence as\n /// its argument and returns a Boolean value indicating whether the element\n /// should be included in the second returned array. Otherwise, the element\n /// will appear in the first returned array.\n /// - Returns: Two arrays with all of the elements of the receiver. The\n /// first array contains all the elements that `predicate` didn\u2019t allow, and\n /// the second array contains all the elements that `predicate` allowed. The\n /// order of the elements in the arrays matches the order of the elements in\n /// the original sequence.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public func partitioned(\n by predicate: (Element) throws -> Bool\n ) rethrows -> (falseElements: [Element], trueElements: [Element]) {\n var lhs: [Element] = []\n var rhs: [Element] = []\n\n for element in self {\n if try predicate(element) {\n rhs.append(element)\n } else {\n lhs.append(element)\n }\n }\n\n return (lhs, rhs)\n }\n}\n\nextension Collection {\n /// Returns two arrays containing the elements of the collection that\n /// don\u2019t and do satisfy the given predicate, respectively.\n ///\n /// In this example, `partitioned(by:)` is used to separate the input based on\n /// whether a name is shorter than five characters.\n ///\n /// let cast = [\"Vivien\", \"Marlon\", \"Kim\", \"Karl\"]\n /// let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })\n /// print(longNames)\n /// // Prints \"[\"Vivien\", \"Marlon\"]\"\n /// print(shortNames)\n /// // Prints \"[\"Kim\", \"Karl\"]\"\n ///\n /// - Parameter predicate: A closure that takes an element of the collection\n /// as its argument and returns a Boolean value indicating whether the\n /// element should be included in the second returned array. Otherwise, the\n /// element will appear in the first returned array.\n /// - Returns: Two arrays with all of the elements of the receiver. The\n /// first array contains all the elements that `predicate` didn\u2019t allow, and\n /// the second array contains all the elements that `predicate` allowed. The\n /// order of the elements in the arrays matches the order of the elements in\n /// the original collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public func partitioned(\n by predicate: (Element) throws -> Bool\n ) rethrows -> (falseElements: [Element], trueElements: [Element]) {\n guard !self.isEmpty else {\n return ([], [])\n }\n\n // Since collections have known sizes, we can allocate one array of size\n // `self.count`, then insert items at the beginning or end of that contiguous\n // block. This way, we don\u2019t have to do any dynamic array resizing. Since we\n // insert the right elements on the right side in reverse order, we need to\n // reverse them back to the original order at the end.\n\n let count = self.count\n\n // Inside of the `initializer` closure, we set what the actual mid-point is.\n // We will use this to partition the single array into two.\n var midPoint: Int = 0\n\n let elements = try [Element](\n unsafeUninitializedCapacity: count,\n initializingWith: { buffer, initializedCount in\n // swift-format-ignore: NeverForceUnwrap\n // Non-empty check above.\n let bufferStart = buffer.baseAddress!\n var lhs = bufferStart\n var rhs = lhs + buffer.count\n do {\n for element in self {\n if try predicate(element) {\n rhs -= 1\n rhs.initialize(to: element)\n } else {\n lhs.initialize(to: element)\n lhs += 1\n }\n }\n\n precondition(\n lhs == rhs,\n \"\"\"\n Collection's `count` differed from the number of elements iterated.\n \"\"\"\n )\n\n let rhsIndex = rhs - bufferStart\n buffer[rhsIndex...].reverse()\n initializedCount = buffer.count\n\n midPoint = rhsIndex\n } catch {\n let lhsCount = lhs - bufferStart\n let rhsCount = (bufferStart + buffer.count) - rhs\n bufferStart.deinitialize(count: lhsCount)\n rhs.deinitialize(count: rhsCount)\n throw error\n }\n })\n\n let lhs = elements[..<midPoint]\n let rhs = elements[midPoint...]\n return (\n Array(lhs),\n Array(rhs)\n )\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Product.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// A sequence that represents the product of two sequences' elements.\npublic struct Product2Sequence<Base1: Sequence, Base2: Collection> {\n /// The outer sequence in the product.\n @usableFromInline\n internal let base1: Base1\n\n /// The inner sequence in the product.\n @usableFromInline\n internal let base2: Base2\n\n @inlinable\n internal init(_ base1: Base1, _ base2: Base2) {\n self.base1 = base1\n self.base2 = base2\n }\n}\n\nextension Product2Sequence: Sequence {\n public typealias Element = (Base1.Element, Base2.Element)\n\n /// The iterator for a `Product2Sequence` sequence.\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal var i1: Base1.Iterator\n @usableFromInline\n internal var i2: Base2.Iterator\n @usableFromInline\n internal var element1: Base1.Element?\n @usableFromInline\n internal let base2: Base2\n\n @inlinable\n internal init(_ c: Product2Sequence) {\n self.base2 = c.base2\n self.i1 = c.base1.makeIterator()\n self.i2 = c.base2.makeIterator()\n self.element1 = nil\n }\n\n @inlinable\n public mutating func next() -> (\n Base1.Element,\n Base2.Element\n )? {\n // This is the initial state, where i1.next() has never\n // been called, or the final state, where i1.next() has\n // already returned nil.\n if element1 == nil {\n element1 = i1.next()\n // once Base1 is exhausted, return `nil` forever\n if element1 == nil { return nil }\n }\n\n // Get the next element from the second sequence, if not\n // at end.\n if let element2 = i2.next() {\n // swift-format-ignore: NeverForceUnwrap\n // `element1` has a nil check above.\n return (element1!, element2)\n }\n\n // We've reached the end of the second sequence, so:\n // 1) Get the next element of the first sequence, if exists\n // 2) Restart iteration of the second sequence\n // 3) Get the first element of the second sequence, if exists\n element1 = i1.next()\n guard let element1 else {\n return nil\n }\n\n i2 = base2.makeIterator()\n guard let element2 = i2.next() else {\n return nil\n }\n return (element1, element2)\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(self)\n }\n}\n\nextension Product2Sequence: Collection where Base1: Collection {\n /// The index type for a `Product2Sequence` collection.\n public struct Index: Comparable {\n @usableFromInline\n internal var i1: Base1.Index\n @usableFromInline\n internal var i2: Base2.Index\n\n @inlinable\n internal init(i1: Base1.Index, i2: Base2.Index) {\n self.i1 = i1\n self.i2 = i2\n }\n\n @inlinable\n public static func < (lhs: Index, rhs: Index) -> Bool {\n (lhs.i1, lhs.i2) < (rhs.i1, rhs.i2)\n }\n }\n\n @inlinable\n public var count: Int {\n base1.count * base2.count\n }\n\n @inlinable\n public var startIndex: Index {\n Index(\n i1: base2.isEmpty ? base1.endIndex : base1.startIndex,\n i2: base2.startIndex)\n }\n\n @inlinable\n public var endIndex: Index {\n // `base2.startIndex` simplifies index calculations.\n Index(i1: base1.endIndex, i2: base2.startIndex)\n }\n\n @inlinable\n public subscript(position: Index) -> (\n Base1.Element,\n Base2.Element\n ) {\n (base1[position.i1], base2[position.i2])\n }\n\n /// Forms an index from a pair of base indices, normalizing\n /// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if\n /// necessary.\n @inlinable\n internal func normalizeIndex(_ i1: Base1.Index, _ i2: Base2.Index) -> Index {\n i2 == base2.endIndex\n ? Index(i1: base1.index(after: i1), i2: base2.startIndex)\n : Index(i1: i1, i2: i2)\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n precondition(i.i1 != base1.endIndex, \"Can't advance past endIndex\")\n return normalizeIndex(i.i1, base2.index(after: i.i2))\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n guard start.i1 <= end.i1\n else { return -distance(from: end, to: start) }\n guard start.i1 != end.i1\n else { return base2.distance(from: start.i2, to: end.i2) }\n\n // The number of full cycles through `base2` between `start` and `end`,\n // excluding the cycles that `start` and `end` are on.\n let fullBase2Cycles = base1[start.i1..<end.i1].count - 1\n\n if start.i2 <= end.i2 {\n // start.i2\n // v\n // start.i1 > [l l l|c c c c c c r r r]\n // [l l l c c c c c c r r r] >\n // ... > `fullBase2Cycles` times\n // [l l l c c c c c c r r r] >\n // end.i1 > [l l l c c c c c c|r r r]\n // ^\n // end.i2\n\n let left = base2[..<start.i2].count\n let center = base2[start.i2..<end.i2].count\n let right = base2[end.i2...].count\n\n return center + right\n + fullBase2Cycles * (left + center + right)\n + left + center\n } else {\n // start.i2\n // v\n // start.i1 > [l l l c c c c c c|r r r]\n // [l l l c c c c c c r r r] >\n // ... > `fullBase2Cycles` times\n // [l l l c c c c c c r r r] >\n // end.i1 > [l l l|c c c c c c r r r]\n // ^\n // end.i2\n\n let left = base2[..<end.i2].count\n let right = base2[start.i2...].count\n\n // We can avoid traversing `base2[end.i2..<start.i2]` if `start` and `end`\n // are on consecutive cycles.\n guard fullBase2Cycles > 0 else { return right + left }\n\n let center = base2[end.i2..<start.i2].count\n return right\n + fullBase2Cycles * (left + center + right)\n + left\n }\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n guard distance != 0 else { return i }\n\n return distance > 0\n ? offsetForward(i, by: distance)\n : offsetBackward(i, by: -distance)\n }\n\n @inlinable\n public func index(\n _ i: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n if distance >= 0 {\n return limit >= i\n ? offsetForward(i, by: distance, limitedBy: limit)\n : offsetForward(i, by: distance)\n } else {\n return limit <= i\n ? offsetBackward(i, by: -distance, limitedBy: limit)\n : offsetBackward(i, by: -distance)\n }\n }\n\n @inlinable\n internal func offsetForward(_ i: Index, by distance: Int) -> Index {\n guard let index = offsetForward(i, by: distance, limitedBy: endIndex)\n else { fatalError(\"Index is out of bounds\") }\n return index\n }\n\n @inlinable\n internal func offsetBackward(_ i: Index, by distance: Int) -> Index {\n guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)\n else { fatalError(\"Index is out of bounds\") }\n return index\n }\n\n @inlinable\n internal func offsetForward(\n _ i: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance >= 0)\n assert(limit >= i)\n\n if limit.i1 == i.i1 {\n // Delegate to `base2` if the offset is limited to `i.i1`.\n //\n // i.i2 limit.i2\n // v v\n // i.i1 > [x x x|x x x x x x|x x x]\n\n return base2.index(i.i2, offsetBy: distance, limitedBy: limit.i2)\n .map { i2 in Index(i1: i.i1, i2: i2) }\n }\n\n if let i2 =\n base2\n .index(i.i2, offsetBy: distance, limitedBy: base2.endIndex)\n {\n // `distance` does not overflow `base2[i.i2...]`.\n //\n // i.i2 i2\n // v v\n // i.i1 > [x x x|x x x x x x|x x x]\n // [ |> > > > > >| ] (`distance`)\n\n return normalizeIndex(i.i1, i2)\n }\n\n let suffixCount = base2[i.i2...].count\n let remaining = distance - suffixCount\n let nextI1 = base1.index(after: i.i1)\n\n if limit.i1 == nextI1 {\n // Delegate to `base2` if the offset is limited to `nextI1`.\n //\n // i.i2\n // v\n // i.i1 > [x x x|x x x x x x x x x]\n // nextI1 > [x x x x x x x x x|x x x]\n // ^\n // limit.i2\n\n return\n base2\n .index(base2.startIndex, offsetBy: remaining, limitedBy: limit.i2)\n .map { i2 in Index(i1: nextI1, i2: i2) }\n }\n\n if let i2 =\n base2\n .index(base2.startIndex, offsetBy: remaining, limitedBy: i.i2)\n {\n // `remaining` does not overflow `base2[..<i.i2]`.\n //\n // i.i2\n // v\n // i.i1 > [x x x x x x x x x|x x x]\n // [ |> > >] (`suffixCount`)\n // [> > >| ] (`remaining`)\n // nextI1 > [x x x|x x x x x x x x x]\n // ^\n // i2\n\n return Index(i1: nextI1, i2: i2)\n }\n\n let prefixCount = base2[..<i.i2].count\n let base2Count = prefixCount + suffixCount\n let base1Distance = remaining / base2Count\n\n guard\n let i1 = base1.index(nextI1, offsetBy: base1Distance, limitedBy: limit.i1)\n else { return nil }\n\n // The distance from `base2.startIndex` to the target.\n let base2Distance = remaining % base2Count\n\n let base2Limit = limit.i1 == i1 ? limit.i2 : base2.endIndex\n return\n base2\n .index(base2.startIndex, offsetBy: base2Distance, limitedBy: base2Limit)\n .map { i2 in Index(i1: i1, i2: i2) }\n }\n\n @inlinable\n internal func offsetBackward(\n _ i: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance >= 0)\n assert(limit <= i)\n\n if limit.i1 == i.i1 {\n // Delegate to `base2` if the offset is limited to `i.i1`.\n //\n // limit.i2 i.i2\n // v v\n // i.i1 > [x x x|x x x x x x|x x x]\n\n return base2.index(i.i2, offsetBy: -distance, limitedBy: limit.i2)\n .map { i2 in Index(i1: i.i1, i2: i2) }\n }\n\n if let i2 =\n base2\n .index(i.i2, offsetBy: -distance, limitedBy: base2.startIndex)\n {\n // `distance` does not underflow `base2[..<i.i2]`.\n //\n // i2 i.i2\n // v v\n // i.i1 > [x x x|x x x x x x|x x x]\n // [ |< < < < < <| ] (`distance`)\n\n return Index(i1: i.i1, i2: i2)\n }\n\n let prefixCount = base2[..<i.i2].count\n let remaining = distance - prefixCount\n let previousI1 = base1.index(i.i1, offsetBy: -1)\n\n if limit.i1 == previousI1 {\n // Delegate to `base2` if the offset is limited to `previousI1`.\n //\n // limit.i2\n // v\n // previousI1 > [x x x|x x x x x x x x x]\n // i.i1 > [x x x x x x x x x|x x x]\n // ^\n // i.i2\n\n return\n base2\n .index(base2.endIndex, offsetBy: -remaining, limitedBy: limit.i2)\n .map { i2 in Index(i1: previousI1, i2: i2) }\n }\n\n if let i2 =\n base2\n .index(base2.endIndex, offsetBy: -remaining, limitedBy: i.i2)\n {\n // `remaining` does not underflow `base2[i.i2...]`.\n //\n // i2\n // v\n // previousI1 > [x x x x x x x x x|x x x]\n // [ |< < <] (`remaining`)\n // [< < <| ] (`prefixCount`)\n // i.i1 > [x x x|x x x x x x x x x]\n // ^\n // i.i2\n\n return Index(i1: previousI1, i2: i2)\n }\n\n let suffixCount = base2[i.i2...].count\n let base2Count = prefixCount + suffixCount\n let base1Distance = remaining / base2Count\n\n // The distance from `base2.endIndex` to the target.\n let base2Distance = remaining % base2Count\n\n if base2Distance == 0 {\n // We end up exactly between two cycles, so `base1Distance` would\n // overshoot the target by 1.\n //\n // base2.startIndex\n // v\n // i1 > |x x x x x x x x x x x x] >\n // ... > `base1Distance` times\n // previousI1 > [x x x x x x x x x x x x] >\n // i.i1 > [x x x|x x x x x x x x x]\n // ^\n // i.i2\n\n guard\n let i1 = base1.index(\n previousI1,\n offsetBy: -(base1Distance - 1),\n limitedBy: limit.i1)\n else {\n return nil\n }\n let index = Index(i1: i1, i2: base2.startIndex)\n return index < limit ? nil : index\n }\n\n guard\n let i1 =\n base1\n .index(previousI1, offsetBy: -base1Distance, limitedBy: limit.i1)\n else { return nil }\n\n let base2Limit = limit.i1 == i1 ? limit.i2 : base2.startIndex\n return\n base2\n .index(base2.endIndex, offsetBy: -base2Distance, limitedBy: base2Limit)\n .map { i2 in Index(i1: i1, i2: i2) }\n }\n}\n\nextension Product2Sequence: BidirectionalCollection\nwhere Base1: BidirectionalCollection, Base2: BidirectionalCollection {\n @inlinable\n public func index(before i: Index) -> Index {\n precondition(\n i != startIndex,\n \"Can't move before startIndex\")\n guard i.i2 == base2.startIndex else {\n return Index(i1: i.i1, i2: base2.index(before: i.i2))\n }\n return Index(\n i1: base1.index(before: i.i1),\n i2: base2.index(before: base2.endIndex))\n }\n}\n\nextension Product2Sequence: RandomAccessCollection\nwhere Base1: RandomAccessCollection, Base2: RandomAccessCollection {}\n\nextension Product2Sequence.Index: Hashable\nwhere Base1.Index: Hashable, Base2.Index: Hashable {}\n\n//===----------------------------------------------------------------------===//\n// product(_:_:)\n//===----------------------------------------------------------------------===//\n\n/// Creates a sequence of each pair of elements of two underlying sequences.\n///\n/// Use this function to iterate over every pair of elements in two different\n/// collections. The returned sequence yields 2-element tuples, where the first\n/// element of the tuple is from the first collection and the second element is\n/// from the second collection.\n///\n/// let numbers = 1...3\n/// let colors = [\"cerise\", \"puce\", \"heliotrope\"]\n/// for (number, color) in product(numbers, colors) {\n/// print(\"\\(number): \\(color)\")\n/// }\n/// // 1: cerise\n/// // 1: puce\n/// // 1: heliotrope\n/// // 2: cerise\n/// // 2: puce\n/// // 2: heliotrope\n/// // 3: cerise\n/// // 3: puce\n/// // 3: heliotrope\n///\n/// The order of tuples in the returned sequence is consistent. The first\n/// element of the first collection is paired with each element of the second\n/// collection, then the second element of the first collection is paired with\n/// each element of the second collection, and so on.\n///\n/// - Parameters:\n/// - s1: The first sequence to iterate over.\n/// - s2: The second sequence to iterate over.\n/// - Returns: A sequence of tuples, with every combination of the elements\n/// of `s1` and `s2`, in order.\n///\n/// - Complexity: O(1)\n@inlinable\npublic func product<Base1: Sequence, Base2: Collection>(\n _ s1: Base1,\n _ s2: Base2\n) -> Product2Sequence<Base1, Base2> {\n Product2Sequence(s1, s2)\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Grouped.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Groups elements of this sequence into a new dictionary,\n /// whose values are arrays of grouped elements,\n /// each keyed by the key returned by the given closure.\n ///\n /// - Parameter keyForValue: A closure that returns a key for each element\n /// in the sequence.\n /// - Returns: A dictionary containing grouped elements of self, keyed by\n /// the keys derived by the `keyForValue` closure.\n @inlinable\n public func grouped<GroupKey>(\n by keyForValue: (Element) throws -> GroupKey\n ) rethrows -> [GroupKey: [Element]] {\n try Dictionary(grouping: self, by: keyForValue)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Reductions.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n// MARK: - Exclusive Reductions\n\nextension LazySequenceProtocol {\n /// Returns a sequence containing the accumulated results of combining the\n /// elements of the sequence using the given closure.\n ///\n /// This can be seen as applying the reduce function to each element and\n /// providing the initial value followed by these results as a sequence.\n ///\n /// ```\n /// let runningTotal = [1, 2, 3, 4].lazy.reductions(0, +)\n /// print(Array(runningTotal))\n ///\n /// // prints [0, 1, 3, 6, 10]\n /// ```\n ///\n /// - Parameters:\n /// - initial: The value to use as the initial value.\n /// - transform: A closure that combines the previously reduced result and\n /// the next element in the receiving sequence.\n /// - Returns: A sequence of the initial value followed by the reduced\n /// elements.\n ///\n /// - Complexity: O(1)\n @inlinable\n public func reductions<Result>(\n _ initial: Result,\n _ transform: @escaping (Result, Element) -> Result\n ) -> ExclusiveReductionsSequence<Elements, Result> {\n reductions(into: initial) { result, element in\n result = transform(result, element)\n }\n }\n\n /// Returns a sequence containing the accumulated results of combining the\n /// elements of the sequence using the given closure.\n ///\n /// This can be seen as applying the reduce function to each element and\n /// providing the initial value followed by these results as a sequence.\n ///\n /// ```\n /// let runningTotal = [1, 2, 3, 4].lazy.reductions(into: 0, +)\n /// print(Array(runningTotal))\n ///\n /// // prints [0, 1, 3, 6, 10]\n /// ```\n ///\n /// - Parameters:\n /// - initial: The value to use as the initial value.\n /// - transform: A closure that combines the previously reduced result and\n /// the next element in the receiving sequence.\n /// - Returns: A sequence of the initial value followed by the reduced\n /// elements.\n ///\n /// - Complexity: O(1)\n @inlinable\n public func reductions<Result>(\n into initial: Result,\n _ transform: @escaping (inout Result, Element) -> Void\n ) -> ExclusiveReductionsSequence<Elements, Result> {\n ExclusiveReductionsSequence(\n base: elements,\n initial: initial,\n transform: transform)\n }\n}\n\nextension Sequence {\n /// Returns an array containing the accumulated results of combining the\n /// elements of the sequence using the given closure.\n ///\n /// This can be seen as applying the reduce function to each element and\n /// providing the initial value followed by these results as a sequence.\n ///\n /// ```\n /// let runningTotal = [1, 2, 3, 4].reductions(0, +)\n /// print(runningTotal)\n ///\n /// // prints [0, 1, 3, 6, 10]\n /// ```\n ///\n /// When `reductions(_:_:)` is called, the following steps occur:\n ///\n /// 1. The `initial` result is added to an array of results.\n /// 2. The `transform` closure is called with the `initial` result and the\n /// first element of the sequence, appending the result to the array.\n /// 3. The closure is called again repeatedly with the updated accumulating\n /// result and each element of the sequence, adding each result to the\n /// array.\n /// 4. When the sequence is exhausted, the results array is returned to the\n /// caller.\n ///\n /// If the sequence has no elements, `transform` is never executed and\n /// an array containing only the `initial` result is returned.\n ///\n /// - Parameters:\n /// - initial: The value to use as the initial value.\n /// - transform: A closure that combines the previously reduced result and\n /// the next element in the receiving sequence.\n /// - Returns: An array of the initial value followed by the reduced elements.\n ///\n /// - Complexity: O(_n_), where _n_ is the length of the sequence.\n @inlinable\n public func reductions<Result>(\n _ initial: Result,\n _ transform: (Result, Element) throws -> Result\n ) rethrows -> [Result] {\n try reductions(into: initial) { result, element in\n result = try transform(result, element)\n }\n }\n\n /// Returns an array containing the accumulated results of combining the\n /// elements of the sequence using the given closure.\n ///\n /// This can be seen as applying the reduce function to each element and\n /// providing the initial value followed by these results as a sequence.\n ///\n /// ```\n /// let runningTotal = [1, 2, 3, 4].reductions(into: 0, +)\n /// print(runningTotal)\n ///\n /// // prints [0, 1, 3, 6, 10]\n /// ```\n ///\n /// When `reductions(into:_:_)` is called, the following steps occur:\n ///\n /// 1. The `initial` result is added to an array of results.\n /// 2. The `transform` closure is called with the `initial` result and the\n /// first element of the sequence, appending the result to the array.\n /// 3. The closure is called again repeatedly with the updated accumulating\n /// result and each element of the sequence, adding each result to the\n /// array.\n /// 4. When the sequence is exhausted, the results array is returned to the\n /// caller.\n ///\n /// If the sequence has no elements, `transform` is never executed and\n /// an array containing only the `initial` result is returned.\n ///\n /// - Parameters:\n /// - initial: The value to use as the initial value.\n /// - transform: A closure that combines the previously reduced result and\n /// the next element in the receiving sequence.\n /// - Returns: An array of the initial value followed by the reduced elements.\n ///\n /// - Complexity: O(_n_), where _n_ is the length of the sequence.\n @inlinable\n public func reductions<Result>(\n into initial: Result,\n _ transform: (inout Result, Element) throws -> Void\n ) rethrows -> [Result] {\n\n var output: [Result] = []\n output.reserveCapacity(underestimatedCount + 1)\n output.append(initial)\n\n var initial = initial\n for element in self {\n try transform(&initial, element)\n output.append(initial)\n }\n\n return output\n }\n}\n\n/// A sequence of applying a transform to the element of a sequence and the\n/// previously transformed result.\npublic struct ExclusiveReductionsSequence<Base: Sequence, Result> {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let initial: Result\n\n @usableFromInline\n internal let transform: (inout Result, Base.Element) -> Void\n\n @inlinable\n internal init(\n base: Base,\n initial: Result,\n transform: @escaping (inout Result, Base.Element) -> Void\n ) {\n self.base = base\n self.initial = initial\n self.transform = transform\n }\n}\n\nextension ExclusiveReductionsSequence: Sequence {\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal var iterator: Base.Iterator\n\n @usableFromInline\n internal var current: Result?\n\n @usableFromInline\n internal let transform: (inout Result, Base.Element) -> Void\n\n @inlinable\n internal init(\n iterator: Base.Iterator,\n current: Result? = nil,\n transform: @escaping (inout Result, Base.Element) -> Void\n ) {\n self.iterator = iterator\n self.current = current\n self.transform = transform\n }\n\n @inlinable\n public mutating func next() -> Result? {\n guard let result = current else { return nil }\n current = iterator.next().map { element in\n var result = result\n transform(&result, element)\n return result\n }\n return result\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(\n iterator: base.makeIterator(),\n current: initial,\n transform: transform)\n }\n}\n\nextension ExclusiveReductionsSequence: Collection where Base: Collection {\n public struct Index: Comparable {\n @usableFromInline\n internal enum Representation {\n case base(Base.Index, Result)\n case end\n }\n\n @usableFromInline\n internal let representation: Representation\n\n @inlinable\n internal init(_ representation: Representation) {\n self.representation = representation\n }\n\n @inlinable\n public static func == (lhs: Self, rhs: Self) -> Bool {\n switch (lhs.representation, rhs.representation) {\n case (.base(let lhs, _), .base(let rhs, _)):\n return lhs == rhs\n case (.end, .end):\n return true\n case (.base, .end), (.end, .base):\n return false\n }\n }\n\n @inlinable\n public static func < (lhs: Self, rhs: Self) -> Bool {\n switch (lhs.representation, rhs.representation) {\n case (.end, _):\n return false\n case (_, .end):\n return true\n case (.base(let lhs, _), .base(let rhs, _)):\n return lhs < rhs\n }\n }\n }\n\n @inlinable\n public var startIndex: Index {\n Index(.base(base.startIndex, initial))\n }\n\n @inlinable\n public var endIndex: Index {\n Index(.end)\n }\n\n @inlinable\n public subscript(position: Index) -> Result {\n switch position.representation {\n case .base(_, let result):\n return result\n case .end:\n fatalError(\"Cannot get element of end index.\")\n }\n }\n\n @inlinable\n public func index(after index: Index) -> Index {\n switch index.representation {\n case .base(base.endIndex, _):\n return Index(.end)\n case .base(let index, var result):\n transform(&result, base[index])\n return Index(.base(base.index(after: index), result))\n case .end:\n fatalError(\"Cannot get index after end index.\")\n }\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n switch (start.representation, end.representation) {\n case (.base(let start, _), .base(let end, _)):\n return base.distance(from: start, to: end)\n case (.base(let index, _), .end):\n return base.distance(from: index, to: base.endIndex) + 1\n case (.end, .base(let index, _)):\n return base.distance(from: base.endIndex, to: index) - 1\n case (.end, .end):\n return 0\n }\n }\n}\n\nextension ExclusiveReductionsSequence: LazySequenceProtocol {}\n\nextension ExclusiveReductionsSequence: LazyCollectionProtocol\nwhere Base: Collection {}\n\nextension ExclusiveReductionsSequence.Index: Hashable\nwhere Base.Index: Hashable {\n @inlinable\n public func hash(into hasher: inout Hasher) {\n switch representation {\n case .base(let base, _):\n hasher.combine(base)\n case .end:\n break\n }\n }\n}\n\n// MARK: - Inclusive Reductions\n\nextension LazySequenceProtocol {\n /// Returns a sequence containing the accumulated results of combining the\n /// elements of the sequence using the given closure.\n ///\n /// This can be seen as applying the reduce function to each element and\n /// providing the initial value followed by these results as a sequence.\n ///\n /// ```\n /// let runningTotal = [1, 2, 3, 4].lazy.reductions(+)\n /// print(Array(runningTotal))\n ///\n /// // prints [1, 3, 6, 10]\n /// ```\n ///\n /// - Parameter transform: A closure that combines the previously reduced\n /// result and the next element in the receiving sequence.\n /// - Returns: A sequence of the reduced elements.\n ///\n /// - Complexity: O(1)\n @inlinable\n public func reductions(\n _ transform: @escaping (Element, Element) -> Element\n ) -> InclusiveReductionsSequence<Elements> {\n InclusiveReductionsSequence(base: elements, transform: transform)\n }\n}\n\nextension Sequence {\n /// Returns an array containing the accumulated results of combining the\n /// elements of the sequence using the given closure.\n ///\n /// This can be seen as applying the reduce function to each element and\n /// providing the initial value followed by these results as a sequence.\n ///\n /// ```\n /// let runningTotal = [1, 2, 3, 4].reductions(+)\n /// print(runningTotal)\n ///\n /// // prints [1, 3, 6, 10]\n /// ```\n ///\n /// When `reductions(_:)` is called, the following steps occur:\n ///\n /// 1. The `transform` closure is called with the first and second elements\n /// of the sequence, appending the result to an array of results.\n /// 2. The closure is called again repeatedly with the updated accumulating\n /// result and the next element of the sequence, adding each result to the\n /// array.\n /// 3. When the sequence is exhausted, the results array is returned to the\n /// caller.\n ///\n /// If the sequence has no elements, `transform` is never executed and\n /// an empty array is returned.\n ///\n /// If the sequence has one element, `transform` is never executed and\n /// an array containing only that first element is returned.\n ///\n /// - Parameter transform: A closure that combines the previously reduced\n /// result and the next element in the receiving sequence.\n /// - Returns: An array of the reduced elements.\n ///\n /// - Complexity: O(_n_), where _n_ is the length of the sequence.\n @inlinable\n public func reductions(\n _ transform: (Element, Element) throws -> Element\n ) rethrows -> [Element] {\n var iterator = makeIterator()\n guard let initial = iterator.next() else { return [] }\n return try IteratorSequence(iterator).reductions(initial, transform)\n }\n}\n\npublic struct InclusiveReductionsSequence<Base: Sequence> {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let transform: (Base.Element, Base.Element) -> Base.Element\n\n @inlinable\n internal init(\n base: Base,\n transform: @escaping (Base.Element, Base.Element) -> Base.Element\n ) {\n self.base = base\n self.transform = transform\n }\n}\n\nextension InclusiveReductionsSequence: Sequence {\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal var iterator: Base.Iterator\n\n @usableFromInline\n internal var element: Base.Element?\n\n @usableFromInline\n internal let transform: (Base.Element, Base.Element) -> Base.Element\n\n @inlinable\n internal init(\n iterator: Base.Iterator,\n transform: @escaping (Base.Element, Base.Element) -> Base.Element\n ) {\n self.iterator = iterator\n self.transform = transform\n }\n\n @inlinable\n public mutating func next() -> Base.Element? {\n guard let previous = element else {\n element = iterator.next()\n return element\n }\n guard let next = iterator.next() else { return nil }\n element = transform(previous, next)\n return element\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(iterator: base.makeIterator(), transform: transform)\n }\n}\n\nextension InclusiveReductionsSequence: Collection where Base: Collection {\n public struct Index: Comparable {\n @usableFromInline\n internal let base: Base.Index\n\n @usableFromInline\n internal let result: Element?\n\n @inlinable\n internal init(base: Base.Index, result: Element?) {\n self.base = base\n self.result = result\n }\n\n @inlinable\n public static func < (lhs: Self, rhs: Self) -> Bool {\n lhs.base < rhs.base\n }\n\n @inlinable\n public static func == (lhs: Self, rhs: Self) -> Bool {\n lhs.base == rhs.base\n }\n }\n\n @inlinable\n public var startIndex: Index {\n Index(base: base.startIndex, result: base.first)\n }\n\n @inlinable\n public var endIndex: Index {\n Index(base: base.endIndex, result: nil)\n }\n\n @inlinable\n public subscript(index: Index) -> Base.Element {\n guard let result = index.result else {\n fatalError(\"Can't subscript using endIndex\")\n }\n\n return result\n }\n\n @inlinable\n public func index(after index: Index) -> Index {\n guard let result = index.result else {\n fatalError(\"Can't advance past endIndex\")\n }\n\n let index = base.index(after: index.base)\n let nextResult =\n index == base.endIndex\n ? nil\n : transform(result, base[index])\n\n return Index(base: index, result: nextResult)\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n base.distance(from: start.base, to: end.base)\n }\n}\n\nextension InclusiveReductionsSequence: LazySequenceProtocol {}\n\nextension InclusiveReductionsSequence: LazyCollectionProtocol\nwhere Base: Collection {}\n\nextension InclusiveReductionsSequence.Index: Hashable\nwhere Base.Index: Hashable {\n @inlinable\n public func hash(into hasher: inout Hasher) {\n hasher.combine(base)\n }\n}\n\n// MARK: - Scan\n\nextension LazySequenceProtocol {\n @available(*, deprecated, message: \"Use reductions(_:_:) instead.\")\n @inlinable\n public func scan<Result>(\n _ initial: Result,\n _ transform: @escaping (Result, Element) -> Result\n ) -> ExclusiveReductionsSequence<Elements, Result> {\n reductions(initial, transform)\n }\n\n @available(*, deprecated, message: \"Use reductions(into:_:) instead.\")\n @inlinable\n public func scan<Result>(\n into initial: Result,\n _ transform: @escaping (inout Result, Element) -> Void\n ) -> ExclusiveReductionsSequence<Elements, Result> {\n reductions(into: initial, transform)\n }\n}\n\nextension Sequence {\n @available(*, deprecated, message: \"Use reductions(_:_:) instead.\")\n @inlinable\n public func scan<Result>(\n _ initial: Result,\n _ transform: (Result, Element) throws -> Result\n ) rethrows -> [Result] {\n try reductions(initial, transform)\n }\n\n @available(*, deprecated, message: \"Use reductions(into:_:) instead.\")\n @inlinable\n public func scan<Result>(\n into initial: Result,\n _ transform: (inout Result, Element) throws -> Void\n ) rethrows -> [Result] {\n try reductions(into: initial, transform)\n }\n}\n\nextension LazySequenceProtocol {\n @available(*, deprecated, message: \"Use reductions(_:) instead.\")\n @inlinable\n public func scan(\n _ transform: @escaping (Element, Element) -> Element\n ) -> InclusiveReductionsSequence<Elements> {\n reductions(transform)\n }\n}\n\nextension Sequence {\n @available(*, deprecated, message: \"Use reductions(_:) instead.\")\n @inlinable\n public func scan(\n _ transform: (Element, Element) throws -> Element\n ) rethrows -> [Element] {\n try reductions(transform)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "RandomSample.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n// For log(_:) and root(_:_:)\n#if ALGORITHMS_DARWIN_ONLY\ninternal import Darwin\n\nextension Double {\n @_transparent\n internal static func root(_ x: Double, _ n: Int) -> Double {\n guard x >= 0 || n % 2 != 0 else { return .nan }\n if n == 3 { return cbrt(x) }\n return Double(signOf: x, magnitudeOf: pow(x.magnitude, 1 / Double(n)))\n }\n\n @_transparent\n internal static func log(_ x: Double) -> Double {\n Darwin.log(x)\n }\n\n @_transparent\n internal static func log(onePlus x: Double) -> Double {\n Darwin.log1p(x)\n }\n}\n#elseif swift(>=5.11)\ninternal import RealModule\n#elseif swift(>=5.10)\nimport RealModule\n#else\n@_implementationOnly import RealModule\n#endif\n\n//===----------------------------------------------------------------------===//\n// randomStableSample(count:)\n//===----------------------------------------------------------------------===//\n\nextension Collection {\n /// Randomly selects the specified number of elements from this collection,\n /// maintaining their relative order.\n ///\n /// - Parameters:\n /// - k: The number of elements to randomly select.\n /// - rng: The random number generator to use for the sampling.\n /// - Returns: An array of `k` random elements. If `k` is greater than this\n /// collection's count, then this method returns the full collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public func randomStableSample<G: RandomNumberGenerator>(\n count k: Int,\n using rng: inout G\n ) -> [Element] {\n guard k > 0 else { return [] }\n\n var remainingCount = count\n guard k < remainingCount else { return Array(self) }\n\n var result: [Element] = []\n result.reserveCapacity(k)\n\n var i = startIndex\n var countToSelect = k\n while countToSelect > 0 {\n let r = Int.random(in: 0..<remainingCount, using: &rng)\n if r < countToSelect {\n result.append(self[i])\n countToSelect -= 1\n }\n\n formIndex(after: &i)\n remainingCount -= 1\n }\n\n return result\n }\n\n /// Randomly selects the specified number of elements from this collection,\n /// maintaining their relative order.\n ///\n /// This method is equivalent to calling `randomStableSample(k:using:)`,\n /// passing in the system's default random generator.\n ///\n /// - Parameter k: The number of elements to randomly select.\n /// - Returns: An array of `k` random elements. If `k` is greater than this\n /// collection's count, then this method returns the full collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public func randomStableSample(count k: Int) -> [Element] {\n var g = SystemRandomNumberGenerator()\n return randomStableSample(count: k, using: &g)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// randomSample(count:)\n//===----------------------------------------------------------------------===//\n\n// These methods use Algorithm L, described in \"Reservoir-Sampling\n// Algorithms of Time Complexity O(n(1 + log(N/n)))\":\n// https://dl.acm.org/doi/pdf/10.1145/198429.198435\n\n@usableFromInline\ninternal func nextW<G: RandomNumberGenerator>(\n k: Int,\n using rng: inout G\n) -> Double {\n Double.root(.random(in: 0..<1, using: &rng), k)\n}\n\n@usableFromInline\ninternal func nextOffset<G: RandomNumberGenerator>(\n w: Double,\n using rng: inout G\n) -> Int {\n let offset = Double.log(.random(in: 0..<1, using: &rng)) / .log(onePlus: -w)\n return offset < Double(Int.max) ? Int(offset) : Int.max\n}\n\nextension Collection {\n /// Randomly selects the specified number of elements from this collection.\n ///\n /// - Parameters:\n /// - k: The number of elements to randomly select.\n /// - rng: The random number generator to use for the sampling.\n /// - Returns: An array of `k` random elements. The returned elements may be\n /// in any order. If `k` is greater than this collection's count, then this\n /// method returns the full collection.\n ///\n /// - Complexity: O(*k*), where *k* is the number of elements to select, if\n /// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),\n /// where *n* is the length of the collection.\n @inlinable\n public func randomSample<G: RandomNumberGenerator>(\n count k: Int,\n using rng: inout G\n ) -> [Element] {\n guard k > 0 else { return [] }\n\n var w = 1.0\n var result: [Element] = []\n result.reserveCapacity(k)\n\n // Fill the reservoir with the first `k` elements.\n var i = startIndex\n while i != endIndex, result.count < k {\n result.append(self[i])\n formIndex(after: &i)\n }\n\n while i != endIndex {\n // Calculate the next value of w.\n w *= nextW(k: k, using: &rng)\n\n // Find index of the next element to swap into the reservoir.\n let offset = nextOffset(w: w, using: &rng)\n i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex\n\n if i != endIndex {\n // Swap selected element with a randomly chosen one in the reservoir.\n let j = Int.random(in: 0..<result.count, using: &rng)\n result[j] = self[i]\n formIndex(after: &i)\n }\n }\n\n // FIXME: necessary?\n result.shuffle(using: &rng)\n return result\n }\n\n /// Randomly selects the specified number of elements from this collection.\n ///\n /// This method is equivalent to calling `randomSample(k:using:)`, passing in\n /// the system's default random generator.\n ///\n /// - Parameter k: The number of elements to randomly select.\n /// - Returns: An array of `k` random elements. The returned elements may be\n /// in any order. If `k` is greater than this collection's count, then this\n /// method returns the full collection.\n ///\n /// - Complexity: O(*k*), where *k* is the number of elements to select, if\n /// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),\n /// where *n* is the length of the collection.\n @inlinable\n public func randomSample(count k: Int) -> [Element] {\n var g = SystemRandomNumberGenerator()\n return randomSample(count: k, using: &g)\n }\n}\n\nextension Sequence {\n /// Randomly selects the specified number of elements from this sequence.\n ///\n /// - Parameters:\n /// - k: The number of elements to randomly select.\n /// - rng: The random number generator to use for the sampling.\n /// - Returns: An array of `k` random elements. The returned elements may be\n /// in any order. If `k` is greater than this sequence's count, then this\n /// method returns the full sequence.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public func randomSample<G: RandomNumberGenerator>(\n count k: Int,\n using rng: inout G\n ) -> [Element] {\n guard k > 0 else { return [] }\n\n var w = 1.0\n var result: [Element] = []\n result.reserveCapacity(k)\n\n // Fill the reservoir with the first `k` elements.\n var iterator = makeIterator()\n while result.count < k, let el = iterator.next() {\n result.append(el)\n }\n\n while true {\n // Calculate the next value of w.\n w *= nextW(k: k, using: &rng)\n\n // Find the offset of the next element to swap into the reservoir.\n var offset = nextOffset(w: w, using: &rng)\n\n // Skip over `offset` elements to find the selected element.\n while offset > 0, iterator.next() != nil {\n offset -= 1\n }\n guard let nextElement = iterator.next() else { break }\n\n // Swap selected element with a randomly chosen one in the reservoir.\n let j = Int.random(in: 0..<result.count, using: &rng)\n result[j] = nextElement\n }\n\n // FIXME: necessary?\n result.shuffle(using: &rng)\n return result\n }\n\n /// Randomly selects the specified number of elements from this sequence.\n ///\n /// This method is equivalent to calling `randomSample(k:using:)`, passing in\n /// the system's default random generator.\n ///\n /// - Parameter k: The number of elements to randomly select.\n /// - Returns: An array of `k` random elements. The returned elements may be\n /// in any order. If `k` is greater than this sequence's count, then this\n /// method returns the full sequence.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public func randomSample(count k: Int) -> [Element] {\n var g = SystemRandomNumberGenerator()\n return randomSample(count: k, using: &g)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Joined.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// JoinedBySequence\n//===----------------------------------------------------------------------===//\n\n/// A sequence that presents the elements of a base sequence of sequences\n/// concatenated using a given separator.\npublic struct JoinedBySequence<Base: Sequence, Separator: Sequence>\nwhere Base.Element: Sequence, Base.Element.Element == Separator.Element {\n @usableFromInline\n internal typealias Inner = FlattenSequence<\n InterspersedSequence<\n LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>\n >\n >\n\n @usableFromInline\n internal let inner: Inner\n\n @inlinable\n internal init(base: Base, separator: Separator) {\n self.inner = base.lazy\n .map(EitherSequence.left)\n .interspersed(with: .right(separator))\n .joined()\n }\n}\n\nextension JoinedBySequence: Sequence {\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal var inner: Inner.Iterator\n\n @inlinable\n internal init(inner: Inner.Iterator) {\n self.inner = inner\n }\n\n @inlinable\n public mutating func next() -> Base.Element.Element? {\n inner.next()\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(inner: inner.makeIterator())\n }\n}\n\nextension JoinedBySequence: LazySequenceProtocol\nwhere Base: LazySequenceProtocol {}\n\n//===----------------------------------------------------------------------===//\n// JoinedByClosureSequence\n//===----------------------------------------------------------------------===//\n\n/// A sequence that presents the elements of a base sequence of sequences\n/// concatenated using a given separator that depends on the sequences right\n/// before and after it.\npublic struct JoinedByClosureSequence<Base: Sequence, Separator: Sequence>\nwhere Base.Element: Sequence, Base.Element.Element == Separator.Element {\n @usableFromInline\n internal typealias Inner = FlattenSequence<\n InterspersedMapSequence<\n Base, EitherSequence<Base.Element, Separator>\n >\n >\n\n @usableFromInline\n internal let inner: Inner\n\n @inlinable\n internal init(\n base: Base,\n separator: @escaping (Base.Element, Base.Element) -> Separator\n ) {\n self.inner = base.lazy\n .interspersedMap(\n EitherSequence.left,\n with: { EitherSequence.right(separator($0, $1)) }\n )\n .joined()\n }\n}\n\nextension JoinedByClosureSequence: Sequence {\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal var inner: Inner.Iterator\n\n @inlinable\n internal init(inner: Inner.Iterator) {\n self.inner = inner\n }\n\n @inlinable\n public mutating func next() -> Base.Element.Element? {\n inner.next()\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(inner: inner.makeIterator())\n }\n}\n\nextension JoinedByClosureSequence: LazySequenceProtocol {}\n\n//===----------------------------------------------------------------------===//\n// JoinedByCollection\n//===----------------------------------------------------------------------===//\n\n/// A collection that presents the elements of a base collection of collections\n/// concatenated using a given separator.\npublic struct JoinedByCollection<Base: Collection, Separator: Collection>\nwhere Base.Element: Collection, Base.Element.Element == Separator.Element {\n @usableFromInline\n internal typealias Inner = FlattenCollection<\n InterspersedSequence<\n LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>\n >\n >\n\n @usableFromInline\n internal let inner: Inner\n\n @inlinable\n internal init(base: Base, separator: Separator) {\n self.inner = base.lazy\n .map(EitherSequence.left)\n .interspersed(with: .right(separator))\n .joined()\n }\n}\n\nextension JoinedByCollection: Collection {\n public struct Index: Comparable {\n @usableFromInline\n internal let inner: Inner.Index\n\n @inlinable\n internal init(_ inner: Inner.Index) {\n self.inner = inner\n }\n\n @inlinable\n public static func == (lhs: Self, rhs: Self) -> Bool {\n lhs.inner == rhs.inner\n }\n\n @inlinable\n public static func < (lhs: Self, rhs: Self) -> Bool {\n lhs.inner < rhs.inner\n }\n }\n\n @inlinable\n public var startIndex: Index {\n Index(inner.startIndex)\n }\n\n @inlinable\n public var endIndex: Index {\n Index(inner.endIndex)\n }\n\n @inlinable\n public func index(after index: Index) -> Index {\n Index(inner.index(after: index.inner))\n }\n\n @inlinable\n public subscript(position: Index) -> Base.Element.Element {\n inner[position.inner]\n }\n\n @inlinable\n public func index(_ index: Index, offsetBy distance: Int) -> Index {\n Index(inner.index(index.inner, offsetBy: distance))\n }\n\n @inlinable\n public func index(\n _ index: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n inner.index(index.inner, offsetBy: distance, limitedBy: limit.inner)\n .map(Index.init)\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n inner.distance(from: start.inner, to: end.inner)\n }\n}\n\nextension JoinedByCollection: BidirectionalCollection\nwhere\n Base: BidirectionalCollection,\n Base.Element: BidirectionalCollection,\n Separator: BidirectionalCollection\n{\n @inlinable\n public func index(before index: Index) -> Index {\n Index(inner.index(before: index.inner))\n }\n}\n\nextension JoinedByCollection: LazySequenceProtocol, LazyCollectionProtocol\nwhere Base: LazySequenceProtocol {}\n\n//===----------------------------------------------------------------------===//\n// JoinedByClosureCollection\n//===----------------------------------------------------------------------===//\n\n/// A collection that presents the elements of a base collection of collections\n/// concatenated using a given separator that depends on the collections right\n/// before and after it.\npublic struct JoinedByClosureCollection<Base: Collection, Separator: Collection>\nwhere Base.Element: Collection, Base.Element.Element == Separator.Element {\n @usableFromInline\n internal typealias Inner = FlattenCollection<\n InterspersedMapSequence<\n Base, EitherSequence<Base.Element, Separator>\n >\n >\n\n @usableFromInline\n internal let inner: Inner\n\n @inlinable\n internal init(\n base: Base,\n separator: @escaping (Base.Element, Base.Element) -> Separator\n ) {\n self.inner = base.lazy\n .interspersedMap(\n EitherSequence.left,\n with: { EitherSequence.right(separator($0, $1)) }\n )\n .joined()\n }\n}\n\nextension JoinedByClosureCollection: Collection {\n public struct Index: Comparable {\n @usableFromInline\n internal let inner: Inner.Index\n\n @inlinable\n internal init(_ inner: Inner.Index) {\n self.inner = inner\n }\n\n @inlinable\n public static func == (lhs: Self, rhs: Self) -> Bool {\n lhs.inner == rhs.inner\n }\n\n @inlinable\n public static func < (lhs: Self, rhs: Self) -> Bool {\n lhs.inner < rhs.inner\n }\n }\n\n @inlinable\n public var startIndex: Index {\n Index(inner.startIndex)\n }\n\n @inlinable\n public var endIndex: Index {\n Index(inner.endIndex)\n }\n\n @inlinable\n public func index(after index: Index) -> Index {\n Index(inner.index(after: index.inner))\n }\n\n @inlinable\n public subscript(position: Index) -> Base.Element.Element {\n inner[position.inner]\n }\n\n @inlinable\n public func index(_ index: Index, offsetBy distance: Int) -> Index {\n Index(inner.index(index.inner, offsetBy: distance))\n }\n\n @inlinable\n public func index(\n _ index: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n inner.index(index.inner, offsetBy: distance, limitedBy: limit.inner)\n .map(Index.init)\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n inner.distance(from: start.inner, to: end.inner)\n }\n}\n\nextension JoinedByClosureCollection: BidirectionalCollection\nwhere\n Base: BidirectionalCollection,\n Base.Element: BidirectionalCollection,\n Separator: BidirectionalCollection\n{\n @inlinable\n public func index(before index: Index) -> Index {\n Index(inner.index(before: index.inner))\n }\n}\n\nextension JoinedByClosureCollection: LazyCollectionProtocol {}\n\n//===----------------------------------------------------------------------===//\n// Sequence.joined(by:)\n//===----------------------------------------------------------------------===//\n\nextension Sequence where Element: Sequence {\n /// Returns the concatenation of the elements in this sequence of sequences,\n /// inserting the given separator between each sequence.\n ///\n /// for x in [[1, 2], [3, 4], [5, 6]].joined(by: 100) {\n /// print(x)\n /// }\n /// // 1, 2, 100, 3, 4, 100, 5, 6\n @inlinable\n public func joined(by separator: Element.Element)\n -> JoinedBySequence<Self, CollectionOfOne<Element.Element>>\n {\n joined(by: CollectionOfOne(separator))\n }\n\n /// Returns the concatenation of the elements in this sequence of sequences,\n /// inserting the given separator between each sequence.\n ///\n /// for x in [[1, 2], [3, 4], [5, 6]].joined(by: [100, 200]) {\n /// print(x)\n /// }\n /// // 1, 2, 100, 200, 3, 4, 100, 200, 5, 6\n @inlinable\n public func joined<Separator>(\n by separator: Separator\n ) -> JoinedBySequence<Self, Separator>\n where Separator: Collection, Separator.Element == Element.Element {\n JoinedBySequence(base: self, separator: separator)\n }\n\n @inlinable\n internal func _joined(\n by update: (inout [Element.Element], Element, Element) throws -> Void\n ) rethrows -> [Element.Element] {\n var iterator = makeIterator()\n guard let first = iterator.next() else { return [] }\n\n var result = Array(first)\n var previous = first\n\n while let next = iterator.next() {\n try update(&result, previous, next)\n result.append(contentsOf: next)\n previous = next\n }\n\n return result\n }\n\n /// Returns the concatenation of the elements in this sequence of sequences,\n /// inserting the separator produced by the closure between each sequence.\n ///\n /// for x in [[1, 2], [3, 4], [5, 6]].joined(by: { $0.last! * $1.first! }) {\n /// print(x)\n /// }\n /// // 1, 2, 6, 3, 4, 20, 5, 6\n @inlinable\n public func joined(\n by separator: (Element, Element) throws -> Element.Element\n ) rethrows -> [Element.Element] {\n try _joined(by: { $0.append(try separator($1, $2)) })\n }\n\n /// Returns the concatenation of the elements in this sequence of sequences,\n /// inserting the separator produced by the closure between each sequence.\n ///\n /// for x in [[1, 2], [3, 4], [5, 6]].joined(by: { [100 * $0.last!, 100 * $1.first!] }) {\n /// print(x)\n /// }\n /// // 1, 2, 200, 300, 3, 4, 400, 500, 5, 6\n @inlinable\n public func joined<Separator>(\n by separator: (Element, Element) throws -> Separator\n ) rethrows -> [Element.Element]\n where Separator: Sequence, Separator.Element == Element.Element {\n try _joined(by: { $0.append(contentsOf: try separator($1, $2)) })\n }\n}\n\n//===----------------------------------------------------------------------===//\n// LazySequenceProtocol.joined(by:)\n//===----------------------------------------------------------------------===//\n\nextension LazySequenceProtocol where Element: Sequence {\n /// Returns the concatenation of the elements in this sequence of sequences,\n /// inserting the separator produced by the closure between each sequence.\n @inlinable\n public func joined(\n by separator: @escaping (Element, Element) -> Element.Element\n ) -> JoinedByClosureSequence<Elements, CollectionOfOne<Element.Element>> {\n joined(by: { CollectionOfOne(separator($0, $1)) })\n }\n\n /// Returns the concatenation of the elements in this sequence of sequences,\n /// inserting the separator produced by the closure between each sequence.\n @inlinable\n public func joined<Separator>(\n by separator: @escaping (Element, Element) -> Separator\n ) -> JoinedByClosureSequence<Elements, Separator> {\n JoinedByClosureSequence(base: elements, separator: separator)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Collection.joined(by:)\n//===----------------------------------------------------------------------===//\n\nextension Collection where Element: Collection {\n /// Returns the concatenation of the elements in this collection of\n /// collections, inserting the given separator between each collection.\n ///\n /// for x in [[1, 2], [3, 4], [5, 6]].joined(by: 100) {\n /// print(x)\n /// }\n /// // 1, 2, 100, 3, 4, 100, 5, 6\n @inlinable\n public func joined(by separator: Element.Element)\n -> JoinedByCollection<Self, CollectionOfOne<Element.Element>>\n {\n joined(by: CollectionOfOne(separator))\n }\n\n /// Returns the concatenation of the elements in this collection of\n /// collections, inserting the given separator between each collection.\n ///\n /// for x in [[1, 2], [3, 4], [5, 6]].joined(by: [100, 200]) {\n /// print(x)\n /// }\n /// // 1, 2, 100, 200, 3, 4, 100, 200, 5, 6\n @inlinable\n public func joined<Separator>(by separator: Separator)\n -> JoinedByCollection<Self, Separator>\n {\n JoinedByCollection(base: self, separator: separator)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// LazySequenceProtocol.joined(by:) where Self: Collection\n//===----------------------------------------------------------------------===//\n\nextension LazySequenceProtocol where Elements: Collection, Element: Collection {\n /// Returns the concatenation of the elements in this collection of\n /// collections, inserting the separator produced by the closure between each\n /// sequence.\n @inlinable\n public func joined(\n by separator: @escaping (Element, Element) -> Element.Element\n ) -> JoinedByClosureCollection<Elements, CollectionOfOne<Element.Element>> {\n joined(by: { CollectionOfOne(separator($0, $1)) })\n }\n\n /// Returns the concatenation of the elements in this collection of\n /// collections, inserting the separator produced by the closure between each\n /// sequence.\n @inlinable\n public func joined<Separator>(\n by separator: @escaping (Element, Element) -> Separator\n ) -> JoinedByClosureCollection<Elements, Separator> {\n JoinedByClosureCollection(base: elements, separator: separator)\n }\n}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Windows.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// windows(ofCount:)\n//===----------------------------------------------------------------------===//\n\nextension Collection {\n /// Returns a collection of all the overlapping slices of a given size.\n ///\n /// Use this method to iterate over overlapping subsequences of this\n /// collection. This example prints every five character substring of `str`:\n ///\n /// let str = \"Hello, world!\"\n /// for substring in str.windows(ofCount: 5) {\n /// print(substring)\n /// }\n /// // \"Hello\"\n /// // \"ello,\"\n /// // \"llo, \"\n /// // \"lo, W\"\n /// // ...\n /// // \"orld!\"\n ///\n /// - Parameter count: The number of elements in each window subsequence.\n /// - Returns: A collection of subsequences of this collection, each with\n /// length `count`. If this collection is shorter than `count`, the\n /// resulting collection is empty.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`.\n /// Access to successive windows is O(1).\n @inlinable\n public func windows(ofCount count: Int) -> WindowsOfCountCollection<Self> {\n WindowsOfCountCollection(base: self, windowSize: count)\n }\n}\n\n/// A collection wrapper that presents a sliding window over the elements of\n/// a collection.\npublic struct WindowsOfCountCollection<Base: Collection> {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let windowSize: Int\n\n @usableFromInline\n internal var endOfFirstWindow: Base.Index?\n\n @inlinable\n internal init(base: Base, windowSize: Int) {\n precondition(windowSize > 0, \"Windows size must be greater than zero\")\n self.base = base\n self.windowSize = windowSize\n self.endOfFirstWindow =\n base\n .index(base.startIndex, offsetBy: windowSize, limitedBy: base.endIndex)\n }\n}\n\nextension WindowsOfCountCollection: Collection {\n /// A position in a `WindowsOfCountCollection` instance.\n public struct Index: Comparable {\n @usableFromInline\n internal var lowerBound: Base.Index\n\n @usableFromInline\n internal var upperBound: Base.Index\n\n @inlinable\n internal init(lowerBound: Base.Index, upperBound: Base.Index) {\n self.lowerBound = lowerBound\n self.upperBound = upperBound\n }\n\n @inlinable\n public static func == (lhs: Index, rhs: Index) -> Bool {\n lhs.lowerBound == rhs.lowerBound\n }\n\n @inlinable\n public static func < (lhs: Index, rhs: Index) -> Bool {\n lhs.lowerBound < rhs.lowerBound\n }\n }\n\n @inlinable\n public var startIndex: Index {\n guard let upperBound = endOfFirstWindow else {\n return endIndex\n }\n return Index(lowerBound: base.startIndex, upperBound: upperBound)\n }\n\n @inlinable\n public var endIndex: Index {\n Index(lowerBound: base.endIndex, upperBound: base.endIndex)\n }\n\n @inlinable\n public subscript(index: Index) -> Base.SubSequence {\n precondition(\n index.lowerBound != index.upperBound,\n \"Windows index is out of range\")\n return base[index.lowerBound..<index.upperBound]\n }\n\n @inlinable\n public func index(after index: Index) -> Index {\n precondition(index != endIndex, \"Advancing past end index\")\n guard index.upperBound < base.endIndex else { return endIndex }\n\n let lowerBound =\n windowSize == 1\n ? index.upperBound\n : base.index(after: index.lowerBound)\n let upperBound = base.index(after: index.upperBound)\n return Index(lowerBound: lowerBound, upperBound: upperBound)\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n guard distance != 0 else { return i }\n\n return distance > 0\n ? offsetForward(i, by: distance)\n : offsetBackward(i, by: -distance)\n }\n\n @inlinable\n public func index(\n _ i: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n guard distance != 0 else { return i }\n guard limit != i else { return nil }\n\n if distance > 0 {\n return limit > i\n ? offsetForward(i, by: distance, limitedBy: limit)\n : offsetForward(i, by: distance)\n } else {\n return limit < i\n ? offsetBackward(i, by: -distance, limitedBy: limit)\n : offsetBackward(i, by: -distance)\n }\n }\n\n @inlinable\n internal func offsetForward(_ i: Index, by distance: Int) -> Index {\n guard let index = offsetForward(i, by: distance, limitedBy: endIndex)\n else { fatalError(\"Index is out of bounds\") }\n return index\n }\n\n @inlinable\n internal func offsetBackward(_ i: Index, by distance: Int) -> Index {\n guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)\n else { fatalError(\"Index is out of bounds\") }\n return index\n }\n\n @inlinable\n internal func offsetForward(\n _ i: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance > 0)\n assert(limit > i)\n\n // `endIndex` and the index before it both have `base.endIndex` as their\n // upper bound, so we first advance to the base index _before_ the upper\n // bound of the output, in order to avoid advancing past the end of `base`\n // when advancing to `endIndex`.\n //\n // Advancing by 4:\n //\n // input: [x|x x x x x|x x x x] [x x|x x x x x|x x x]\n // |> > >|>| or |> > >|\n // output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`)\n\n if distance >= windowSize {\n // Avoid traversing `self[i.lowerBound..<i.upperBound]` when the lower\n // bound of the output is greater than or equal to the upper bound of the\n // input.\n\n // input: [x|x x x x|x x x x x x x]\n // |> >|> > >|>|\n // output: [x x x x x x x|x x x x|x]\n\n guard limit.lowerBound >= i.upperBound,\n let lowerBound = base.index(\n i.upperBound,\n offsetBy: distance - windowSize,\n limitedBy: limit.lowerBound),\n let indexBeforeUpperBound = base.index(\n lowerBound,\n offsetBy: windowSize - 1,\n limitedBy: limit.upperBound)\n else { return nil }\n\n // If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to\n // `endIndex`.\n guard indexBeforeUpperBound != base.endIndex else { return endIndex }\n\n return Index(\n lowerBound: lowerBound,\n upperBound: base.index(after: indexBeforeUpperBound))\n } else {\n // input: [x|x x x x x x|x x x x x]\n // |> > > >| |> > >|>|\n // output: [x x x x x|x x x x x x|x]\n\n guard\n let indexBeforeUpperBound = base.index(\n i.upperBound,\n offsetBy: distance - 1,\n limitedBy: limit.upperBound)\n else { return nil }\n\n // If `indexBeforeUpperBound` equals the limit, the upper bound itself\n // exceeds it.\n guard indexBeforeUpperBound != limit.upperBound || limit == endIndex\n else { return nil }\n\n // If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to\n // `endIndex`.\n guard indexBeforeUpperBound != base.endIndex else { return endIndex }\n\n return Index(\n lowerBound: base.index(i.lowerBound, offsetBy: distance),\n upperBound: base.index(after: indexBeforeUpperBound))\n }\n }\n\n @inlinable\n internal func offsetBackward(\n _ i: Index,\n by distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n assert(distance > 0)\n assert(limit < i)\n\n if i == endIndex {\n // Advance `base.endIndex` by `distance - 1`, because the index before\n // `endIndex` also has `base.endIndex` as its upper bound.\n //\n // Advancing by 4:\n //\n // input: [x x x x x x x x x x] (`endIndex`)\n // |< < < < <|< < <|\n // output: [x x|x x x x x|x x x]\n\n guard\n let upperBound = base.index(\n base.endIndex,\n offsetBy: -(distance - 1),\n limitedBy: limit.upperBound)\n else { return nil }\n\n return Index(\n lowerBound: base.index(upperBound, offsetBy: -windowSize),\n upperBound: upperBound)\n } else if distance >= windowSize {\n // Avoid traversing `self[i.lowerBound..<i.upperBound]` when the upper\n // bound of the output is less than or equal to the lower bound of the\n // input.\n //\n // input: [x x x x x x x|x x x x|x]\n // |< < < <|< <|\n // output: [x|x x x x|x x x x x x x]\n\n guard limit.upperBound <= i.lowerBound,\n let upperBound = base.index(\n i.lowerBound,\n offsetBy: -(distance - windowSize),\n limitedBy: limit.upperBound)\n else { return nil }\n\n return Index(\n lowerBound: base.index(upperBound, offsetBy: -windowSize),\n upperBound: upperBound)\n } else {\n // input: [x x x x x|x x x x x x|x]\n // |< < < <| |< < < <|\n // output: [x|x x x x x x|x x x x x]\n\n guard\n let lowerBound = base.index(\n i.lowerBound,\n offsetBy: -distance,\n limitedBy: limit.lowerBound)\n else { return nil }\n\n return Index(\n lowerBound: lowerBound,\n upperBound: base.index(i.lowerBound, offsetBy: -distance))\n }\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n guard start <= end else { return -distance(from: end, to: start) }\n guard start != end else { return 0 }\n guard end != endIndex else {\n // We add 1 here because the index before `endIndex` also has\n // `base.endIndex` as its upper bound.\n return base[start.upperBound...].count + 1\n }\n\n if start.upperBound <= end.lowerBound {\n // The distance between `start.lowerBound` and `start.upperBound` is\n // already known.\n //\n // start: [x|x x x x|x x x x x x x]\n // |- - - -|> >|\n // end: [x x x x x x x|x x x x|x]\n\n return windowSize + base[start.upperBound..<end.lowerBound].count\n } else {\n // start: [x|x x x x x x|x x x x x]\n // |> > > >|\n // end: [x x x x x|x x x x x x|x]\n\n return base[start.lowerBound..<end.lowerBound].count\n }\n }\n}\n\nextension WindowsOfCountCollection: BidirectionalCollection\nwhere Base: BidirectionalCollection {\n @inlinable\n public func index(before index: Index) -> Index {\n precondition(index != startIndex, \"Decrementing past start index\")\n if index == endIndex {\n return Index(\n lowerBound: base.index(index.lowerBound, offsetBy: -windowSize),\n upperBound: index.upperBound)\n } else {\n return Index(\n lowerBound: base.index(before: index.lowerBound),\n upperBound: base.index(before: index.upperBound))\n }\n }\n}\n\nextension WindowsOfCountCollection: RandomAccessCollection\nwhere Base: RandomAccessCollection {}\n\nextension WindowsOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol\nwhere Base: LazySequenceProtocol {}\n\nextension WindowsOfCountCollection.Index: Hashable where Base.Index: Hashable {}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Stride.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// striding(by:)\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns a sequence stepping through the elements every `step` starting at\n /// the first value.\n ///\n /// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]\n /// (0...10).striding(by: 3) // == [0, 3, 6, 9]\n ///\n /// - Complexity: O(1). Access to successive values is O(k) where _k_ is the\n /// striding `step`.\n ///\n /// - Parameter step: The amount to step with each iteration.\n /// - Returns: A sequence for stepping through the elements by the specified\n /// amount. Any remaining elements after the last multiple of the stride\n /// are omitted.\n @inlinable\n public func striding(by step: Int) -> StridingSequence<Self> {\n StridingSequence(base: self, stride: step)\n }\n}\n\nextension Collection {\n /// Returns a sequence stepping through the elements every `step` starting at\n /// the first value.\n ///\n /// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]\n /// (0...10).striding(by: 3) // == [0, 3, 6, 9]\n ///\n /// - Complexity: O(1). Access to successive values is O(k) where _k_ is the\n /// striding `step`.\n ///\n /// - Parameter step: The amount to step with each iteration.\n /// - Returns: A sequence for stepping through the elements by the specified\n /// amount. Any remaining elements after the last multiple of the stride\n /// are omitted.\n @inlinable\n public func striding(by step: Int) -> StridingCollection<Self> {\n StridingCollection(base: self, stride: step)\n }\n}\n\n/// A wrapper that strides over a base sequence.\npublic struct StridingSequence<Base: Sequence> {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let stride: Int\n\n @inlinable\n internal init(base: Base, stride: Int) {\n precondition(stride > 0, \"Stride must be greater than zero\")\n self.base = base\n self.stride = stride\n }\n}\n\nextension StridingSequence {\n @inlinable\n public func striding(by step: Int) -> Self {\n Self(base: base, stride: stride * step)\n }\n}\n\nextension StridingSequence: Sequence {\n /// An iterator over a `StridingSequence` instance.\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal var iterator: Base.Iterator\n\n @usableFromInline\n internal let stride: Int\n\n @usableFromInline\n internal var striding: Bool = false\n\n @inlinable\n internal init(iterator: Base.Iterator, stride: Int) {\n self.iterator = iterator\n self.stride = stride\n }\n\n @inlinable\n public mutating func next() -> Base.Element? {\n guard striding else {\n striding = true\n return iterator.next()\n }\n for _ in 0..<stride - 1 {\n guard iterator.next() != nil else { break }\n }\n return iterator.next()\n }\n }\n\n @inlinable\n public func makeIterator() -> Iterator {\n Iterator(iterator: base.makeIterator(), stride: stride)\n }\n}\n\nextension StridingSequence: LazySequenceProtocol\nwhere Base: LazySequenceProtocol {}\n\n/// A wrapper that strides over a base collection.\npublic struct StridingCollection<Base: Collection> {\n @usableFromInline\n internal let base: Base\n\n @usableFromInline\n internal let stride: Int\n\n @inlinable\n internal init(base: Base, stride: Int) {\n precondition(stride > 0, \"striding must be greater than zero\")\n self.base = base\n self.stride = stride\n }\n}\n\nextension StridingCollection {\n @inlinable\n public func striding(by step: Int) -> Self {\n Self(base: base, stride: stride * step)\n }\n}\n\nextension StridingCollection: Collection {\n /// A position in a `StridingCollection` instance.\n public struct Index: Comparable {\n @usableFromInline\n internal let base: Base.Index\n\n @usableFromInline\n internal init(_ base: Base.Index) {\n self.base = base\n }\n\n @inlinable\n public static func < (lhs: Index, rhs: Index) -> Bool {\n lhs.base < rhs.base\n }\n }\n\n @inlinable\n public var startIndex: Index {\n Index(base.startIndex)\n }\n\n @inlinable\n public var endIndex: Index {\n Index(base.endIndex)\n }\n\n @inlinable\n public subscript(i: Index) -> Base.Element {\n base[i.base]\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n precondition(i.base != base.endIndex, \"Advancing past end index\")\n return index(i, offsetBy: 1)\n }\n\n @inlinable\n public func index(\n _ i: Index,\n offsetBy n: Int,\n limitedBy limit: Index\n ) -> Index? {\n guard n != 0 else { return i }\n guard limit != i else { return nil }\n\n return n > 0\n ? offsetForward(i, offsetBy: n, limitedBy: limit)\n : offsetBackward(i, offsetBy: -n, limitedBy: limit)\n }\n\n @inlinable\n internal func offsetForward(\n _ i: Index,\n offsetBy n: Int,\n limitedBy limit: Index\n ) -> Index? {\n if limit < i {\n guard\n let idx = base.index(\n i.base,\n offsetBy: n * stride,\n limitedBy: base.endIndex\n )\n else {\n assert(distance(from: i, to: endIndex) == n, \"Advancing past end index\")\n return endIndex\n }\n return Index(idx)\n } else if let idx = base.index(\n i.base,\n offsetBy: n * stride,\n limitedBy: limit.base\n ) {\n return Index(idx)\n } else {\n return distance(from: i, to: limit) == n\n ? endIndex\n : nil\n }\n }\n\n @inlinable\n internal func offsetBackward(\n _ i: Index,\n offsetBy n: Int,\n limitedBy limit: Index\n ) -> Index? {\n // We typically use the ternary operator but this significantly increases\n // compile times when using Swift 5.3.2\n // https://github.com/apple/swift-algorithms/issues/146\n let distance: Int\n if i == endIndex {\n distance = -((base.count - 1) % stride + 1) + (n - 1) * -stride\n } else {\n distance = n * -stride\n }\n return base.index(\n i.base,\n offsetBy: distance,\n limitedBy: limit.base\n ).map(Index.init)\n }\n\n @inlinable\n public var count: Int {\n base.isEmpty ? 0 : (base.count - 1) / stride + 1\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n let distance = base.distance(from: start.base, to: end.base)\n return distance / stride + (distance % stride).signum()\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n precondition(\n distance <= 0 || i.base != base.endIndex, \"Advancing past end index\")\n precondition(\n distance >= 0 || i.base != base.startIndex,\n \"Incrementing past start index\")\n let limit = distance > 0 ? endIndex : startIndex\n guard let idx = index(i, offsetBy: distance, limitedBy: limit) else {\n preconditionFailure(\n \"The distance \\(distance) is not valid for this collection\")\n }\n return idx\n }\n}\n\nextension StridingCollection: BidirectionalCollection\nwhere Base: RandomAccessCollection {\n @inlinable\n public func index(before i: Index) -> Index {\n precondition(i.base != base.startIndex, \"Incrementing past start index\")\n return index(i, offsetBy: -1)\n }\n}\n\nextension StridingCollection: RandomAccessCollection\nwhere Base: RandomAccessCollection {}\n\nextension StridingCollection: LazySequenceProtocol, LazyCollectionProtocol\nwhere Base: LazySequenceProtocol {}\n\nextension StridingCollection.Index: Hashable where Base.Index: Hashable {}"} | |
| {"repo": "swift-algorithms", "lang": "swift", "aspect": "algorithms", "file": "Keyed.swift", "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift Algorithms open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Creates a new dictionary keyed by the result of the given closure, using\n /// the latest element for any duplicate keys.\n ///\n /// If the key derived for a new element collides with an existing key from a\n /// previous element, the latest value will be kept.\n ///\n /// - Parameter keyForValue: A closure that returns a key for each element in\n /// `self`.\n /// - Returns: A dictionary with key-value pairs generated by calling\n /// `keyForValue` for each element in this sequence. If `keyForValue`\n /// returns the same key for two or more elements, the returned dictionary\n /// uses the last value for that key.\n @inlinable\n public func keyed<Key>(\n by keyForValue: (Element) throws -> Key\n ) rethrows -> [Key: Element] {\n try self.reduce(into: [:]) { result, element in\n try result[keyForValue(element)] = element\n }\n }\n\n /// Creates a new dictionary keyed by the result of the first closure, using\n /// the second closure to resolve the ambiguity for any duplicate keys.\n ///\n /// As the dictionary is built, the initializer calls the `resolve` closure\n /// with the current and new values for any duplicate keys. Pass a closure as\n /// `resolve` that returns the value to use for that key in the resulting\n /// dictionary. The closure can choose between the two values, combine them to\n /// produce a new value, or even throw an error.\n ///\n /// - Parameters:\n /// - keyForValue: A closure that returns a key for each element in `self`.\n /// - resolve: A closure that is called with the values for any duplicate\n /// keys that are encountered. The closure returns the desired value for\n /// the final dictionary.\n /// - Returns: A dictionary with key-value pairs generated by calling\n /// `keyForValue` for each element in this sequence. If `keyForValue`\n /// returns the same key for two or more elements, the result of the\n /// `resolve` closure is used as the value for that key.\n @inlinable\n public func keyed<Key>(\n by keyForValue: (Element) throws -> Key,\n resolvingConflictsWith resolve: (Key, Element, Element) throws -> Element\n ) rethrows -> [Key: Element] {\n var result: [Key: Element] = [:]\n\n for element in self {\n let key = try keyForValue(element)\n\n if let oldValue = result.updateValue(element, forKey: key) {\n let valueToKeep = try resolve(key, oldValue, element)\n\n // This causes a second look-up for the same key. The standard library can avoid that\n // by calling `mutatingFind` to get access to the bucket where the value will end up,\n // and updating in place.\n // Swift Algorithms doesn't have access to that API, so we make do.\n // When this gets merged into the standard library, we should optimize this.\n result[key] = valueToKeep\n }\n }\n\n return result\n }\n}"} | |