Michael Michael - 1 month ago 6
Java Question

Best way to get a power set of an array?

What is the best way to get the power set of an array? For example if I have an array:

int[] A = {1, 2}


And to get the following output

int[] P = {{}, {1}, {2}, {1, 2}}

Answer

Try this.

int[] a = {1, 2};
int max = 1 << a.length;
int[][] result = new int[max][];
for (int i = 0; i < max; ++i) {
    result[i] = new int[Integer.bitCount(i)];
    for (int j = 0, b = i, k = 0; j < a.length; ++j, b >>= 1)
        if ((b & 1) != 0)
            result[i][k++] = a[j];
}
System.out.println(Arrays.deepToString(result));

result:

[[], [1], [2], [1, 2]]