Java : Cartesian Product of a List of Lists

后端 未结 12 1093
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 19:03

I have a problem that is really kind of a general programming question, but my implementation is in Java, so I will provide my examples that way

I have a class like

12条回答
  •  甜味超标
    2020-12-02 19:55

    I'm late to the party but I followed Shiomi's link and translated the functions into Java. The result is an easy to follow and understand algorithm (I may be a little slow since I had a hard time understanding Bart Kiers' solution).

    Here it is (the key is an int, replacing to String should be straightforward):

    Usage

        public void testProduct(){
            Map> data =   new LinkedHashMap>(){{                
                put(0, new ArrayList(){{
                    add("John"); add("Sarah");                      
                }});                
                put(1, new ArrayList(){{
                    add("Red"); add("Green"); add("Blue"); add("Orange");
                }});
                put(2, new ArrayList(){{
                    add("Apple"); add("Tomatoe"); add("Bananna");                   
                }});
        }};
    
            List product =  GetCrossProduct(data);
            for(String[] o : product)
                System.out.println(Arrays.toString(o));
    
        }
    

    Result

    [John, Red, Apple]
    [John, Red, Tomatoe]
    [John, Red, Bananna]
    [John, Green, Apple]
    [John, Green, Tomatoe]
    [John, Green, Bananna]
    [John, Blue, Apple]
    [John, Blue, Tomatoe]
    [John, Blue, Bananna]
    [John, Orange, Apple]
    [John, Orange, Tomatoe]
    [John, Orange, Bananna]
    [Sarah, Red, Apple]
    [Sarah, Red, Tomatoe]
    [Sarah, Red, Bananna]
    [Sarah, Green, Apple]
    [Sarah, Green, Tomatoe]
    [Sarah, Green, Bananna]
    [Sarah, Blue, Apple]
    [Sarah, Blue, Tomatoe]
    [Sarah, Blue, Bananna]
    [Sarah, Orange, Apple]
    [Sarah, Orange, Tomatoe]
    [Sarah, Orange, Bananna]
    

    Cartesian Product Functions

        public static List GetCrossProduct(Map> lists)
        {
            List results = new ArrayList();
            GetCrossProduct(results, lists, 0, new String[(lists.size())]);
            return results;
        }
    
        private void GetCrossProduct(List results, Map> lists, int depth, String[] current)
        {
            for (int i = 0; i < lists.get(depth).size(); i++)
            {
                current[depth] = lists.get(depth).get(i);            
                if (depth < lists.keySet().size() - 1)
                    GetCrossProduct(results, lists, depth + 1, current);
                else{
                    results.add(Arrays.copyOf(current,current.length));                
                }
            }
        }       
    

提交回复
热议问题