permutations(ofCount:)
Returns a collection of the permutations of this collection of the specified length.
func permutations(ofCount k: Int? = nil) -> PermutationsSequence<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.
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.