获取具有子集的列表的"相邻"值的算法

HBv*_*Bv6 0 java algorithm list subset

我有这样的文本文件:

A
B
C
Run Code Online (Sandbox Code Playgroud)

每个元素都有一个像这样的子集:

A = { a1, a2, a3 }
B = { b1, b2 }
C = { c1, c2, c3 }
Run Code Online (Sandbox Code Playgroud)

我想生成这个:

    a1, b1, c1
    a2, b1, c1
    a3, b1, c1
    a1, b2, c1
    a1, b1, c2
    a1, b1, c3

我不知道文本文件中的元素数量(例如可能是:A,B,C,D,E),并且子集的大小可能不同.

我只能认为这是一个带有2个索引的递归函数,可能是"数组中的位置"和"数组的索引",但我真的不知道如何实现所有这些.

我甚至尝试使用相同的输入调整笛卡尔积的函数,但我完全失败了.我不需要生成笛卡尔积.

che*_*ken 6

构建"基本列表",它由每个列表的第一个元素组成.然后循环遍历所有列表的所有元素.对于每个这样的元素,使用该元素在适当的位置更新基本列表,并将此更新的列表添加到正在运行的列表中.

我在下面列出了一个示例实现.

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

[a1, b1, c1]
[a2, b1, c1]
[a3, b1, c1]
[a1, b2, c1]
[a1, b1, c2]
[a1, b1, c3]
Run Code Online (Sandbox Code Playgroud)