Permutations.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // This source file is part of the Swift Algorithms open source project
  4. //
  5. // Copyright (c) 2020 Apple Inc. and the Swift project authors
  6. // Licensed under Apache License v2.0 with Runtime Library Exception
  7. //
  8. // See https://swift.org/LICENSE.txt for license information
  9. //
  10. //===----------------------------------------------------------------------===//
  11. //===----------------------------------------------------------------------===//
  12. // nextPermutation()
  13. //===----------------------------------------------------------------------===//
  14. extension MutableCollection
  15. where Self: BidirectionalCollection, Element: Comparable
  16. {
  17. /// Permutes this collection's elements through all the lexical orderings.
  18. ///
  19. /// Call `nextPermutation()` repeatedly starting with the collection in sorted
  20. /// order. When the full cycle of all permutations has been completed, the
  21. /// collection will be back in sorted order and this method will return
  22. /// `false`.
  23. ///
  24. /// - Returns: A Boolean value indicating whether the collection still has
  25. /// remaining permutations. When this method returns `false`, the collection
  26. /// is in ascending order according to `areInIncreasingOrder`.
  27. ///
  28. /// - Complexity: O(*n*), where *n* is the length of the collection.
  29. @inlinable
  30. internal mutating func nextPermutation(upperBound: Index? = nil) -> Bool {
  31. // Ensure we have > 1 element in the collection.
  32. guard !isEmpty else { return false }
  33. var i = index(before: endIndex)
  34. if i == startIndex { return false }
  35. let upperBound = upperBound ?? endIndex
  36. while true {
  37. let ip1 = i
  38. formIndex(before: &i)
  39. // Find the last ascending pair (ie. ..., a, b, ... where a < b)
  40. if self[i] < self[ip1] {
  41. // Find the last element greater than self[i]
  42. // This is _always_ at most `ip1` due to if statement above
  43. let j = lastIndex(where: { self[i] < $0 })!
  44. // At this point we have something like this:
  45. // 0, 1, 4, 3, 2
  46. // ^ ^
  47. // i j
  48. swapAt(i, j)
  49. self.reverse(subrange: ip1 ..< endIndex)
  50. // Only return if we've made a change within ..<upperBound region
  51. if i < upperBound {
  52. return true
  53. } else {
  54. i = index(before: endIndex)
  55. continue
  56. }
  57. }
  58. if i == startIndex {
  59. self.reverse()
  60. return false
  61. }
  62. }
  63. }
  64. }
  65. //===----------------------------------------------------------------------===//
  66. // struct Permutations<Base>
  67. //===----------------------------------------------------------------------===//
  68. /// A sequence of all the permutations of a collection's elements.
  69. public struct PermutationsSequence<Base: Collection> {
  70. /// The base collection to iterate over for permutations.
  71. @usableFromInline
  72. internal let base: Base
  73. @usableFromInline
  74. internal let baseCount: Int
  75. /// The range of accepted sizes of permutations.
  76. ///
  77. /// - Note: This may be empty if the attempted range entirely exceeds the
  78. /// bounds of the size of the `base` collection.
  79. @usableFromInline
  80. internal let kRange: Range<Int>
  81. /// Initializes a `PermutationsSequence` for all permutations of `base` of
  82. /// size `k`.
  83. ///
  84. /// - Parameters:
  85. /// - base: The collection to iterate over for permutations
  86. /// - k: The expected size of each permutation, or `nil` (default) to
  87. /// iterate over all permutations of the same size as the base collection.
  88. @inlinable
  89. internal init(_ base: Base, k: Int? = nil) {
  90. let kRange: ClosedRange<Int>?
  91. if let countToChoose = k {
  92. kRange = countToChoose ... countToChoose
  93. } else {
  94. kRange = nil
  95. }
  96. self.init(base, kRange: kRange)
  97. }
  98. /// Initializes a `PermutationsSequence` for all combinations of `base` of
  99. /// sizes within a given range.
  100. ///
  101. /// - Parameters:
  102. /// - base: The collection to iterate over for permutations.
  103. /// - kRange: The range of accepted sizes of permutations, or `nil` to
  104. /// iterate over all permutations of the same size as the base collection.
  105. @inlinable
  106. internal init<R: RangeExpression>(
  107. _ base: Base, kRange: R?
  108. ) where R.Bound == Int {
  109. self.base = base
  110. let baseCount = base.count
  111. self.baseCount = baseCount
  112. let upperBound = baseCount + 1
  113. self.kRange = kRange?.relative(to: 0 ..< .max)
  114. .clamped(to: 0 ..< upperBound) ??
  115. baseCount ..< upperBound
  116. }
  117. /// The total number of permutations.
  118. @inlinable
  119. public var count: Int {
  120. kRange.map {
  121. stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *)
  122. }.reduce(0, +)
  123. }
  124. }
  125. extension PermutationsSequence: Sequence {
  126. /// The iterator for a `PermutationsSequence` instance.
  127. public struct Iterator: IteratorProtocol {
  128. @usableFromInline
  129. internal let base: Base
  130. @usableFromInline
  131. internal let baseCount: Int
  132. /// The current range of accepted sizes of permutations.
  133. /// - Note: The range is contracted until empty while iterating over
  134. /// permutations of different sizes. When the range is empty, iteration is
  135. /// finished.
  136. @usableFromInline
  137. internal var kRange: Range<Int>
  138. /// Whether or not iteration is finished (`kRange` is empty)
  139. @inlinable
  140. internal var isFinished: Bool {
  141. return kRange.isEmpty
  142. }
  143. @usableFromInline
  144. internal var indexes: [Base.Index]
  145. @inlinable
  146. internal init(_ permutations: PermutationsSequence) {
  147. self.base = permutations.base
  148. self.baseCount = permutations.baseCount
  149. self.kRange = permutations.kRange
  150. self.indexes = Array(permutations.base.indices)
  151. }
  152. /// Advances the `indexes` array such that the first `countToChoose`
  153. /// elements contain the next lexicographic ordering of elements.
  154. ///
  155. /// Uses the SEP(n,k) algorithm, as described in:
  156. /// https://alistairisrael.wordpress.com/2009/09/22/simple-efficient-pnk-algorithm/
  157. ///
  158. /// - Returns: A Boolean value indicating whether `indexes` still has
  159. /// remaining permutations. When this method returns `false`, `indexes`
  160. /// is in ascending order.
  161. ///
  162. /// - Complexity: O(*n*), where *n* is the length of the collection.
  163. @inlinable
  164. internal mutating func nextState() -> Bool {
  165. let countToChoose = self.kRange.lowerBound
  166. let edge = countToChoose - 1
  167. // Find first index greater than the one at `edge`.
  168. if let i = indexes[countToChoose...].firstIndex(where: { indexes[edge] < $0 }) {
  169. indexes.swapAt(edge, i)
  170. } else {
  171. indexes.reverse(subrange: countToChoose ..< indexes.endIndex)
  172. // Find last increasing pair below `edge`.
  173. // TODO: This could be indexes[..<edge].adjacentPairs().lastIndex(where: ...)
  174. var lastAscent = edge - 1
  175. while (lastAscent >= 0 && indexes[lastAscent] >= indexes[lastAscent + 1]) {
  176. lastAscent -= 1
  177. }
  178. if lastAscent < 0 {
  179. return false
  180. }
  181. // Find rightmost index less than that at `lastAscent`.
  182. if let i = indexes[lastAscent...].lastIndex(where: { indexes[lastAscent] < $0 }) {
  183. indexes.swapAt(lastAscent, i)
  184. }
  185. indexes.reverse(subrange: (lastAscent + 1) ..< indexes.endIndex)
  186. }
  187. return true
  188. }
  189. @inlinable
  190. public mutating func next() -> [Base.Element]? {
  191. guard !isFinished else { return nil }
  192. /// Advances `kRange` by incrementing its `lowerBound` until the range is
  193. /// empty, when iteration is finished.
  194. func advanceKRange() {
  195. kRange.removeFirst()
  196. indexes = Array(base.indices)
  197. }
  198. let countToChoose = self.kRange.lowerBound
  199. if countToChoose == 0 {
  200. defer {
  201. advanceKRange()
  202. }
  203. return []
  204. }
  205. let permutesFullCollection = (countToChoose == baseCount)
  206. if permutesFullCollection {
  207. // If we're permuting the full collection, each iteration is just a
  208. // call to `nextPermutation` on `indexes`.
  209. defer {
  210. let hasMorePermutations = indexes.nextPermutation()
  211. if !hasMorePermutations {
  212. advanceKRange()
  213. }
  214. }
  215. return indexes.map { base[$0] }
  216. } else {
  217. // Otherwise, return the items at the first `countToChoose` indices and
  218. // advance the state.
  219. defer {
  220. let hasMorePermutations = nextState()
  221. if !hasMorePermutations {
  222. advanceKRange()
  223. }
  224. }
  225. return indexes.prefix(countToChoose).map { base[$0] }
  226. }
  227. }
  228. }
  229. @inlinable
  230. public func makeIterator() -> Iterator {
  231. Iterator(self)
  232. }
  233. }
  234. extension PermutationsSequence: LazySequenceProtocol
  235. where Base: LazySequenceProtocol {}
  236. //===----------------------------------------------------------------------===//
  237. // permutations(ofCount:)
  238. //===----------------------------------------------------------------------===//
  239. extension Collection {
  240. /// Returns a collection of the permutations of this collection with lengths
  241. /// in the specified range.
  242. ///
  243. /// This example prints the different permutations of one to two elements from
  244. /// an array of three names:
  245. ///
  246. /// let names = ["Alex", "Celeste", "Davide"]
  247. /// for perm in names.permutations(ofCount: 1...2) {
  248. /// print(perm.joined(separator: ", "))
  249. /// }
  250. /// // Alex
  251. /// // Celeste
  252. /// // Davide
  253. /// // Alex, Celeste
  254. /// // Alex, Davide
  255. /// // Celeste, Alex
  256. /// // Celeste, Davide
  257. /// // Davide, Alex
  258. /// // Davide, Celeste
  259. ///
  260. /// This example prints _all_ the permutations (including an empty array) from
  261. /// an array of numbers:
  262. ///
  263. /// let numbers = [10, 20, 30]
  264. /// for perm in numbers.permutations(ofCount: 0...) {
  265. /// print(perm)
  266. /// }
  267. /// // []
  268. /// // [10]
  269. /// // [20]
  270. /// // [30]
  271. /// // [10, 20]
  272. /// // [10, 30]
  273. /// // [20, 10]
  274. /// // [20, 30]
  275. /// // [30, 10]
  276. /// // [30, 20]
  277. /// // [10, 20, 30]
  278. /// // [10, 30, 20]
  279. /// // [20, 10, 30]
  280. /// // [20, 30, 10]
  281. /// // [30, 10, 20]
  282. /// // [30, 20, 10]
  283. ///
  284. /// The returned permutations are in ascending order by length, and then
  285. /// lexicographically within each group of the same length.
  286. ///
  287. /// - Parameter kRange: A range of the number of elements to include in each
  288. /// permutation. `kRange` can be any integer range expression, and is
  289. /// clamped to the number of elements in this collection. Passing a range
  290. /// covering sizes greater than the number of elements in this collection
  291. /// results in an empty sequence.
  292. ///
  293. /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
  294. /// is the number of elements in the base collection, since
  295. /// `PermutationsSequence` accesses the `count` of the base collection.
  296. @inlinable
  297. public func permutations<R: RangeExpression>(
  298. ofCount kRange: R
  299. ) -> PermutationsSequence<Self> where R.Bound == Int {
  300. PermutationsSequence(self, kRange: kRange)
  301. }
  302. /// Returns a collection of the permutations of this collection of the
  303. /// specified length.
  304. ///
  305. /// This example prints the different permutations of two elements from an
  306. /// array of three names:
  307. ///
  308. /// let names = ["Alex", "Celeste", "Davide"]
  309. /// for perm in names.permutations(ofCount: 2) {
  310. /// print(perm.joined(separator: ", "))
  311. /// }
  312. /// // Alex, Celeste
  313. /// // Alex, Davide
  314. /// // Celeste, Alex
  315. /// // Celeste, Davide
  316. /// // Davide, Alex
  317. /// // Davide, Celeste
  318. ///
  319. /// The permutations present the elements in increasing lexicographic order
  320. /// of the collection's original ordering (rather than the order of the
  321. /// elements themselves). The first permutation will always consist of
  322. /// elements in their original order, and the last will have the elements in
  323. /// the reverse of their original order.
  324. ///
  325. /// Values that are repeated in the original collection are always treated as
  326. /// separate values in the resulting permutations:
  327. ///
  328. /// let numbers = [20, 10, 10]
  329. /// for perm in numbers.permutations() {
  330. /// print(perm)
  331. /// }
  332. /// // [20, 10, 10]
  333. /// // [20, 10, 10]
  334. /// // [10, 20, 10]
  335. /// // [10, 10, 20]
  336. /// // [10, 20, 10]
  337. /// // [10, 10, 20]
  338. ///
  339. /// If `k` is zero, the resulting sequence has exactly one element, an
  340. /// empty array. If `k` is greater than the number of elements in this
  341. /// sequence, the resulting sequence has no elements.
  342. ///
  343. /// - Parameter k: The number of elements to include in each permutation.
  344. /// If `k` is `nil`, the resulting sequence represents permutations of this
  345. /// entire collection. If `k` is greater than the number of elements in
  346. /// this collection, the resulting sequence is empty.
  347. ///
  348. /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
  349. /// is the number of elements in the base collection, since
  350. /// `PermutationsSequence` accesses the `count` of the base collection.
  351. @inlinable
  352. public func permutations(ofCount k: Int? = nil) -> PermutationsSequence<Self> {
  353. precondition(
  354. k ?? 0 >= 0,
  355. "Can't have permutations with a negative number of elements.")
  356. return PermutationsSequence(self, k: k)
  357. }
  358. }
  359. //===----------------------------------------------------------------------===//
  360. // uniquePermutations()
  361. //===----------------------------------------------------------------------===//
  362. /// A sequence of the unique permutations of the elements of a sequence or
  363. /// collection.
  364. ///
  365. /// To create a `UniquePermutationsSequence` instance, call one of the
  366. /// `uniquePermutations` methods on your collection.
  367. public struct UniquePermutationsSequence<Base: Collection> {
  368. /// The base collection to iterate over for permutations.
  369. @usableFromInline
  370. internal let base: Base
  371. @usableFromInline
  372. internal var indexes: [Base.Index]
  373. @usableFromInline
  374. internal let kRange: Range<Int>
  375. }
  376. extension UniquePermutationsSequence where Base.Element: Hashable {
  377. @inlinable
  378. internal static func _indexes(_ base: Base) -> [Base.Index] {
  379. let firstIndexesAndCountsByElement = Dictionary(
  380. base.indices.lazy.map { (base[$0], ($0, 1)) },
  381. uniquingKeysWith: { indexAndCount, _ in (indexAndCount.0, indexAndCount.1 + 1) })
  382. return firstIndexesAndCountsByElement
  383. .values.sorted(by: { $0.0 < $1.0 })
  384. .flatMap { index, count in repeatElement(index, count: count) }
  385. }
  386. @inlinable
  387. internal init(_ elements: Base) {
  388. self.indexes = Self._indexes(elements)
  389. self.base = elements
  390. self.kRange = self.indexes.count ..< (self.indexes.count + 1)
  391. }
  392. @inlinable
  393. internal init<R: RangeExpression>(_ base: Base, _ range: R)
  394. where R.Bound == Int
  395. {
  396. self.indexes = Self._indexes(base)
  397. self.base = base
  398. let upperBound = self.indexes.count + 1
  399. self.kRange = range.relative(to: 0 ..< .max)
  400. .clamped(to: 0 ..< upperBound)
  401. }
  402. }
  403. extension UniquePermutationsSequence: Sequence {
  404. /// The iterator for a `UniquePermutationsSequence` instance.
  405. public struct Iterator: IteratorProtocol {
  406. @usableFromInline
  407. internal let base: Base
  408. @usableFromInline
  409. internal var indexes: [Base.Index]
  410. @usableFromInline
  411. internal var lengths: Range<Int>
  412. @usableFromInline
  413. internal var initial = true
  414. @inlinable
  415. internal init(_ elements: Base, indexes: [Base.Index], lengths: Range<Int>) {
  416. self.base = elements
  417. self.indexes = indexes
  418. self.lengths = lengths
  419. }
  420. @inlinable
  421. public mutating func next() -> [Base.Element]? {
  422. // In the end case, `lengths` is an empty range.
  423. if lengths.isEmpty {
  424. return nil
  425. }
  426. // The first iteration must produce the original sorted array, before any
  427. // permutations. We skip the permutation the first time so that we can
  428. // always mutate the array _before_ returning a slice, which avoids
  429. // copying when possible.
  430. if initial {
  431. initial = false
  432. return indexes[..<lengths.lowerBound].map { base[$0] }
  433. }
  434. if !indexes.nextPermutation(upperBound: lengths.lowerBound) {
  435. lengths.removeFirst()
  436. if lengths.isEmpty {
  437. return nil
  438. }
  439. }
  440. return indexes[..<lengths.lowerBound].map { base[$0] }
  441. }
  442. }
  443. @inlinable
  444. public func makeIterator() -> Iterator {
  445. Iterator(base, indexes: indexes, lengths: kRange)
  446. }
  447. }
  448. extension UniquePermutationsSequence: LazySequenceProtocol
  449. where Base: LazySequenceProtocol {}
  450. extension Collection where Element: Hashable {
  451. /// Returns a sequence of the unique permutations of this sequence of the
  452. /// specified length.
  453. ///
  454. /// Use this method to iterate over the unique permutations of a sequence
  455. /// with repeating elements. This example prints every unique two-element
  456. /// permutation of an array of numbers:
  457. ///
  458. /// let numbers = [1, 1, 2]
  459. /// for perm in numbers.uniquePermutations(ofCount: 2) {
  460. /// print(perm)
  461. /// }
  462. /// // [1, 1]
  463. /// // [1, 2]
  464. /// // [2, 1]
  465. ///
  466. /// By contrast, the `permutations(ofCount:)` method permutes a collection's
  467. /// elements by position, and can include permutations with equal elements
  468. /// in each permutation:
  469. ///
  470. /// for perm in numbers.permutations(ofCount: 2)
  471. /// print(perm)
  472. /// }
  473. /// // [1, 1]
  474. /// // [1, 1]
  475. /// // [1, 2]
  476. /// // [1, 2]
  477. /// // [2, 1]
  478. /// // [2, 1]
  479. ///
  480. /// The returned permutations are in lexicographically sorted order.
  481. ///
  482. /// - Parameter k: The number of elements to include in each permutation.
  483. /// If `k` is `nil`, the resulting sequence represents permutations of this
  484. /// entire collection. If `k` is greater than the number of elements in
  485. /// this collection, the resulting sequence is empty.
  486. ///
  487. /// - Complexity: O(*n*), where *n* is the number of elements in this
  488. /// collection.
  489. @inlinable
  490. public func uniquePermutations(ofCount k: Int? = nil)
  491. -> UniquePermutationsSequence<Self>
  492. {
  493. if let k = k {
  494. return UniquePermutationsSequence(self, k ..< (k + 1))
  495. } else {
  496. return UniquePermutationsSequence(self)
  497. }
  498. }
  499. /// Returns a collection of the unique permutations of this sequence with
  500. /// lengths in the specified range.
  501. ///
  502. /// Use this method to iterate over the unique permutations of a sequence
  503. /// with repeating elements. This example prints every unique permutation
  504. /// of an array of numbers with lengths through 2 elements:
  505. ///
  506. /// let numbers = [1, 1, 2]
  507. /// for perm in numbers.uniquePermutations(ofCount: ...2) {
  508. /// print(perm)
  509. /// }
  510. /// // []
  511. /// // [1]
  512. /// // [2]
  513. /// // [1, 1]
  514. /// // [1, 2]
  515. /// // [2, 1]
  516. ///
  517. /// The returned permutations are in ascending order by length, and then
  518. /// lexicographically within each group of the same length.
  519. ///
  520. /// - Parameter kRange: A range of the number of elements to include in each
  521. /// permutation. `kRange` can be any integer range expression, and is
  522. /// clamped to the number of elements in this collection. Passing a range
  523. /// covering sizes greater than the number of elements in this collection
  524. /// results in an empty sequence.
  525. ///
  526. /// - Complexity: O(*n*), where *n* is the number of elements in this
  527. /// collection.
  528. @inlinable
  529. public func uniquePermutations<R: RangeExpression>(
  530. ofCount kRange: R
  531. ) -> UniquePermutationsSequence<Self> where R.Bound == Int {
  532. UniquePermutationsSequence(self, kRange)
  533. }
  534. }