gpt4 book ai didi

java - 如何在 Java 中将 powerSet 的内容保存到二维数组中

转载 作者:行者123 更新时间:2023-12-01 17:31:56 26 4
gpt4 key购买 nike

我正在尝试将从一维数组获取的 PowerSet 内容保存到二维数组中。我尝试在“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
}
}
}

最佳答案

由于您的内部数组的长度可变,您可能需要使用内部 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));

之后您的列表数组将包含以下幂集:

[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.

关于java - 如何在 Java 中将 powerSet 的内容保存到二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61103715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com