1function getArrayMutations(arr, perms = [], len = arr.length) {
2 if (len === 1) perms.push(arr.slice(0))
3
4 for (let i = 0; i < len; i++) {
5 getArrayMutations(arr, perms, len - 1)
6
7 len % 2 // parity dependent adjacent elements swap
8 ? [arr[0], arr[len - 1]] = [arr[len - 1], arr[0]]
9 : [arr[i], arr[len - 1]] = [arr[len - 1], arr[i]]
10 }
11
12 return perms
13}
1/* to be used something like this:
2int [] toBePermuted = new int [] {1, 2, 3, 4};
3ArrayList<int[]> a = heap(toBePermuted);
4any mention of int [] can be replaced with any other Array of objects */
5
6ArrayList<int []> heap(int [] input) {
7 ArrayList<int []> ret = new ArrayList<int []> ();
8 ret = generate(input.length, input, ret);
9 return ret;
10}
11
12ArrayList<int []> generate(int k, int [] a, ArrayList<int []> output) {
13 if (k == 1) {
14 output.add(a.clone());
15 } else {
16 output = generate(k-1, a, output);
17 for (int i=0; i<k-1; i++) {
18 if (k%2 == 0) {
19 int temp = a[i];
20 a[i] = a[k-1];
21 a[k-1] = temp;
22 } else {
23 int temp = a[0];
24 a[0] = a[k-1];
25 a[k-1] = temp;
26 }
27 generate(k-1, a, output);
28 }
29 }
30 return output;
31}