Tuesday, 5 September 2017

java - permutations of an array (Heap's algorithm)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Toast {
    /**
     * https://en.wikipedia.org/wiki/Permutation
     * https://en.wikipedia.org/wiki/Heap%27s_algorithm
     * 
     * @param array
     * @return
     */
    public static <E>  List<E[]> permutations(E[] array) {
        ArrayList<E[]> list = new ArrayList<>();
        permute(array, array.length, list);
        return  list;
    } 

    static <E>  void permute(E[] array, int n, List<E[]> collector) {

        if(n == 1)
            collector.add(Arrays.copyOf(array, array.length));
        else {
            for (int i = 0; i < n; i++) {
                permute(array, n - 1, collector);
                if (n % 2 == 1)
                    swap(array, 0, n - 1);
                else
                    swap(array, i, n - 1);
            }
        }
    }
}

styled using hilite.me

No comments:

Post a Comment