java - 如何从多个列表中获取笛卡尔积?

标签 java list algorithm matrix cartesian-product

假设我有几个 List<T> s,我会把它们放入另一个列表或其他集合中,所以我不知道有多少list<T>我有,直到我打电话List<List<T>>.size()

如下List<Integer>举个例子:

list1=[1,2]
list2=[3,4]
list3=[5,6]
....
listn=[2*n-1,2n];

如何获得 list1*list2*list3*...listn 的结果作为笛卡尔积?

例如:

list1*list2*list3

应该是:

[1,3,5],[1,3,6],[1,4,5],[1,4,6],[2,3,5],[2,3,6],[2,4,5],[2,4,6]

最佳答案

您可以使用递归来实现它,递归的基本情况是当输入为空时返回空列表,否则处理剩余元素。例如

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

public class CartesianProduct {
    public static <T> List<List<T>> calculate(List<List<T>> input) {
        List<List<T>> res = new ArrayList<>();
        if (input.isEmpty()) { // if no more elements to process
            res.add(new ArrayList<>()); // then add empty list and return
            return res;
        } else {
            // we need to calculate the cartesian product
            // of input and store it in res variable
            process(input, res);
        }
        return res; // method completes , return result
    }

    private static <T> void process(List<List<T>> lists, List<List<T>> res) {
        //take first element of the list
        List<T> head = lists.get(0);
        //invoke calculate on remaining element, here is recursion
        List<List<T>> tail = calculate(lists.subList(1, lists.size()));

        for (T h : head) { // for each head
            for (List<T> t : tail) { //iterate over the tail
                List<T> tmp = new ArrayList<>(t.size());
                tmp.add(h); // add the head
                tmp.addAll(t); // and current tail element
                res.add(tmp);
            }
        }
    }

    public static void main(String[] args) {
        //we invoke the calculate method
        System.out.println(calculate(Arrays.asList(
                Arrays.asList(1, 2),
                Arrays.asList(3, 4),
                Arrays.asList(5, 6))));
    }
}

输出

[[1,3,5],[1,3,6],[1,4,5],[1,4,6],[2,3,5],[2,3,6],[2,4,5],[2,4,6]]

关于java - 如何从多个列表中获取笛卡尔积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26995166/

相关文章:

python - 在每个可能的组合中调用函数

java - JNA 和结构体数组作为参数

python - 生成包含数组元素的每个组合的数组

perl - 为什么我的 Perl 打印显示 HASH(0x100a2d018)?

python - 找到两个列表之间的共同元素?

arrays - 在 0 和 1 的排序数组中查找 1 位置的解决方案

java - 当我们创建数组的数组时,有多少对象符合垃圾收集器的条件?

具有自签名证书的 Java SSL 连接,无需将完整的 keystore 复制到客户端

java - 实体管理器 - "cloud ready"、 "graph"、 "self validating"

node.js - 我应该如何保证涉及金融交易操作的数据库的一致性