c++ - 权重增加的枚举位集。 (C++ & Boost::dynamic_bitset)

标签 c++ algorithm boost bitset

<分区>

如何用C++实现算法? 这样的任务,有一个bitset size N。需要一直遍历所有的bitset overhang k = 1,2, ... l,直到序列总数不等于M。即, 结果应该是一个数组:

0 ... 001
0 ... 010
0 ... 100
...
1 ... 000
0 ... 011
0 ... 101
0 ... 110
....
....
etc

权重为 1 时,向左清除按位。但是如何处理权重为 k = 2,3 的比特集,...同时保持算法的质量我不知道。请帮助,有人可以面临类似的挑战。 Bitset 使用 boost::dynamic_bitset 实现。 C++ 语言。

最佳答案

您可能会发现此 C 代码很有帮助。

函数 make_sets 生成特定权重的所有位模式,因此 main 多次调用它以首先生成具有 1 个设置位的模式,然后是 2 个设置位等。

#include <stdio.h>

#define BYTETOBINARYPATTERN "%d%d%d%d%d"
#define BYTETOBINARY(byte)  \
  (byte & 0x10 ? 1 : 0), \
  (byte & 0x08 ? 1 : 0), \
  (byte & 0x04 ? 1 : 0), \
  (byte & 0x02 ? 1 : 0), \
  (byte & 0x01 ? 1 : 0) 

/* Make all bitsets with bits_to_add set bits in the least significant num_bits bits 
The most significant bit are taken from high_bits.*/
void make_sets(int high_bits, int bits_to_add, int num_bits) {
    // Recurse on the position of the next set bit
    int i;
    if (bits_to_add) {
        for(i=bits_to_add-1;i<num_bits;i++)
            make_sets(high_bits + (1<<i), bits_to_add-1, i);
    } else {
        printf (BYTETOBINARYPATTERN"\n", BYTETOBINARY(high_bits));
    }
}

int main(int argc,char *argv[]) {
    int M;
    for(M=1;M<=5;M++)
        make_sets(0,M,5);
}

这会产生输出:

00001
00010
00100
01000
10000
00011
00101
00110
01001
01010
01100
10001
10010
10100
11000
00111
01011
01101
01110
10011
10101
10110
11001
11010
11100
01111
10111
11011
11101
11110
11111

关于c++ - 权重增加的枚举位集。 (C++ & Boost::dynamic_bitset),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19197487/

相关文章:

c++ - 如何将 Boost::asio::buffer(buf, size) 与 boost 绑定(bind)一起使用?

c++ - 使用 vector 模板时出现 mingw 链接器错误

c++ - 为什么我的浮点值会失去精度并丢掉小数位?下面的示例代码

c++ - 显示二进制加法后的最后一位

algorithm - 在数组 [1, 2 , 5, 9] 中获取总和等于 20 的所有可能组合?

javascript - 数组中的三个最小数字,没有 Math.min 方法。 Javascript

algorithm - 在 O(n) 中查找 2^k 个最大元素

c++ - boost::filesystem3::detail::dir_itr_imp 在 boost::shared_ptr 解引用中的含义

c++ - Debug模式下的 xcode 链接器错误(重复符号)

c++ - 带有使用自定义模型的复选框的qlistview