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

前端 未结 2 1665
难免孤独
难免孤独 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);
    

提交回复
热议问题