我有一个这样的文本文件:
A
B
C
每个元素都有这样的子集:
A = { a1, a2, a3 }
B = { b1, b2 }
C = { c1, c2, c3 }
我想生成这个:
a1, b1, c1 a2, b1, c1 a3, b1, c1 a1, b2, c1 a1, b1, c2 a1, b1, c3
我不知道文本文件中元素的数量(例如可能是:A、B、C、D、E)并且子集的大小可能会有所不同。
我只能认为这是一个具有 2 个索引的递归函数,可能是“数组中的位置”和“数组的索引”,但我真的不知道如何实现所有这些。
我什至尝试调整一个函数,该函数使用相同的输入进行笛卡尔积,但我完全失败了。 我不需要生成笛卡尔积。
最佳答案
构建“基本列表”,它由每个列表的第一个元素组成。然后遍历所有列表的所有元素。对于每个这样的元素,用该元素在适当的位置更新基本列表,并将这个更新的列表添加到列表的运行计数中。
我在下面包含了一个示例实现。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AdjacentListGenerator {
public static <T> List<List<T>> generateAdjacentLists(List<List<T>> lists) {
List<List<T>> result = new ArrayList<List<T>>();
List<T> baseList = new ArrayList<T>();
// Generate the base list, which is comprised of all the first elements
for (List<T> list : lists) {
baseList.add(list.get(0));
}
result.add(baseList);
// Loop over each list, and for each element beyond the first, make a
// copy of the base list, update that element in place, and add it to
// our result
for (int list_i = 0; list_i < lists.size(); list_i++) {
List<T> list = lists.get(list_i);
for (int listElement_i = 1; listElement_i < list.size(); listElement_i++) {
List<T> updatedList = new ArrayList<T>(baseList);
updatedList.set(list_i, list.get(listElement_i));
result.add(updatedList);
}
}
return result;
}
public static void main(String... args) {
List<String> a = Arrays.asList(new String[] { "a1", "a2", "a3" });
List<String> b = Arrays.asList(new String[] { "b1", "b2" });
List<String> c = Arrays.asList(new String[] { "c1", "c2", "c3" });
List<List<String>> lists = new ArrayList<List<String>>();
lists.add(a);
lists.add(b);
lists.add(c);
for (List<String> list : AdjacentListGenerator
.generateAdjacentLists(lists)) {
System.out.println(list);
}
}
}
输出
[a1, b1, c1]
[a2, b1, c1]
[a3, b1, c1]
[a1, b2, c1]
[a1, b1, c2]
[a1, b1, c3]
关于java - 获取具有子集的列表的 "adjacent"值的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11052229/