Tuesday, 5 September 2017

java - powerset of an array

 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
38
39
40
41
42
43
44
45
46
47
48
import java.lang.reflect.Array;
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/Power_set
     * @param set
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <E>  List<E[]> powerSet(E[] set) {
        return 
                Stream.of(binaryCounter(set.length))
                .map(is -> {
                    E[] ar = (E[])Array.newInstance(set.getClass().getComponentType(), is.length);

                    for (int i = 0; i < is.length; i++) {
                        if(is[i] != 0)
                            ar[i] = set[i];
                    }
                    return Stream.of(ar).filter(a -> a != null).toArray(size -> (E[])Array.newInstance(set.getClass().getComponentType(), size));
                }).sorted(Comparator.comparing(ar -> ar.length)).collect(Collectors.toList());
    }

    static int[][] binaryCounter(int length) {
        int size = (int) Math.pow(2, length);

        int[][] indices = new int[size][length];

        int half = size/2;
        for (int i = 0; i < length && half > 0; i++) {
            int num = 1;
            for (int j = 0; j < indices.length; j++) {
                if(j%half == 0)
                    num = num == 1 ? 0 : 1;
                indices[j][i] = num;
            }
            half /= 2;
        }

        return indices;
    }


}

styled using hilite.me

No comments:

Post a Comment