How do I generate a Cartesian product in Java?

前端 未结 5 1056
予麋鹿
予麋鹿 2020-12-16 19:13

I have a number of ArrayList with each ArrayList having objects and each one can have different length. I need to generate permutation like in the

5条回答
  •  無奈伤痛
    2020-12-16 20:07

    Use Guava...here is an example of a Cartesian product of a list with itself:

    public static void main(String[] args){
        //How to do a cartesian product of a List of items
        List listToSelfMultiply = Arrays.asList(new Integer(1), new Integer(2), new Integer(3), new Integer(4));
        LinkedList linkedListCopy = Lists.newLinkedList(listToSelfMultiply);
        for (Integer i:listToSelfMultiply) {
            if(linkedListCopy.size() == 1) {
                break;
            }
            linkedListCopy.remove();
            System.out.println("" + Arrays.deepToString(Lists.cartesianProduct(Arrays.asList(i), linkedListCopy).toArray()) + "");
        }
    }
    

提交回复
热议问题