Get all 1-k tuples in a n-tuple

前端 未结 3 1074
借酒劲吻你
借酒劲吻你 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:26

    This technique is called Gosper's hack. It only works for n <= 32 because it uses the bits of an int, but you can increase it to 64 if you use a long.

    int nextCombo(int x) {
      // moves to the next combination with the same number of 1 bits
      int u = x & (-x);
      int v = u + x;
      return v + (((v ^ x) / u) >> 2);
    }
    
    ...
    for (int x = (1 << k) - 1; (x >>> n) == 0; x = nextCombo(x)) {
      System.out.println(Integer.toBinaryString(x));
    }
    

    For n = 5 and k = 3, this prints

    111
    1011
    1101
    1110
    10011
    10101
    10110
    11001
    11010
    11100
    

    exactly as you'd expect.

提交回复
热议问题