简体   繁体   中英

How to save the contents of a powerSet into a 2d array in Java

I'm trying to save the contents of a PowerSet, obtained from a 1d Array into a 2d Array. I tried assigning the values in the array inside the "if" Statement but I'm getting the indices completely wrong

int[] set = new int[]{2,4,5,8}
int powSetLength = (int) Math.pow(2,set.length);
int[][] powSet = new int[powSetLength][];


    for (int i = 0; i<powSetLength; i++){

        for (int j = 0; j<set.length; j++){
            if ((i & (1<<j))>0) {
                powSet[i] = new int[] //here needs to be the length corresponding to the subset
                powSet[i][j] = set[j]; //I know this is wrong but my idea was to assign each number of a subset into the 2d array
            }
        }
    }

Since your inner array is of variable length, you might want to use an inner java.util.ArrayList<Integer> instead. Something like this:

int[] set = new int[]{2,4,5,8};
int powSetLength = (int) Math.pow(2,set.length);
List<Integer>[] powSet = new List[powSetLength];

for (int i = 0; i<powSetLength; i++){
    for (int j = 0; j<set.length; j++){
        if ((i & (1<<j))>0) {
            // If the `i`'th powerSet isn't initialized yet: create an empty ArrayList:
            if(powSet[i] == null)
                powSet[i] = new ArrayList<>();
            // And add the current set-value to the List:
            powSet[i].add(set[j]);
        }
    }
}

System.out.println(Arrays.toString(powSet));

After which your array of Lists will contain the following powerset:

[null, [2], [4], [2, 4], [5], [2, 5], [4, 5], [2, 4, 5], [8], [2, 8], [4, 8], [2, 4, 8], [5, 8], [2, 5, 8], [4, 5, 8], [2, 4, 5, 8]]

Try it online.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM