How to do Combinatorics on the Fly

匆匆过客 提交于 2019-12-05 17:15:51

So this is the cartesian product, you're after?

Assume 3 lists, with 2, 1 and 3 Elements. You would end in 2*1*3 combinations = 6. (abstract: a * b * ... * i)

Now you take 6 numbers from 0 to 5.

void getCombiFor (int i, List <List <Integer>> li) 
{
     if (li.length > 0) 
     { 
        int idx = i % li.get (0).size ();        
        System.out.print (li.get (0).get(idx));                 
        getCombiFor (i - idx, li.remove (0));
     } 
     System.out.println ();
}   
// pseudocodeline:
List li = List (List ('a', 'b'), List ('c'), List ('d', 'e', 'f'))
for (int i = 0; i < 6; ++i) 
{
     getCombiFor (i, li);
}

Example:

Lists = ((a,b), (c), (d,e,f))
acd
bcd
acf
bcf
ace
bce
Caner

You don't need to use any memory to solve this problem. It's possible to get the Nth element of list mathematicaly, without creating the whole combinations. It is explained here

How about creating an array of indices, one for each of the given lists? The current combination could be read off by doing get() on each list in turn. Each index would at zero -- then to advance to the next combination you do in effect

index[0]++;
if (index[0] >= list[0].size()) {
    index[0] = 0;
    index[1]++;
    if (index[1] >= list[1].size()) {
        ...
    }
}

(Turning the nested if's into an iteration left as an exercise for the reader.)

Why don't you actually make a hashmap?

Map<String,Map<String,String>> mainMap = new HashMap<String,Map<String,String>>();

for(List l : lists) {
    for(Data d : l) {
        String item = d.item;
        String name = d.name;
        String value = d.value;

        Map<String,String> itemMap = mainMap.get(item);
        if(item == null) {
            itemMap = new HashMap<String,String>(); 
            mainMap.put(item,itemMap);
        }
        itemMap.put(name,value);
    }
} 

later, you want to get all the values for a given name, no matter what item?

List<String> getValuesForName(String name) {
    List<String> list = new LinkedList<String>();
    for(Map<String,String map : mainMap) {
        String value = map.get(name);
        if(value != null) list.add(value);
    }
    return list;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!