在Java中實現笛卡爾積可以使用循環嵌套、遞歸、流等方法。以下是幾種常見的實現方法:
List<List<Integer>> sets = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5, 6)
);
List<List<Integer>> cartesianProduct = new ArrayList<>();
for (int i = 0; i < sets.get(0).size(); i++) {
for (int j = 0; j < sets.get(1).size(); j++) {
for (int k = 0; k < sets.get(2).size(); k++) {
List<Integer> tuple = Arrays.asList(sets.get(0).get(i), sets.get(1).get(j), sets.get(2).get(k));
cartesianProduct.add(tuple);
}
}
}
public static List<List<Integer>> cartesianProduct(List<List<Integer>> sets, int index) {
if (index == sets.size() - 1) {
return sets.get(index).stream()
.map(Collections::singletonList)
.collect(Collectors.toList());
}
List<List<Integer>> result = new ArrayList<>();
for (int i : sets.get(index)) {
for (List<Integer> rest : cartesianProduct(sets, index + 1)) {
List<Integer> tuple = new ArrayList<>();
tuple.add(i);
tuple.addAll(rest);
result.add(tuple);
}
}
return result;
}
List<List<Integer>> sets = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5, 6)
);
List<List<Integer>> cartesianProduct = sets.stream()
.reduce((a, b) -> a.stream()
.flatMap(i -> b.stream().map(j -> new ArrayList<>(Arrays.asList(i, j))))
.collect(Collectors.toList()))
.orElse(Collections.emptyList());
以上是幾種常見的Java實現笛卡爾積的方法,具體選擇哪種方法取決于具體的需求和場景。