permutations(ofCount:)
Returns a collection of the permutations of this collection with lengths in the specified range.
func permutations<R>(ofCount kRange: R) -> PermutationsSequence<Self> where R : RangeExpression, R.Bound == Int
Parameters
- kRange
A range of the number of elements to include in each permutation.
kRange
can be any integer range expression, and is clamped to the number of elements in this collection. Passing a range covering sizes greater than the number of elements in this collection results in an empty sequence.
This example prints the different permutations of one to two elements from an array of three names:
let names = ["Alex", "Celeste", "Davide"]
for perm in names.permutations(ofCount: 1...2) {
print(perm.joined(separator: ", "))
}
// Alex
// Celeste
// Davide
// Alex, Celeste
// Alex, Davide
// Celeste, Alex
// Celeste, Davide
// Davide, Alex
// Davide, Celeste
This example prints all the permutations (including an empty array) from an array of numbers:
let numbers = [10, 20, 30]
for perm in numbers.permutations(ofCount: 0...) {
print(perm)
}
// []
// [10]
// [20]
// [30]
// [10, 20]
// [10, 30]
// [20, 10]
// [20, 30]
// [30, 10]
// [30, 20]
// [10, 20, 30]
// [10, 30, 20]
// [20, 10, 30]
// [20, 30, 10]
// [30, 10, 20]
// [30, 20, 10]
The returned permutations are in ascending order by length, and then lexicographically within each group of the same length.