Iterative Cartesian Product in Java

前端 未结 9 1882
既然无缘
既然无缘 2020-11-27 07:00

I want to compute the cartesian product of an arbitrary number of nonempty sets in Java.

I\'ve wrote that iterative code...

public s         


        
9条回答
  •  Happy的楠姐
    2020-11-27 07:28

    You might be interested in Another question about cartesian products (edit: removed to conserve hyperlinks, search for the tag cartesian products). That answer has a nice recursive solution that I'd be hard pressed to improve on. Do you specifically want an iterative solution instead of recursive solution?


    EDIT:

    After looking at another iterative solution on stack overflow in perl and a clean explanation , here is another solution:

    public static  List> uglyCartesianProduct(List> list) {
            List> iterators = new ArrayList>(list.size());
            List elements = new ArrayList(list.size());
            List> toRet = new ArrayList>();
    
            for (int i = 0; i < list.size(); i++) {
                iterators.add(list.get(i).iterator());
                elements.add(iterators.get(i).next());
            }
    
            for(int i = 0; i < numberOfTuples(list); i++)
            {
                toRet.add(new HashSet());
            }
    
            int setIndex = 0;
            for (Set set : list) {
                int index = 0;
                for (int i = 0; i < numberOfTuples(list); i++) {
                    toRet.get(index).add((T) set.toArray()[index % set.size()]);
                    index++;
                }
                setIndex++;
            }
    
            return toRet;
        }
    
        private static  int numberOfTuples(List> list) {
            int product = 1;
            for (Set set : list) {
                product *= set.size();
            }
            return product;
        }
    

提交回复
热议问题