Initial import

This commit is contained in:
Nate Cook committed 2020-10-07 10:24:43 -05:00
commit 6cffd04a4f
47 files changed
+3944

No files matched your search

+271
View File
@@ -0,0 +1,271 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A concatenation of two sequences with the same element type.
public struct Chain<Base1: Sequence, Base2: Sequence>
where Base1.Element == Base2.Element
{
/// The first sequence in this chain.
public let base1: Base1
/// The second sequence in this chain.
public let base2: Base2
internal init(base1: Base1, base2: Base2) {
self.base1 = base1
self.base2 = base2
}
}
extension Chain: Sequence {
/// The iterator for a `Chain` sequence.
public struct Iterator: IteratorProtocol {
internal var iterator1: Base1.Iterator
internal var iterator2: Base2.Iterator
internal init(_ concatenation: Chain) {
iterator1 = concatenation.base1.makeIterator()
iterator2 = concatenation.base2.makeIterator()
}
public mutating func next() -> Base1.Element? {
return iterator1.next() ?? iterator2.next()
}
}
public func makeIterator() -> Iterator {
Iterator(self)
}
}
extension Chain: Collection where Base1: Collection, Base2: Collection {
/// A position in a `Chain` collection.
public struct Index: Comparable {
// The internal index representation, which can either be an index of the
// first collection or the second. The `endIndex` of the first collection
// is not to be used as a value - iterating over indices should go straight
// from the penultimate index of the first collection to the start of the
// second.
internal enum Representation : Equatable {
case first(Base1.Index)
case second(Base2.Index)
}
internal let position: Representation
/// Creates a new index into the first underlying collection.
internal init(first i: Base1.Index) {
position = .first(i)
}
/// Creates a new index into the second underlying collection.
internal init(second i: Base2.Index) {
position = .second(i)
}
public static func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs.position, rhs.position) {
case (.first, .second):
return true
case (.second, .first):
return false
case let (.first(l), .first(r)):
return l < r
case let (.second(l), .second(r)):
return l < r
}
}
}
public var startIndex: Index {
// If `base1` is empty, then `base2.startIndex` is either a valid position
// of the first element in `base2` or equal to `base2.endIndex`.
return base1.isEmpty
? Index(second: base2.startIndex)
: Index(first: base1.startIndex)
}
public var endIndex: Index {
return Index(second: base2.endIndex)
}
public subscript(i: Index) -> Base1.Element {
switch i.position {
case let .first(i):
return base1[i]
case let .second(i):
return base2[i]
}
}
public func index(after i: Index) -> Index {
switch i.position {
case let .first(i):
assert(i != base1.endIndex)
let next = base1.index(after: i)
return next == base1.endIndex
? Index(second: base2.startIndex)
: Index(first: next)
case let .second(i):
return Index(second: base2.index(after: i))
}
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
if n == 0 { return i }
return n > 0
? offsetForward(i, by: n, limitedBy: endIndex)!
: offsetBackward(i, by: -n, limitedBy: startIndex)!
}
public func index(
_ i: Index,
offsetBy n: Int,
limitedBy limit: Index
) -> Index? {
if n == 0 { return i }
return n > 0
? offsetForward(i, by: n, limitedBy: limit)
: offsetBackward(i, by: -n, limitedBy: limit)
}
private func offsetForward(
_ i: Index, by n: Int, limitedBy limit: Index
) -> Index? {
switch (i.position, limit.position) {
case let (.first(i), .first(limit)):
let d = base1.distance(from: i, to: base1.endIndex)
if n < d {
return base1.index(i, offsetBy: n, limitedBy: limit)
.map(Index.init(first:))
} else {
// The limit only has an effect here if it's "above" `i`
if limit >= i {
return Index(first: limit)
} else {
return Index(
second: base2.index(base2.startIndex, offsetBy: n - d))
}
}
case let (.first(i), .second(limit)):
let d = base1.distance(from: i, to: base1.endIndex)
if n < d {
return Index(first: base1.index(i, offsetBy: n))
} else {
return base2.index(
base2.startIndex, offsetBy: n - d, limitedBy: limit)
.map(Index.init(second:))
}
case let (.second(i), .first):
// `limit` has no effect here
return Index(second: base2.index(i, offsetBy: n))
case let (.second(i), .second(limit)):
return base2.index(i, offsetBy: n, limitedBy: limit)
.map(Index.init(second:))
}
}
private func offsetBackward(
_ i: Index, by n: Int, limitedBy limit: Index
) -> Index? {
switch (i.position, limit.position) {
case let (.first(i), .first(limit)):
return base1.index(i, offsetBy: -n, limitedBy: limit)
.map(Index.init(first:))
case let (.first(i), .second):
// `limit` has no effect here
return Index(first: base1.index(i, offsetBy: -n))
case let (.second(i), .first(limit)):
let d = base2.distance(from: base2.startIndex, to: i)
if n <= d {
return Index(second: base2.index(i, offsetBy: -n))
} else {
return base1.index(base1.endIndex, offsetBy: -n - d, limitedBy: limit)
.map(Index.init(first:))
}
case let (.second(i), .second(limit)):
let d = base2.distance(from: base2.startIndex, to: i)
if n <= d {
return base2.index(i, offsetBy: -n, limitedBy: limit)
.map(Index.init(second:))
} else {
return Index(
first: base1.index(base1.endIndex, offsetBy: -n - d))
}
}
}
// TODO: Add distance(from:to:)
}
extension Chain: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
{
public func index(before i: Index) -> Index {
assert(i != startIndex, "Can't advance before startIndex")
switch i.position {
case let .first(i):
return Index(first: base1.index(before: i))
case let .second(i):
return i == base2.startIndex
? Index(first: base1.index(before: base1.endIndex))
: Index(second: base2.index(before: i))
}
}
}
extension Chain: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
extension Chain: Equatable where Base1: Equatable, Base2: Equatable {}
extension Chain: Hashable where Base1: Hashable, Base2: Hashable {}
//===----------------------------------------------------------------------===//
// chained(with:)
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a new sequence that iterates over this sequence, followed by the
/// given sequence.
///
/// You can pass a sequence or collection of any type that has the same
/// element type as this sequence. This example chains a closed range of `Int`
/// with an array of `Int`:
///
/// let small = 1...3
/// let big = [100, 200, 300]
/// for num in small.chained(with: big) {
/// print(num)
/// }
/// // 1
/// // 2
/// // 3
/// // 100
/// // 200
/// // 300
///
/// - Parameter other: The sequence to iterate over after this sequence.
/// - Returns: A sequences that follows iteration of this sequence with
/// `other`.
///
/// - Complexity: O(1)
public func chained<S: Sequence>(with other: S) -> Chain<Self, S>
where Element == S.Element
{
Chain(base1: self, base2: other)
}
}
+188
View File
@@ -0,0 +1,188 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
public struct LazyChunked<Base: Collection> {
/// The collection that this instance provides a view onto.
public let base: Base
/// The projection function.
internal var belongInSameGroup: (Base.Element, Base.Element) -> Bool
}
extension LazyChunked: LazyCollectionProtocol {
/// A position in a chunked collection.
public struct Index: Comparable {
/// The lower bound of the chunk at this position.
internal var lowerBound: Base.Index
/// The upper bound of the chunk at this position.
///
/// `upperBound` is optional so that computing `startIndex` can be an O(1)
/// operation. When `upperBound` is `nil`, the actual upper bound is found
/// when subscripting or calling `index(after:)`.
internal var upperBound: Base.Index?
public static func == (lhs: Index, rhs: Index) -> Bool {
// Only use the lower bound to test for equality, since sometimes the
// `startIndex` will have an upper bound of `nil` and sometimes it won't,
// such as when retrieved by:
// `c.index(before: c.index(after: c.startIndex))`.
//
// Since each index represents the range of a disparate chunk, no two
// unique indices will have the same lower bound.
lhs.lowerBound == rhs.lowerBound
}
public static func < (lhs: Index, rhs: Index) -> Bool {
// Only use the lower bound to test for ordering, as above.
lhs.lowerBound < rhs.lowerBound
}
}
/// Returns the index in the base collection for the first element that
/// doesn't match the current chunk.
internal func endOfChunk(from i: Base.Index) -> Base.Index {
guard i != base.endIndex else { return base.endIndex }
return base[base.index(after: i)...]
.firstIndex(where: { !belongInSameGroup($0, base[i]) }) ?? base.endIndex
}
public var startIndex: Index {
Index(lowerBound: base.startIndex)
}
public var endIndex: Index {
Index(lowerBound: base.endIndex, upperBound: base.endIndex)
}
public func index(after i: Index) -> Index {
let upperBound = i.upperBound ?? endOfChunk(from: i.lowerBound)
let end = endOfChunk(from: upperBound)
return Index(lowerBound: upperBound, upperBound: end)
}
public subscript(position: Index) -> Base.SubSequence {
let upperBound = position.upperBound
?? endOfChunk(from: position.lowerBound)
return base[position.lowerBound..<upperBound]
}
}
extension LazyChunked.Index: Hashable where Base.Index: Hashable {}
extension LazyChunked: BidirectionalCollection
where Base: BidirectionalCollection
{
/// Returns the index in the base collection for the element that starts
/// the chunk ending at the given index.
internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
// Get the projected value of the last element in the range ending at `end`.
let lastOfPreviousChunk = base[base.index(before: end)]
// Search backward from `end` for the first element whose projection isn't
// equal to `lastOfPreviousChunk`.
if let firstMismatch = base[..<end]
.lastIndex(where: { !belongInSameGroup($0, lastOfPreviousChunk) })
{
// If we found one, that's the last element of the _next_ previous chunk,
// and therefore one position _before_ the start of this chunk.
return base.index(after: firstMismatch)
} else {
// If we didn't find such an element, this chunk extends back to the start
// of the collection.
return base.startIndex
}
}
public func index(before i: Index) -> Index {
let start = startOfChunk(endingAt: i.lowerBound)
return Index(lowerBound: start, upperBound: i.lowerBound)
}
}
//===----------------------------------------------------------------------===//
// lazy.chunked(by:)
//===----------------------------------------------------------------------===//
extension LazyCollectionProtocol {
/// Returns a lazy collection of subsequences of this collection, chunked by
/// the given predicate.
///
/// - Complexity: O(1). When iterating over the resulting collection,
/// accessing each successive chunk has a complexity of O(*m*), where *m*
/// is the length of the chunk.
public func chunked(
by belongInSameGroup: @escaping (Element, Element) -> Bool
) -> LazyChunked<Elements> {
LazyChunked(base: elements, belongInSameGroup: belongInSameGroup)
}
/// Returns a lazy collection of subsequences of this collection, chunked by
/// grouping elements that project to the same value.
///
/// - Complexity: O(1). When iterating over the resulting collection,
/// accessing each successive chunk has a complexity of O(*m*), where *m*
/// is the length of the chunk.
public func chunked<Subject: Equatable>(
on projection: @escaping (Element) -> Subject
) -> LazyChunked<Elements> {
LazyChunked(
base: elements,
belongInSameGroup: { projection($0) == projection($1) })
}
}
//===----------------------------------------------------------------------===//
// chunked(by:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns a collection of subsequences of this collection, chunked by
/// the given predicate.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
public func chunked(
by belongInSameGroup: (Element, Element) -> Bool
) -> [SubSequence] {
guard !isEmpty else { return [] }
var result: [SubSequence] = []
var start = startIndex
var current = startIndex
while true {
let next = index(after: current)
if next == endIndex { break }
if !belongInSameGroup(self[current], self[next]) {
result.append(self[start..<next])
start = next
}
current = next
}
if start != endIndex {
result.append(self[start..<endIndex])
}
return result
}
/// Returns a collection of subsequences of this collection, chunked by
/// grouping elements that project to the same value.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
public func chunked<Subject: Equatable>(
on projection: (Element) -> Subject
) -> [SubSequence] {
chunked(by: { projection($0) == projection($1) })
}
}
+153
View File
@@ -0,0 +1,153 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
public struct Combinations<Base: Collection> {
/// The collection to iterate over for combinations.
public let base: Base
internal var k: Int
internal init(_ base: Base, k: Int) {
self.base = base
self.k = base.count < k ? -1 : k
}
public var count: Int {
func binomial(n: Int, k: Int) -> Int {
switch k {
case n, 0: return 1
case n...: return 0
case (n / 2 + 1)...: return binomial(n: n, k: n - k)
default: return n * binomial(n: n - 1, k: k - 1) / k
}
}
return k >= 0
? binomial(n: base.count, k: k)
: 0
}
}
extension Combinations: Sequence {
public struct Iterator: IteratorProtocol {
internal let base: Base
internal var indexes: [Base.Index]
internal var finished: Bool
internal init(_ combinations: Combinations) {
self.base = combinations.base
self.finished = combinations.k < 0
self.indexes = combinations.k < 0
? []
: Array(combinations.base.indices.prefix(combinations.k))
}
/// Advances the current indices to the next set of combinations. If
/// `indexes.count == 3` and `base.count == 5`, the indices advance like
/// this:
///
/// [0, 1, 2]
/// [0, 1, 3]
/// [0, 1, 4] *
/// // * `base.endIndex` reached in `indexes.last`
/// // Advance penultimate index and propagate that change
/// [0, 2, 3]
/// [0, 2, 4] *
/// [0, 3, 4] *
/// [1, 2, 3]
/// [1, 2, 4] *
/// [1, 3, 4] *
/// [2, 3, 4] *
/// // Can't advance without needing to go past `base.endIndex`,
/// // so the iteration is finished.
internal mutating func advance() {
guard !indexes.isEmpty else {
// Initial state for combinations of 0 elements is an empty array with
// `finished == false`. Even though no indexes are involved, advancing
// from that state means we are finished with iterating.
finished = true
return
}
let i = indexes.count - 1
base.formIndex(after: &indexes[i])
if indexes[i] != base.endIndex { return }
var j = i
while indexes[i] == base.endIndex {
j -= 1
guard j >= 0 else {
// Finished iterating over combinations
finished = true
return
}
base.formIndex(after: &indexes[j])
for k in indexes.indices[(j + 1)...] {
indexes[k] = base.index(after: indexes[k - 1])
if indexes[k] == base.endIndex {
break
}
}
}
}
public mutating func next() -> [Base.Element]? {
if finished { return nil }
defer { advance() }
return indexes.map { i in base[i] }
}
}
public func makeIterator() -> Iterator {
Iterator(self)
}
}
extension Combinations: Equatable where Base: Equatable {}
extension Combinations: Hashable where Base: Hashable {}
//===----------------------------------------------------------------------===//
// combinations(count:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns a collection of combinations of this collection's elements, with
/// each combination having the specificed number of elements.
///
/// This example prints the different combinations of three from an array of
/// four colors:
///
/// let colors = ["fuchsia", "cyan", "mauve", "magenta"]
/// for combo in colors.combinations(ofCount k: 3) {
/// print(combo.joined(separator: ", "))
/// }
/// // fuchsia, cyan, mauve
/// // fuchsia, cyan, magenta
/// // fuchsia, mauve, magenta
/// // cyan, mauve, magenta
///
/// The returned collection presents combinations in a consistent order, where
/// the indices in each combination are in ascending lexicographical order.
/// That is, in the example above, the combinations in order are the elements
/// at `[0, 1, 2]`, `[0, 1, 3]`, `[0, 2, 3]`, and finally `[1, 2, 3]`.
///
/// If `k` is zero, the resulting sequence has exactly one element, an empty
/// array. If `k` is greater than the number of elements in this sequence,
/// the resulting sequence has no elements.
///
/// - Parameter k: The number of elements to include in each combination.
///
/// - Complexity: O(1)
public func combinations(ofCount k: Int) -> Combinations<Self> {
assert(k >= 0, "Can't have combinations with a negative number of elements.")
return Combinations(self, k: k)
}
}
+101
View File
@@ -0,0 +1,101 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A collection wrapper that repeats the elements of a base collection.
public struct Cycle<Base: Collection> {
/// The collection to repeat.
public let base: Base
}
extension Cycle: Sequence {
/// The iterator for a `Cycle` sequence.
public struct Iterator: IteratorProtocol {
let base: Base
var current: Base.Index
public mutating func next() -> Base.Element? {
guard !base.isEmpty else { return nil }
if current == base.endIndex {
current = base.startIndex
}
defer { base.formIndex(after: &current) }
return base[current]
}
}
public func makeIterator() -> Iterator {
Iterator(base: base, current: base.startIndex)
}
}
//===----------------------------------------------------------------------===//
// cycled()
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns a sequence that repeats the elements of this collection forever.
///
/// Use the `cycled()` method to repeat the elements of a sequence or
/// collection forever. You can combine `cycled()` with another, finite
/// sequence to iterate over the two together.
///
/// for (evenOrOdd, number) in zip(["even", "odd"].cycled(), 0..<10) {
/// print("\(number) is \(evenOrOdd)")
/// }
/// // 0 is even
/// // 1 is odd
/// // 2 is even
/// // 3 is odd
/// // ...
/// // 9 is odd
///
/// - Important: When called on a non-empty collection, the resulting sequence
/// is infinite. Do not directly call methods that require a finite
/// sequence, like `map` or `filter`, without first constraining the length
/// of the cycling sequence.
///
/// - Returns: A sequence that repeats the elements of this collection
/// forever.
///
/// - Complexity: O(1)
public func cycled() -> Cycle<Self> {
Cycle(base: self)
}
}
//===----------------------------------------------------------------------===//
// repeated(count:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns a sequence that repeats the elements of this collection the
/// specified number of times.
///
/// Passing `1` as `times` results in this collection's elements being
/// provided a single time; passing `0` results in an empty sequence. The
/// `print(_:)` function in this example is never called:
///
/// for x in [1, 2, 3].cycled(times: 0) {
/// print(x)
/// }
///
/// - Parameter times: The number of times to repeat this sequence. `times`
/// must be zero or greater.
/// - Returns: A sequence that repeats the elements of this sequence `times`
/// times.
///
/// - Complexity: O(1)
public func cycled(times: Int) -> FlattenSequence<Repeated<Self>> {
repeatElement(self, count: times).joined()
}
}
+81
View File
@@ -0,0 +1,81 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A collection wrapper that iterates over the indices and elements of a
/// collection together.
public struct Indexed<Base: Collection> {
/// The element type for an `Indexed` collection.
public typealias Element = (index: Base.Index, element: Base.Element)
/// The base collection.
public let base: Base
}
extension Indexed: Collection {
public var startIndex: Base.Index {
base.startIndex
}
public var endIndex: Base.Index {
base.endIndex
}
public subscript(position: Base.Index) -> Element {
(index: position, element: base[position])
}
public func index(after i: Base.Index) -> Base.Index {
base.index(after: i)
}
public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index {
base.index(i, offsetBy: distance)
}
public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index) -> Base.Index? {
base.index(i, offsetBy: distance, limitedBy: limit)
}
public func distance(from start: Base.Index, to end: Base.Index) -> Int {
base.distance(from: start, to: end)
}
}
extension Indexed: BidirectionalCollection where Base: BidirectionalCollection {
public func index(before i: Base.Index) -> Base.Index {
base.index(before: i)
}
}
extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {}
extension Indexed: Equatable where Base: Equatable {}
extension Indexed: Hashable where Base: Hashable {}
extension Collection {
/// Returns a collection of pairs *(i, x)*, where *i* represents an index of
/// the collection, and *x* represents an element.
///
/// This example iterates over the indices and elements of a set, building an
/// array consisting of indices of names with five or fewer letters.
///
/// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
/// var shorterIndices: [Set<String>.Index] = []
/// for (i, name) in zip(names.indices, names) {
/// if name.count <= 5 {
/// shorterIndices.append(i)
/// }
/// }
///
/// Returns: A collection of paired indices and elements of this collection.
public func indexed() -> Indexed<Self> {
Indexed(base: self)
}
}
+200
View File
@@ -0,0 +1,200 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// stablePartition(by:)
//===----------------------------------------------------------------------===//
extension MutableCollection {
/// Moves all elements satisfying `belongsInSecondPartition` into a suffix
/// of the collection, preserving their relative order, and returns the
/// start of the resulting suffix.
///
/// - Complexity: O(*n* log *n*), where *n* is the number of elements.
/// - Precondition:
/// `n == distance(from: range.lowerBound, to: range.upperBound)`
internal mutating func stablePartition(
count n: Int,
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index {
if n == 0 { return subrange.lowerBound }
if n == 1 {
return try belongsInSecondPartition(self[subrange.lowerBound])
? subrange.lowerBound
: subrange.upperBound
}
let h = n / 2, i = index(subrange.lowerBound, offsetBy: h)
let j = try stablePartition(
count: h,
subrange: subrange.lowerBound..<i,
by: belongsInSecondPartition)
let k = try stablePartition(
count: n - h,
subrange: i..<subrange.upperBound,
by: belongsInSecondPartition)
return rotate(subrange: j..<k, at: i)
}
/// Moves all elements satisfying the given predicate into a suffix of the
/// given range, preserving the relative order of the elements in both
/// partitions, and returns the start of the resulting suffix.
///
/// - Parameters:
/// - subrange: The range of elements within this collection to partition.
/// - belongsInSecondPartition: A predicate used to partition the
/// collection. All elements satisfying this predicate are ordered after
/// all elements not satisfying it.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
public mutating func stablePartition(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index {
try stablePartition(
count: count,
subrange: subrange,
by: belongsInSecondPartition)
}
/// Moves all elements satisfying the given predicate into a suffix of this
/// collection, preserving the relative order of the elements in both
/// partitions, and returns the start of the resulting suffix.
///
/// - Parameter belongsInSecondPartition: A predicate used to partition the
/// collection. All elements satisfying this predicate are ordered after
/// all elements not satisfying it.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
public mutating func stablePartition(
by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index {
try stablePartition(
subrange: startIndex..<endIndex,
by: belongsInSecondPartition)
}
}
//===----------------------------------------------------------------------===//
// partition(by:)
//===----------------------------------------------------------------------===//
extension MutableCollection {
/// Moves all elements satisfying `isSuffixElement` into a suffix of the
/// collection, returning the start position of the resulting suffix.
///
/// - Complexity: O(*n*) where n is the length of the collection.
public mutating func partition(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
// This version of `partition(subrange:)` is half stable; the elements in
// the first partition retain their original relative order.
guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition)
else { return subrange.upperBound }
var j = index(after: i)
while j != subrange.upperBound {
if try !belongsInSecondPartition(self[j]) {
swapAt(i, j)
formIndex(after: &i)
}
formIndex(after: &j)
}
return i
}
}
extension MutableCollection where Self: BidirectionalCollection {
/// Moves all elements satisfying `isSuffixElement` into a suffix of the
/// collection, returning the start position of the resulting suffix.
///
/// - Complexity: O(*n*) where n is the length of the collection.
public mutating func partition(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
var lo = subrange.lowerBound
var hi = subrange.upperBound
// 'Loop' invariants (at start of Loop, all are true):
// * lo < hi
// * predicate(self[i]) == false, for i in startIndex ..< lo
// * predicate(self[i]) == true, for i in hi ..< endIndex
Loop: while true {
FindLo: repeat {
while lo < hi {
if try belongsInSecondPartition(self[lo]) { break FindLo }
formIndex(after: &lo)
}
break Loop
} while false
FindHi: repeat {
formIndex(before: &hi)
while lo < hi {
if try !belongsInSecondPartition(self[hi]) { break FindHi }
formIndex(before: &hi)
}
break Loop
} while false
swapAt(lo, hi)
formIndex(after: &lo)
}
return lo
}
}
//===----------------------------------------------------------------------===//
// partitioningIndex(where:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns the index of the first element in the collection that matches
/// the predicate.
///
/// The collection must already be partitioned according to the predicate.
/// That is, there should be an index `i` where for every element in
/// `collection[..<i]` the predicate is `false`, and for every element
/// in `collection[i...]` the predicate is `true`.
///
/// - Parameter belongsInSecondPartition: A predicate that partitions the
/// collection.
/// - Returns: The index of the first element in the collection for which
/// `predicate` returns `true`.
///
/// - Complexity: O(log *n*), where *n* is the length of this collection if
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
public func partitioningIndex(
where belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
var n = count
var l = startIndex
while n > 0 {
let half = n / 2
let mid = index(l, offsetBy: half)
if try belongsInSecondPartition(self[mid]) {
n = half
} else {
l = index(after: mid)
n -= half + 1
}
}
return l
}
}
+236
View File
@@ -0,0 +1,236 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A sequence of all the permutations of a collection's elements.
public struct Permutations<Base: Collection> {
/// The base collection.
public let base: Base
internal let baseCount: Int
internal let countToChoose: Int
internal init(_ base: Base, k: Int? = nil) {
self.base = base
let baseCount = base.count
self.baseCount = baseCount
self.countToChoose = k ?? baseCount
}
public var count: Int {
return baseCount >= countToChoose
? stride(from: baseCount, to: baseCount - countToChoose, by: -1).reduce(1, *)
: 0
}
}
extension Permutations: Sequence {
public struct Iterator: IteratorProtocol {
internal var base: Base
internal var indexes: [Base.Index]
internal var hasMorePermutations: Bool
internal var countToChoose: Int = 0
/// `true` if we're generating permutations of the full collection.
internal var permutesFullCollection: Bool {
countToChoose == indexes.count
}
internal init(_ base: Base) {
self.base = base
self.indexes = Array(base.indices)
self.countToChoose = self.indexes.count
self.hasMorePermutations = true
}
internal init(_ base: Base, count: Int) {
self.base = base
self.countToChoose = count
// Produce exactly one empty permutation when `count == 0`.
self.indexes = count == 0 ? [] : Array(base.indices)
// Can't produce any permutations when `count > base.count`.
self.hasMorePermutations = count <= indexes.count
}
/// Advances the `indexes` array such that the first `countToChoose`
/// elements contain the next lexicographic ordering of elements.
///
/// Uses the SEP(n,k) algorithm, as described in:
/// https://alistairisrael.wordpress.com/2009/09/22/simple-efficient-pnk-algorithm/
///
/// - Returns: A Boolean value indicating whether `indexes` still has
/// remaining permutations. When this method returns `false`, `indexes`
/// is in ascending order.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
internal mutating func nextState() -> Bool {
let edge = countToChoose - 1
// Find first index greater than the one at `edge`.
if let i = indexes[countToChoose...].firstIndex(where: { indexes[edge] < $0 }) {
indexes.swapAt(edge, i)
} else {
indexes.reverse(subrange: countToChoose..<indexes.endIndex)
// Find last increasing pair below `edge`.
// TODO: This could be indexes[..<edge].adjacentPairs().lastIndex(where: ...)
var lastAscent = edge - 1
while (lastAscent >= 0 && indexes[lastAscent] >= indexes[lastAscent + 1]) {
lastAscent -= 1
}
if (lastAscent < 0) {
return false
}
// Find rightmost index less than that at `lastAscent`.
if let i = indexes[lastAscent...].lastIndex(where: { indexes[lastAscent] < $0 }) {
indexes.swapAt(lastAscent, i)
}
indexes.reverse(subrange: (lastAscent + 1)..<indexes.endIndex)
}
return true
}
public mutating func next() -> [Base.Element]? {
if !hasMorePermutations { return nil }
if permutesFullCollection {
// If we're permuting the full collection, each iteration is just a
// call to `nextPermutation` on `indexes`.
defer { hasMorePermutations = indexes.nextPermutation() }
return indexes.map { base[$0] }
} else {
// Otherwise, return the items at the first `countToChoose` indices and
// advance the state.
defer { hasMorePermutations = nextState() }
return indexes.prefix(countToChoose).map { base[$0] }
}
}
}
internal var permutesFullCollection: Bool {
baseCount == countToChoose
}
public func makeIterator() -> Iterator {
permutesFullCollection
? Iterator(base)
: Iterator(base, count: countToChoose)
}
}
//===----------------------------------------------------------------------===//
// nextPermutation(by:)
//===----------------------------------------------------------------------===//
extension MutableCollection
where Self: BidirectionalCollection, Element: Comparable
{
/// Permutes this collection's elements through all the lexical orderings.
///
/// Call `nextPermutation()` repeatedly starting with the collection in
/// sorted order. When the full cycle of all permutations has been completed,
/// the collection will be back in sorted order and this method will return
/// `false`.
///
/// - Returns: A Boolean value indicating whether the collection still has
/// remaining permutations. When this method returns `false`, the collection
/// is in ascending order according to `areInIncreasingOrder`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
internal mutating func nextPermutation() -> Bool {
// ensure we have > 1 element in the collection
if isEmpty { return false }
var i = index(before: endIndex)
if i == startIndex { return false }
while true {
let ip1 = i
formIndex(before: &i)
if self[i] < self[ip1] {
var j = index(before: endIndex)
while self[i] >= self[j] {
formIndex(before: &j)
}
swapAt(i, j)
self.reverse(subrange: ip1..<endIndex)
return true
}
if i == startIndex {
self.reverse()
return false
}
}
}
}
//===----------------------------------------------------------------------===//
// permutations(count:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns a collection of the permutations of this collection of the
/// specified length.
///
/// This example prints the different permutations of two elements from an
/// array of three names:
///
/// let names = ["Alex", "Celeste", "Davide"]
/// for perm in names.permutations(ofCount: 2) {
/// print(perm.joined(separator: ", "))
/// }
/// // Alex, Celeste
/// // Alex, Davide
/// // Celeste, Alex
/// // Celeste, Davide
/// // Davide, Alex
/// // Davide, Celeste
///
/// The permutations present the elements in increasing lexicographic order
/// of the collection's original ordering (rather than the order of the
/// elements themselves). The first permutation will always consist of
/// elements in their original order, and the last will have the elements in
/// the reverse of their original order.
///
/// Values that are repeated in the original collection are always treated as
/// separate values in the resulting permutations:
///
/// let numbers = [20, 10, 10]
/// for perm in numbers.permutations() {
/// print(perm)
/// }
/// // [20, 10, 10]
/// // [20, 10, 10]
/// // [10, 20, 10]
/// // [10, 10, 20]
/// // [10, 20, 10]
/// // [10, 10, 20]
///
/// If `k` is zero, the resulting sequence has exactly one element, an
/// empty array. If `k` is greater than the number of elements in this
/// sequence, the resulting sequence has no elements.
///
/// - Parameter k: The number of elements to include in each permutation.
/// If `count` is `nil`, the resulting sequence represents permutations
/// of this entire collection.
///
/// - Complexity: O(1)
public func permutations(ofCount k: Int? = nil) -> Permutations<Self> {
assert(
k ?? 0 >= 0,
"Can't have permutations with a negative number of elements.")
return Permutations(self, k: k)
}
}
+200
View File
@@ -0,0 +1,200 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A sequence that represents the product of two sequence's elements.
public struct Product2<Base1: Sequence, Base2: Collection> {
/// The outer sequence in the product.
public let base1: Base1
/// The inner sequence in the product.
public let base2: Base2
internal init(_ base1: Base1, _ base2: Base2) {
self.base1 = base1
self.base2 = base2
}
}
extension Product2: Sequence {
/// The iterator for a `Product2` sequence.
public struct Iterator: IteratorProtocol {
var i1: Base1.Iterator
var i2: Base2.Iterator
var element1: Base1.Element?
let base2: Base2
init(_ c: Product2) {
self.base2 = c.base2
self.i1 = c.base1.makeIterator()
self.i2 = c.base2.makeIterator()
self.element1 = nil
}
public mutating func next() -> (Base1.Element, Base2.Element)? {
// This is the initial state, where i1.next() has never
// been called, or the final state, where i1.next() has
// already returned nil.
if element1 == nil {
element1 = i1.next()
// once Base1 is exhausted, return `nil` forever
if element1 == nil { return nil }
}
// Get the next element from the second sequence, if not
// at end.
if let element2 = i2.next() {
return (element1!, element2)
}
// We've reached the end of the second sequence, so:
// 1) Get the next element of the first sequence, if exists
// 2) Restart iteration of the second sequence
// 3) Get the first element of the second sequence, if exists
element1 = i1.next()
guard let element1 = element1
else { return nil }
i2 = base2.makeIterator()
if let element2 = i2.next() {
return (element1, element2)
} else {
return nil
}
}
}
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
extension Product2: Collection where Base1: Collection {
/// The index type for a `Product2` collection.
public struct Index: Comparable {
var i1: Base1.Index
var i2: Base2.Index
public static func < (lhs: Index, rhs: Index) -> Bool {
(lhs.i1, lhs.i2) < (rhs.i1, rhs.i2)
}
}
public var count: Int {
base1.count * base2.count
}
public var startIndex: Index {
base1.isEmpty || base2.isEmpty
? endIndex
: Index(i1: base1.startIndex, i2: base2.startIndex)
}
public var endIndex: Index {
Index(i1: base1.endIndex, i2: base2.endIndex)
}
public func index(after i: Index) -> Index {
precondition(i.i1 != base1.endIndex && i.i2 != base2.endIndex,
"Can't advance past endIndex")
let newIndex2 = base2.index(after: i.i2)
if newIndex2 < base2.endIndex {
return Index(i1: i.i1, i2: newIndex2)
}
let newIndex1 = base1.index(after: i.i1)
return newIndex1 == base1.endIndex
? endIndex
: Index(i1: newIndex1, i2: base2.startIndex)
}
// TODO: Implement index(_:offsetBy:) and index(_:offsetBy:limitedBy:)
public func distance(from start: Index, to end: Index) -> Int {
if start > end {
return -distance(from: end, to: start)
}
if start.i1 == end.i1 {
return base2[start.i2..<end.i2].count
}
return base2[start.i2...].count + base2[..<end.i2].count
+ base2.count * (base1.distance(from: start.i1, to: end.i1))
}
public subscript(position: Index) -> (Base1.Element, Base2.Element) {
return (base1[position.i1], base2[position.i2])
}
}
extension Product2: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
{
public func index(before i: Index) -> Index {
precondition(i != startIndex,
"Can't move before startIndex")
if i.i2 == base2.startIndex {
return Index(i1: i.i1, i2: base2.index(before: i.i2))
}
return Index(
i1: base1.index(before: i.i1),
i2: base2.index(before: base2.endIndex))
}
}
extension Product2: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {}
extension Product2: Equatable where Base1: Equatable, Base2: Equatable {}
extension Product2: Hashable where Base1: Hashable, Base2: Hashable {}
//===----------------------------------------------------------------------===//
// product(_:_:)
//===----------------------------------------------------------------------===//
/// Creates a sequence of each pair of elements of two underlying sequences.
///
/// Use this function to iterate over every pair of elements in two different
/// collections. The returned sequence yields 2-element tuples, where the first
/// element of the tuple is from the first collection and the second element is
/// from the second collection.
///
///
/// let numbers = 1...3
/// let colors = ["cerise", "puce", "heliotrope"]
/// for (number, color) in product(numbers, colors) {
/// print("\(number): \(color)")
/// }
/// // 1: cerise
/// // 1: puce
/// // 1: heliotrope
/// // 2: cerise
/// // 2: puce
/// // 2: heliotrope
/// // 3: cerise
/// // 3: puce
/// // 3: heliotrope
///
/// The order of tuples in the returned sequence is consistent. The first
/// element of the first collection is paired with each element of the second
/// collection, then the second element of the first collection is paired with
/// each element of the second collection, and so on.
///
/// - Parameters:
/// - s1: The first sequence to iterate over.
/// - s2: The second sequence to iterate over.
///
/// - Complexity: O(1)
public func product<Base1: Sequence, Base2: Collection>(
_ s1: Base1, _ s2: Base2
) -> Product2<Base1, Base2> {
return Product2(s1, s2)
}
+238
View File
@@ -0,0 +1,238 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// For log(_:) and exp(_:)
#if canImport(Glibc)
@_implementationOnly
import Glibc
#elseif canImport(Darwin)
@_implementationOnly
import Darwin
#endif
//===----------------------------------------------------------------------===//
// randomStableSample(count:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Randomly selects the specified number of elements from this collection,
/// maintaining their relative order.
///
/// - Parameters:
/// - k: The number of elements to randomly select.
/// - rng: The random number generator to use for the sampling.
/// - Returns: An array of `k` random elements. If `k` is greater than this
/// collection's count, then this method returns the full collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
public func randomStableSample<G: RandomNumberGenerator>(
count k: Int, using rng: inout G
) -> [Element] {
guard k > 0 else { return [] }
var remainingCount = count
guard k < remainingCount else { return Array(self) }
var result: [Element] = []
result.reserveCapacity(k)
var i = startIndex
var countToSelect = k
while countToSelect > 0 {
let r = Int.random(in: 0..<remainingCount, using: &rng)
if r < countToSelect {
result.append(self[i])
countToSelect -= 1
}
formIndex(after: &i)
remainingCount -= 1
}
return result
}
/// Randomly selects the specified number of elements from this collection,
/// maintaining their relative order.
///
/// This method is equivalent to calling `randomStableSample(k:using:)`,
/// passing in the system's default random generator.
///
/// - Parameters:
/// - k: The number of elements to randomly select.
/// - Returns: An array of `k` random elements. If `k` is greater than this
/// collection's count, then this method returns the full collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
public func randomStableSample(count k: Int) -> [Element] {
var g = SystemRandomNumberGenerator()
return randomStableSample(count: k, using: &g)
}
}
//===----------------------------------------------------------------------===//
// randomSample(count:)
//===----------------------------------------------------------------------===//
// These methods use Algorithm L, described in "Reservoir-Sampling
// Algorithms of Time Complexity O(n(1 + log(N/n)))":
// https://dl.acm.org/doi/pdf/10.1145/198429.198435
fileprivate func nextW<G: RandomNumberGenerator>(
k: Double, using rng: inout G
) -> Double {
exp(log(Double.random(in: 0..<1, using: &rng)) / k)
}
fileprivate func nextOffset<G: RandomNumberGenerator>(
w: Double, using rng: inout G
) -> Int {
Int(log(Double.random(in: 0..<1, using: &rng)) / log(1 - w))
}
extension Collection {
/// Randomly selects the specified number of elements from this collection.
///
/// - Parameters:
/// - k: The number of elements to randomly select.
/// - rng: The random number generator to use for the sampling.
/// - Returns: An array of `k` random elements. The returned elements may be
/// in any order. If `k` is greater than this collection's count, then this
/// method returns the full collection.
///
/// - Complexity: O(*k*), where *k* is the number of elements to select, if
/// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),
/// where *n* is the length of the collection.
public func randomSample<G: RandomNumberGenerator>(
count k: Int, using rng: inout G
) -> [Element] {
guard k > 0 else { return [] }
var w = 1.0
var result: [Element] = []
result.reserveCapacity(k)
// Fill the reservoir with the first `k` elements.
var i = startIndex
while i < endIndex, result.count < k {
result.append(self[i])
formIndex(after: &i)
}
let dk = Double(k)
while i < endIndex {
// Calculate the next value of w.
w *= nextW(k: dk, using: &rng)
// Find index of the next element to swap into the reservoir.
let offset = nextOffset(w: w, using: &rng)
i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex
if i < endIndex {
// Swap selected element with a randomly chosen one in the reservoir.
let j = Int.random(in: 0..<result.count, using: &rng)
result[j] = self[i]
formIndex(after: &i)
}
}
// FIXME: necessary?
result.shuffle(using: &rng)
return result
}
/// Randomly selects the specified number of elements from this collection.
///
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
/// the system's default random generator.
///
/// - Parameters:
/// - k: The number of elements to randomly select.
/// - Returns: An array of `k` random elements. The returned elements may be
/// in any order. If `k` is greater than this collection's count, then this
/// method returns the full collection.
///
/// - Complexity: O(*k*), where *k* is the number of elements to select, if
/// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),
/// where *n* is the length of the collection.
public func randomSample(count k: Int) -> [Element] {
var g = SystemRandomNumberGenerator()
return randomSample(count: k, using: &g)
}
}
extension Sequence {
/// Randomly selects the specified number of elements from this sequence.
///
/// - Parameters:
/// - k: The number of elements to randomly select.
/// - rng: The random number generator to use for the sampling.
/// - Returns: An array of `k` random elements. The returned elements may be
/// in any order. If `k` is greater than this sequence's count, then this
/// method returns the full sequence.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
public func randomSample<G: RandomNumberGenerator>(
count k: Int, using rng: inout G
) -> [Element] {
guard k > 0 else { return [] }
var w = 1.0
var result: [Element] = []
result.reserveCapacity(k)
// Fill the reservoir with the first `k` elements.
var iterator = makeIterator()
while result.count < k, let el = iterator.next() {
result.append(el)
}
let dk = Double(k)
while true {
// Calculate the next value of w.
w *= nextW(k: dk, using: &rng)
// Find the offset of the next element to swap into the reservoir.
var offset = nextOffset(w: w, using: &rng) + 1
// Skip over `offset - 1` elements to find the selected element.
while offset > 1, let _ = iterator.next() {
offset -= 1
}
guard let nextElement = iterator.next() else { break }
// Swap selected element with a randomly chosen one in the reservoir.
let j = Int.random(in: 0..<result.count, using: &rng)
result[j] = nextElement
}
// FIXME: necessary?
result.shuffle(using: &rng)
return result
}
/// Randomly selects the specified number of elements from this sequence.
///
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
/// the system's default random generator.
///
/// - Parameters:
/// - k: The number of elements to randomly select.
/// - Returns: An array of `k` random elements. The returned elements may be
/// in any order. If `k` is greater than this sequence's count, then this
/// method returns the full sequence.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
public func randomSample(count k: Int) -> [Element] {
var g = SystemRandomNumberGenerator()
return randomSample(count: k, using: &g)
}
}
+203
View File
@@ -0,0 +1,203 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// reverse(subrange:)
//===----------------------------------------------------------------------===//
extension MutableCollection where Self: BidirectionalCollection {
/// Reverses the elements of the collection, moving from each end until
/// `limit` is reached from either direction. The returned indices are the
/// start and end of the range of unreversed elements.
///
/// Input:
/// [a b c d e f g h i j k l m n o p]
/// ^
/// limit
/// Output:
/// [p o n m e f g h i j k l d c b a]
/// ^ ^
/// f l
///
/// - Postcondition: For returned indices `(f, l)`:
/// `f == limit || l == limit`
@discardableResult
internal mutating func _reverse(
subrange: Range<Index>, until limit: Index
) -> (Index, Index) {
var f = subrange.lowerBound
var l = subrange.upperBound
while f != limit && l != limit {
formIndex(before: &l)
swapAt(f, l)
formIndex(after: &f)
}
return (f, l)
}
public mutating func reverse(subrange: Range<Index>) {
if subrange.isEmpty { return }
var lo = subrange.lowerBound
var hi = subrange.upperBound
while lo < hi {
formIndex(before: &hi)
swapAt(lo, hi)
formIndex(after: &lo)
}
}
}
//===----------------------------------------------------------------------===//
// rotate(at:) / rotate(subrange:at:)
//===----------------------------------------------------------------------===//
extension MutableCollection {
/// Swaps the elements of the two given subranges, up to the upper bound of
/// the smaller subrange. The returned indices are the ends of the two
/// ranges that were actually swapped.
///
/// Input:
/// [a b c d e f g h i j k l m n o p]
/// ^^^^^^^ ^^^^^^^^^^^^^
/// lhs rhs
///
/// Output:
/// [i j k l e f g h a b c d m n o p]
/// ^ ^
/// p q
///
/// - Precondition: !lhs.isEmpty && !rhs.isEmpty
/// - Postcondition: For returned indices `(p, q)`:
///
/// - distance(from: lhs.lowerBound, to: p) == distance(from:
/// rhs.lowerBound, to: q)
/// - p == lhs.upperBound || q == rhs.upperBound
internal mutating func _swapNonemptySubrangePrefixes(
_ lhs: Range<Index>, _ rhs: Range<Index>
) -> (Index, Index) {
assert(!lhs.isEmpty)
assert(!rhs.isEmpty)
var p = lhs.lowerBound
var q = rhs.lowerBound
repeat {
swapAt(p, q)
formIndex(after: &p)
formIndex(after: &q)
}
while p != lhs.upperBound && q != rhs.upperBound
return (p, q)
}
@discardableResult
public mutating func rotate(
subrange: Range<Index>,
at newStart: Index
) -> Index {
var m = newStart, s = subrange.lowerBound
let e = subrange.upperBound
// Handle the trivial cases
if s == m { return e }
if m == e { return s }
// We have two regions of possibly-unequal length that need to be
// exchanged. The return value of this method is going to be the
// position following that of the element that is currently last
// (element j).
//
// [a b c d e f g|h i j] or [a b c|d e f g h i j]
// ^ ^ ^ ^ ^ ^
// s m e s m e
//
var ret = e // start with a known incorrect result.
while true {
// Exchange the leading elements of each region (up to the
// length of the shorter region).
//
// [a b c d e f g|h i j] or [a b c|d e f g h i j]
// ^^^^^ ^^^^^ ^^^^^ ^^^^^
// [h i j d e f g|a b c] or [d e f|a b c g h i j]
// ^ ^ ^ ^ ^ ^ ^ ^
// s s1 m m1/e s s1/m m1 e
//
let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e)
if m1 == e {
// Left-hand case: we have moved element j into position. if
// we haven't already, we can capture the return value which
// is in s1.
//
// Note: the STL breaks the loop into two just to avoid this
// comparison once the return value is known. I'm not sure
// it's a worthwhile optimization, though.
if ret == e { ret = s1 }
// If both regions were the same size, we're done.
if s1 == m { break }
}
// Now we have a smaller problem that is also a rotation, so we
// can adjust our bounds and repeat.
//
// h i j[d e f g|a b c] or d e f[a b c|g h i j]
// ^ ^ ^ ^ ^ ^
// s m e s m e
s = s1
if s == m { m = m1 }
}
return ret
}
@discardableResult
public mutating func rotate(at newStart: Index) -> Index {
rotate(subrange: startIndex..<endIndex, at: newStart)
}
}
extension MutableCollection where Self: BidirectionalCollection {
@discardableResult
public mutating func rotate(
subrange: Range<Index>,
at newStart: Index
) -> Index {
reverse(subrange: subrange.lowerBound..<newStart)
reverse(subrange: newStart..<subrange.upperBound)
let (p, q) = _reverse(subrange: subrange, until: newStart)
reverse(subrange: p..<q)
return newStart == p ? q : p
}
/// Rotates the elements of this collection so that the element
/// at the specified index moves to the front of the collection.
///
/// Rotating a collection is equivalent to breaking the collection into two
/// sections at the index `newStart`, and then swapping those two sections.
/// In this example, the `numbers` array is rotated so that the element at
/// index `3` (`40`) is first:
///
/// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
/// let oldStart = numbers.rotate(at: 3)
/// // numbers == [40, 50, 60, 70, 80, 10, 20, 30]
/// // numbers[oldStart] == 10
///
/// - Parameter newStart: The index of the element that should be first after
/// rotating.
/// - Returns: The new index of the element that was first pre-rotation.
///
/// - Complexity: O(*n*)
@discardableResult
public mutating func rotate(at newStart: Index) -> Index {
rotate(subrange: startIndex..<endIndex, at: newStart)
}
}
+47
View File
@@ -0,0 +1,47 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// uniqued()
//===----------------------------------------------------------------------===//
extension Sequence where Element: Hashable {
/// Returns an array with only the unique elements of this sequence, in the
/// order of the first occurence of each unique element.
public func uniqued() -> [Element] {
var seen: Set<Element> = []
var result: [Element] = []
for element in self {
if seen.insert(element).inserted {
result.append(element)
}
}
return result
}
}
extension Sequence {
/// Returns an array with the unique elements of this sequence (as determined
/// by the given projection), in the order of the first occurence of each
/// unique element.
public func uniqued<Subject: Hashable>(
on projection: (Element) throws -> Subject
) rethrows -> [Element] {
var seen: Set<Subject> = []
var result: [Element] = []
for element in self {
if seen.insert(try projection(element)).inserted {
result.append(element)
}
}
return result
}
}