Get all 1-k tuples in a n-tuple

前端 未结 3 1071
借酒劲吻你
借酒劲吻你 2021-01-29 04:38

With n=5 and k=3 the following loop will do it

List l=new ArrayList();
l.add(\"A\");l.add(\"B\");l.add(\"C\");l.add(\"D\");l.add(\"E\         


        
3条回答
  •  攒了一身酷
    2021-01-29 05:30

    this should be the most efficient way, even if k embedded loops looks ugly

    //singleton
    for (int i = 0; i < l.size(); i++) {
        System.out.println(l.get(i));
    }
    
    //pairs
    for (int i = 0; i < l.size(); i++) {
        for (int j = i+1; j < l.size(); j++) {
            System.out.println(l.get(i)+l.get(j));
        }
    }
    
    //3-tuple
    for (int i = 0; i < l.size(); i++) {
        for (int j = i+1; j < l.size(); j++) {
            for (int k = j+1; k < l.size(); k++) {
                System.out.println(l.get(i)+l.get(j)+l.get(k));
            }
        }
    }
    // ...
    //k-tuple
    

提交回复
热议问题