For example I have this array:
int a[] = new int[]{3,4,6,2,1};
I need list of all permutations such that if one is like this, {3,2,1
According to wiki https://en.wikipedia.org/wiki/Heap%27s_algorithm
Heap's algorithm generates all possible permutations of n objects. It was first proposed by B. R. Heap in 1963. The algorithm minimizes movement: it generates each permutation from the previous one by interchanging a single pair of elements; the other n−2 elements are not disturbed. In a 1977 review of permutation-generating algorithms, Robert Sedgewick concluded that it was at that time the most effective algorithm for generating permutations by computer.
So if we want to do it in recursive manner, Sudo code is bellow.
procedure generate(n : integer, A : array of any):
if n = 1 then
output(A)
else
for i := 0; i < n - 1; i += 1 do
generate(n - 1, A)
if n is even then
swap(A[i], A[n-1])
else
swap(A[0], A[n-1])
end if
end for
generate(n - 1, A)
end if
java code:
public static void printAllPermutations(
int n, int[] elements, char delimiter) {
if (n == 1) {
printArray(elements, delimiter);
} else {
for (int i = 0; i < n - 1; i++) {
printAllPermutations(n - 1, elements, delimiter);
if (n % 2 == 0) {
swap(elements, i, n - 1);
} else {
swap(elements, 0, n - 1);
}
}
printAllPermutations(n - 1, elements, delimiter);
}
}
private static void printArray(int[] input, char delimiter) {
int i = 0;
for (; i < input.length; i++) {
System.out.print(input[i]);
}
System.out.print(delimiter);
}
private static void swap(int[] input, int a, int b) {
int tmp = input[a];
input[a] = input[b];
input[b] = tmp;
}
public static void main(String[] args) {
int[] input = new int[]{0,1,2,3};
printAllPermutations(input.length, input, ',');
}
If you're using C++, you can use std::next_permutation from the <algorithm>
header file:
int a[] = {3,4,6,2,1};
int size = sizeof(a)/sizeof(a[0]);
std::sort(a, a+size);
do {
// print a's elements
} while(std::next_permutation(a, a+size));
Visual representation of the 3-item recursive solution: http://www.docdroid.net/ea0s/generatepermutations.pdf.html
Breakdown:
This a 2-permutation for a list wrapped in an iterator
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/* all permutations of two objects
*
* for ABC: AB AC BA BC CA CB
*
* */
public class ListPermutation<T> implements Iterator {
int index = 0;
int current = 0;
List<T> list;
public ListPermutation(List<T> e) {
list = e;
}
public boolean hasNext() {
return !(index == list.size() - 1 && current == list.size() - 1);
}
public List<T> next() {
if(current == index) {
current++;
}
if (current == list.size()) {
current = 0;
index++;
}
List<T> output = new LinkedList<T>();
output.add(list.get(index));
output.add(list.get(current));
current++;
return output;
}
public void remove() {
}
}
Implementation via recursion (dynamic programming), in Java, with test case (TestNG).
PrintPermutation.java
import java.util.Arrays;
/**
* Print permutation of n elements.
*
* @author eric
* @date Oct 13, 2018 12:28:10 PM
*/
public class PrintPermutation {
/**
* Print permutation of array elements.
*
* @param arr
* @return count of permutation,
*/
public static int permutation(int arr[]) {
return permutation(arr, 0);
}
/**
* Print permutation of part of array elements.
*
* @param arr
* @param n
* start index in array,
* @return count of permutation,
*/
private static int permutation(int arr[], int n) {
int counter = 0;
for (int i = n; i < arr.length; i++) {
swapArrEle(arr, i, n);
counter += permutation(arr, n + 1);
swapArrEle(arr, n, i);
}
if (n == arr.length - 1) {
counter++;
System.out.println(Arrays.toString(arr));
}
return counter;
}
/**
* swap 2 elements in array,
*
* @param arr
* @param i
* @param k
*/
private static void swapArrEle(int arr[], int i, int k) {
int tmp = arr[i];
arr[i] = arr[k];
arr[k] = tmp;
}
}
PrintPermutationTest.java (test case via TestNG)
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* PrintPermutation test.
*
* @author eric
* @date Oct 14, 2018 3:02:23 AM
*/
public class PrintPermutationTest {
@Test
public void test() {
int arr[] = new int[] { 0, 1, 2, 3 };
Assert.assertEquals(PrintPermutation.permutation(arr), 24);
int arrSingle[] = new int[] { 0 };
Assert.assertEquals(PrintPermutation.permutation(arrSingle), 1);
int arrEmpty[] = new int[] {};
Assert.assertEquals(PrintPermutation.permutation(arrEmpty), 0);
}
}