Как сохранить содержимое PowerSet в 2d массив в Java - PullRequest
0 голосов
/ 08 апреля 2020

Я пытаюсь сохранить содержимое PowerSet, полученного из 1d Array, в 2d Array. Я попытался присвоить значения в массиве внутри оператора "if", но у меня совершенно неправильные индексы

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
            }
        }
    }

1 Ответ

0 голосов
/ 08 апреля 2020

Поскольку ваш внутренний массив имеет переменную длину, вы можете использовать вместо него внутренний java.util.ArrayList<Integer>. Примерно так:

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));

После чего ваш массив списков будет содержать следующий 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]]

Попробуйте онлайн.

...