The code listed below is written basically on the back of the napkin, so while it might not be optimized in any way, it definitely produces the correct result.
The basic idea is to iterate over the array and for each number:
- Create a new array, not containing current number.
- Generate all
possible permutations for that new array (recursively)
- Prepend
current number to every generated permutation.
Recursion terminates when the array for which to generate permutations contains only one element.
So having [1, 2, 3] as input:
currentNumber == 1, subarray to generate permutations for is [2, 3].
Generating recursively all possible permutations for [2, 3] gives [2, 3] and [3, 2].
Prepending currentNumber (1) to both gives [1, 2, 3] and [1, 3, 2].
The same goes when currentNumber is equal to 2 and 3.
Code:
func allAvailablePermutationsForArray(array: [Int]) -> [[Int]]
{
if (array.count == 1)
{
return [array]
}
var ret = [[Int]]()
for number in array
{
var leftOver = array
let index = leftOver.indexOf(number)
leftOver.removeAtIndex(index!)
let leftOverPermutations = allAvailablePermutationsForArray(leftOver)
for var permutationsArray in leftOverPermutations
{
permutationsArray.insert(number, atIndex: 0)
ret.append(permutationsArray)
}
}
return ret
}
Running it the following way:
let array = [1, 2, 3, 4]
let res = allAvailablePermutationsForArray(array)
for (index, permuts) in res.enumerate()
{
print("\(index + 1):\t\(permuts)")
}
the output is:
1: [1, 2, 3, 4]
2: [1, 2, 4, 3]
3: [1, 3, 2, 4]
4: [1, 3, 4, 2]
5: [1, 4, 2, 3]
6: [1, 4, 3, 2]
7: [2, 1, 3, 4]
8: [2, 1, 4, 3]
9: [2, 3, 1, 4]
10: [2, 3, 4, 1]
11: [2, 4, 1, 3]
12: [2, 4, 3, 1]
13: [3, 1, 2, 4]
14: [3, 1, 4, 2]
15: [3, 2, 1, 4]
16: [3, 2, 4, 1]
17: [3, 4, 1, 2]
18: [3, 4, 2, 1]
19: [4, 1, 2, 3]
20: [4, 1, 3, 2]
21: [4, 2, 1, 3]
22: [4, 2, 3, 1]
23: [4, 3, 1, 2]
24: [4, 3, 2, 1]