本文介绍了在n元组中获取所有1-k元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在n = 5且k = 3的情况下,以下循环会做到这一点

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

List<String> l=new ArrayList<String>();
l.add("A");l.add("B");l.add("C");l.add("D");l.add("E");
int broadcastSize = (int) Math.pow(2, l.size());
for (int i = 1; i < broadcastSize; i++) {
    StringBuffer buffer = new StringBuffer(50);
    int mask = i;
    int j = 0;
    int size=0;
    System.out.println();
    while (mask > 0) {
        if ((mask & 1) == 1) {
            System.out.println(".. "+mask);
            buffer.append(l.get(j));
            if (++size>3){
                buffer = new StringBuffer(50);
                break;
            }
        }
        System.out.println(" "+mask);
        mask >>= 1;
        j++;
    }
    if (buffer.length()>0)
        System.out.println(buffer.toString());

}

但是效率不高,我想使用银行家的顺序来完成,从而探究第一个单例,然后配对,然后是3元组,然后停止.

but it's not efficient I would like to do it with Banker's sequence and thus explore first singletons, then pairs, then 3-tuple and stop.

我没有找到一种方法,但是至少此循环应该更有效:

I did not find a way do that, but at least this loop should be more efficient:

List<String> l=new ArrayList<String>();
l.add("A");l.add("B");l.add("C");l.add("D");l.add("E");
int broadcastSize = (int) Math.pow(2, l.size());
for (int i = 1; i < broadcastSize; i++) {
    StringBuffer buffer = new StringBuffer(50);
    int mask = i;
    int j = 0;

    if (StringUtils.countMatches(Integer.toBinaryString(i), "1") < 4){
        while (mask > 0) {
            if ((mask & 1) == 1) {
                buffer.append(l.get(j));

            }
            mask >>= 1;
            j++;
        }
        if (buffer.length()>0)
            System.out.println(buffer.toString());
    }


}

也有:但是k个嵌入式循环看起来很丑

there is also: but 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

推荐答案

这应该是最有效的方法,即使k个嵌入式循环看起来很丑

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

这篇关于在n元组中获取所有1-k元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:39