gpt4 book ai didi

java - JAVA中不同数量的数组和数组元素生成子集

转载 作者:行者123 更新时间:2023-11-30 02:13:43 25 4
gpt4 key购买 nike

我有如下所示的数组

A:[[1,2,3],[100,200]] 
B:[[4,5],[300,400],[500,600,700]]
C:[[6,7,8,9]]

现在我必须使用上面的数组元素进行设置。我的预期结果应该是这样的

Set1:[[1,2,3],[4,5],[6,7,8,9]]
Set2:[[1,2,3],[300,400],[6,7,8,9]]
Set3:[[1,2,3],[500,600,700],[6,7,8,9]]
Set4:[[100,200],[4,5],[6,7,8,9]]
Set5:[[100,200],[300,400],[6,7,8,9]]
Set6:[[100,200],[500,600,700],[6,7,8,9]]

这里我希望代码是动态的,就像数组的数量以及每个数组中的元素数量可能会改变一样。这里我只是用三个数组来解释。

下面是我尝试过的代码,但它不是动态的。下面的代码可以解决问题,但如果数组的数量增加,那么我必须手动更改代码,并且必须放置更多的 for 循环。我该如何克服这个问题?

List<Integer> setList = new ArrayList<>;
for (int j = 0; j < 4; j++) {
for (int k = 0; k < A.length; k++) {
for (int l = 0; l < B.length; l++) {
for (int m = 0; m < C.length; m++) {
List<Integer> tempList = new ArrayList<>
tempList.add(A[k]);
tempList.add(B[l]);
tempList.add(C[m]);
setList.add(tempList);

}
}
}
}

最佳答案

您可以将原始数据建模为 3D 数组

int [][][] arrays = new int[][][] {
{{1,2,3}, {100, 200}}, //array A
{{4,5}, {300, 400}, {500, 600, 700}},//array B
{{6,7,8,9}} //array C
};

如果您想添加新行(除了 ABC 之外),您只需添加新行对此。

public static void solve(int[][][] arrays, List<List<List<Integer>>> result, List<List<Integer>> current,
int row) {
if (row == arrays.length) {
result.add(current);
return;
}

for (int j = 0; j < arrays[row].length; j++) {
List<List<Integer>> localCurrent = new ArrayList<>(current); //Copy the previous result
List<Integer> currentData = Arrays.stream(arrays[row][j])
.boxed()
.collect(Collectors.toList()); //Convert current int[] to List<Integer>
localCurrent.add(currentData);
solve(arrays, result, localCurrent, row + 1);
}
}
<小时/>
//For int [][][] arrays mentioned eariler
List<List<List<Integer>>> result = new ArrayList<>();
List<List<Integer>> current = new ArrayList<>();

solve(arrays, result, current, 0);
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i));
}


[[1, 2, 3], [4, 5], [6, 7, 8, 9]]
[[1, 2, 3], [300, 400], [6, 7, 8, 9]]
[[1, 2, 3], [500, 600, 700], [6, 7, 8, 9]]
[[100, 200], [4, 5], [6, 7, 8, 9]]
[[100, 200], [300, 400], [6, 7, 8, 9]]
[[100, 200], [500, 600, 700], [6, 7, 8, 9]]

关于java - JAVA中不同数量的数组和数组元素生成子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49292590/

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