从对象的arraylist的arraylist获得所有可能的组合

时间:2017-03-18 17:22:49

标签: java algorithm arraylist

我想从以下提取所有可能的组合 包含所有数据的数组列表具有此结构

ArrayList<object> students = new ArrayList<object>();
ArrayList<object> staff = new ArrayList<object>();
ArrayList<object> uni = new ArrayList<object>();
ArrayList<object> exam = new ArrayList<object>();

ArrayList<ArrayList<object>> main = new ArrayList<object>();
main.add(this.students);
main.add(this.staff);
main.add(this.uni);
main.add(this.exam);

类对象只有两个变量

class object {
    public String name; 
    public double cost;
}

此主变量包含表中所示的以下数据,每列可能具有1到100的值,但这并不意味着每列必须具有相同数量的值

|学生|员工| UNI --- |考试|
| 500 -------- | 400-- | 1400 | 20000 |
| 350 -------- | 250-- | 1100 | 10000 |

所以我想提取的是类似的东西 500 =&GT; 400 = GT; 1400 =&GT; 20000个
500 =&GT; 400 = GT; 1400 =&GT; 10000

500 =&GT; 400 = GT; 1100 =&GT; 20000个
500 =&GT; 400 = GT; 1100 =&GT; 10000

500 =&GT; 250 =&GT; 1400 =&GT; 20000个
500 =&GT; 250 =&GT; 1400 =&GT; 10000

500 =&GT; 250 =&GT; 1100 =&GT; 20000个
500 =&GT; 250 =&GT; 1100 =&GT; 10000

350 =&GT; 400 = GT; 1400 =&GT; 20000个
350 =&GT; 400 = GT; 1400 =&GT; 10000

350 =&GT; 400 = GT; 1100 =&GT; 20000个
350 =&GT; 400 = GT; 1100 =&GT; 10000

350 =&GT; 250 =&GT; 1400 =&GT; 20000个
350 =&GT; 250 =&GT; 1400 =&GT; 10000

350 =&GT; 250 =&GT; 1100 =&GT; 20000个
350 =&GT; 250 =&GT; 1100 =&GT; 10000

我该怎么做?

1 个答案:

答案 0 :(得分:2)

这样一个简单的递归函数怎么样?

ArrayList<ArrayList<object>> combs = new ArrayList<>();
object[] comb = new object[main.size()];

void generate(int pos) {
    if (pos == comb.length)
        combs.add(new ArrayList<object>(Arrays.asList(comb)));
    else {
        ArrayList<object> arr = main.get(pos);
        for (object el : arr) {
            comb[pos] = el;
            generate(pos + 1);
        }
    }
}