uniquePermutations(ofCount:)
Returns a sequence of the unique permutations of this sequence of the specified length.
func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutationsSequence<Self>
Parameters
- k
The number of elements to include in each permutation. If
k
isnil
, the resulting sequence represents permutations of this entire collection. Ifk
is greater than the number of elements in this collection, the resulting sequence is empty.
Use this method to iterate over the unique permutations of a sequence with repeating elements. This example prints every unique two-element permutation of an array of numbers:
let numbers = [1, 1, 2]
for perm in numbers.uniquePermutations(ofCount: 2) {
print(perm)
}
// [1, 1]
// [1, 2]
// [2, 1]
By contrast, the permutations(ofCount:)
method permutes a collection’s elements by position, and can include permutations with equal elements in each permutation:
for perm in numbers.permutations(ofCount: 2)
print(perm)
}
// [1, 1]
// [1, 1]
// [1, 2]
// [1, 2]
// [2, 1]
// [2, 1]
The returned permutations are in lexicographically sorted order.