gpt4 book ai didi

java - Java中生成多个列表的所有排列

转载 作者:行者123 更新时间:2023-12-01 06:51:02 28 4
gpt4 key购买 nike

我有 n 个列表,例如:

L_1 = [a_11, a_12, ...]
L_2 = [a_21, a_22, ...]
...
L_n = [a_n1, a_n2, ...]

其中第 i 个列表有 k_i 个元素。现在,我想生成所有 n 元素列表,其中第 i 个元素来自 L_i,我的意思是:

[a_11, a_21, ..., a_n1]
[a_11, a_21, ..., a_n2]
...
[a_11, a_22, ..., a_n1]
[a_11, a_22, ..., a_n2]
...
[a_12, a_21, ..., a_n1]
[a_12, a_21, ..., a_n2]
...
[a_12, a_22, ..., a_n1]
[a_12, a_22, ..., a_n2]
...

列表总数应等于k_1*k_2*...k_n。你能描述一下这个算法的伪代码或者使用Java代码吗?当列表数量被硬编码时,我可以使用嵌套 for 循环来执行此操作,但当 n 在运行时可自定义时,我完全被阻止。

最佳答案

好的,我实现了这个算法。

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PermutationGenerator {
private List<List<Integer>> result;
private List<List<Integer>> data;

public List<List<Integer>> permutate(List<List<Integer>> data) {
this.data = data;
this.result = Lists.newArrayList();

List<Integer> integers = new ArrayList<Integer>(Collections.nCopies(data.size(), 0));
foo(0, data.size() - 1, integers);
return result;
}

private void foo(Integer index, Integer maxIndex, List<Integer> output) {
List<Integer> list = data.get(index);
for (int i = 0; i < list.size(); i++) {
output.set(index, list.get(i));
if (index == maxIndex) {
result.add(Lists.newArrayList(output));
} else {
foo(index + 1, maxIndex, output);
}
}
}
}

测试类:

import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

public class PermutationGeneratorTest {
@Test
public void test() throws Exception {
// given
PermutationGenerator pg = new PermutationGenerator();

List<Integer> list1 = Lists.newArrayList(1, 2, 3);
List<Integer> list2 = Lists.newArrayList(4, 5);
List<Integer> list3 = Lists.newArrayList(6, 7, 8, 9);

List<List<Integer>> input = Lists.newArrayList(list1, list2, list3);

// when
List<List<Integer>> output = pg.permutate(input);

// then
print(output);
}

private void print(List<List<Integer>> output) {
for (List<Integer> list : output) {
System.out.println(Arrays.toString(list.toArray()));
}
System.out.println("TOTAL: " + output.size());
}
}

输出:

[1, 4, 6]
[1, 4, 7]
[1, 4, 8]
[1, 4, 9]
[1, 5, 6]
[1, 5, 7]
[1, 5, 8]
[1, 5, 9]
[2, 4, 6]
[2, 4, 7]
[2, 4, 8]
[2, 4, 9]
[2, 5, 6]
[2, 5, 7]
[2, 5, 8]
[2, 5, 9]
[3, 4, 6]
[3, 4, 7]
[3, 4, 8]
[3, 4, 9]
[3, 5, 6]
[3, 5, 7]
[3, 5, 8]
[3, 5, 9]
TOTAL: 24

关于java - Java中生成多个列表的所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29172066/

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