java - 获取具有子集的列表的 "adjacent"值的算法

标签 java algorithm list subset

我有一个这样的文本文件:

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/

相关文章:

java - 如何设置多个按钮并将它们添加到 gridPane

Java 通过 gmail 发送电子邮件

algorithm - oracle中带点数据的表没有索引的最近邻查询的pl/sql代码

python-3.x - 如何在列表中将百分比转换为小数

python - 迭代时从列表中删除时会跳过迭代

java - 舍入不起作用

java - jButtons 在运行时调整大小

algorithm - 如何找到树的分支因子

c# - 自高峰期开始计算柱状图

python - 在python中获取列表的旋转