英文:
How to save the contents of a powerSet into a 2d array in Java
问题
我试图将从一维数组获得的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[] //这里需要与子集对应的长度
powSet[i][j] = set[j]; //我知道这是错误的,但我的想法是将子集中的每个数字分配到二维数组中
}
}
}
英文:
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
}
}
}
答案1
得分: 0
由于您的内部数组长度是可变的,您可能希望使用内部的 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]]
英文:
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]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论