What is the fastest algorithm to computer all permutations of a binary number with same hamming weight?

前端 未结 2 1664
难免孤独
难免孤独 2021-01-02 16:42

I want an algorithm to compute all permutations of a fixed size binary number with a given hamming weight. For example, if the hamming weight is 2 and the binary size is 4 t

相关标签:
2条回答
  • 2021-01-02 17:09

    You can implement the "lexicographically next bit-permutation" using Gosper's Hack:

    unsigned int v; // current permutation of bits 
    unsigned int w; // next permutation of bits
    
    unsigned int t = v | (v - 1); // t gets v's least significant 0 bits set to 1
    // Next set to 1 the most significant bit to change, 
    // set to 0 the least significant ones, and add the necessary 1 bits.
    w = (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctz(v) + 1));
    

    Or if you don't have ctz (_BitScanForward on MSVC),

    unsigned int t = (v | (v - 1)) + 1;  
    w = t | ((((t & -t) / (v & -v)) >> 1) - 1);
    
    0 讨论(0)
  • 2021-01-02 17:09

    You can generate them in the following manner:

    1. Initially, make a vector with n - r zeros in the beginning and r ones in the end(0011 for n = 4 and r = 2).

    2. Then, repeat the following procedure:

      1. Find the rightmost one such that a zero is located to the left from it. If there is no such one, we are done.
      2. Move it to the left(by one position, that is, swap it with a zero).
      3. Move all the ones that are located to the right from it to the very end of the vector.
        For example, if we have 0110, we first move the rightmost one that can be moved to the left and get 1010, then we shift all ones to the right from it to the end of the vector and get 1001.

    This solution has O(C(n, r) * n) time complexity. One more feature of this solution: it generates elements in lexicographical order.

    0 讨论(0)
提交回复
热议问题