How do I generate a Cartesian product in Java?

前端 未结 5 1095
予麋鹿
予麋鹿 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条回答
  •  猫巷女王i
    2020-12-16 20:10

    With an Iterable+Iterator:

    import java.util.*;
    
    class CartesianIterator  implements Iterator > {
    
        private final List > lilio;    
        private int current = 0;
        private final long last;
    
        public CartesianIterator (final List > llo) {
            lilio = llo;
            long product = 1L;
            for (List  lio: lilio)
                product *= lio.size ();
            last = product;
        } 
    
        public boolean hasNext () {
            return current != last;
        }
    
        public List  next () {
            ++current;
            return get (current - 1, lilio);
        }
    
        public void remove () {
            ++current;
        }
    
        private List get (final int n, final List > lili) {
            switch (lili.size ())
            {
                case 0: return new ArrayList  (); // no break past return;
                default: {
                    List  inner = lili.get (0);
                    List  lo = new ArrayList  ();
                    lo.add (inner.get (n % inner.size ()));
                    lo.addAll (get (n / inner.size (), lili.subList (1, lili.size ())));
                    return lo;
                }
            }
        }
    }
    
    class CartesianIterable  implements Iterable > {
    
        private List > lilio;  
    
        public CartesianIterable (List > llo) {
            lilio = llo;
        }
    
        public Iterator > iterator () {
            return new CartesianIterator  (lilio);
        }
    }
    

    You can use them in a simplified for-loop:

    class CartesianIteratorTest {
    
        public static void main (String[] args) {
            List  la = Arrays.asList (new Character [] {'a', 'b', 'c'});
            List  lb = Arrays.asList (new Character [] {'d', 'e'});      
            List > llc = new ArrayList > ();
            llc.add (la);
            llc.add (lb);
    
            CartesianIterable  ci = new CartesianIterable  (llc);
            for (List lo: ci)
                show (lo);
        }
    
        public static void show (List  lo) {
            System.out.print ("(");
            for (Object o: lo)
                System.out.print (o);
            System.out.println (")");
        }
    }
    

提交回复
热议问题