创建一个数组,它包含从0到N的二进制元素

create an array such that it contains elements from 0 to N in binary

本文关键字:元素 二进制 包含 一个 数组 创建      更新时间:2023-10-16

我需要一个快速的算法,它将生成所有可能的数字,直到一个给定的数字N在二进制数组。

e.g N=3
Then the array should be {0,0,0},{0,0,1}.....{1,1,1}
N<=17. 

我已经试过了,这是一个递归的解决方案。

void print_digits(int n, std::string const& prefix = "") {
    if (!n) {
        printf("%s,",prefix.c_str());
        return;
    }
    print_digits(n-1, prefix + '0');
    print_digits(n-1, prefix + '1');
}

c++中的所有整数都以二进制形式直接存储在内存中。因此,如果您只想存储N个数字,您应该将它们直接写入数组"原样"

std::vector<unsigned> Numbers;
// if N is length of the number, calculate the maximum as 2^N - 1
long long Max = 1 << N - 1;
for (unsinged i = 0; i < Max; ++i)
    Numbers.push_back(i);

如果你想用二进制表示它们,它也很简单,即使你想自己编码。(请原谅,因为这只是一个简单的示例实现)

void PrintAsBits(unsigned value) {
    for (int i = sizeof(unsigned) * 8 - 1; i >= 0; --i)
        cout << ((1 << i) & value) ? 1 : 0;
    cout << 'n';
}

如果有人关心的话,下面的代码实现了原始规范,它调用了一种方法来填充一个二维数组,其中每个值都以数字数组表示,其元素对应于其值的二进制数字,以大端序。

#include <iostream>
static const int DIGIT_COUNT = 10;
static const int VALUE_COUNT = 1 << DIGIT_COUNT;
unsigned char g_binarray[VALUE_COUNT][DIGIT_COUNT];
void Populate() {
    for(int i=0; i<VALUE_COUNT; ++i) {
        unsigned char (&curr)[DIGIT_COUNT] = g_binarray[i];
        for(int di=0; di<DIGIT_COUNT; ++di) {
            curr[di] = unsigned char((i >> (DIGIT_COUNT - 1 - di)) & 1);
        }
    }
}
void DumpArray() {
    static const char *digits = "01";
    for(int i=1; i<VALUE_COUNT; ++i) {
        for(int di=0; di<DIGIT_COUNT; ++di) {
            std::cout << digits[!!g_binarray[i][di]];
        }
        std::cout << "    " << i << std::endl;
    }
}
int main(int argc, char* argv[]) {
    Populate();
    DumpArray();
    return 0;
}

正如我在一篇文章中所写的:

示例:如果需要长度为4的数组,则必须有2^4 = 16个不同的数组。

您可以使用以下简单的Java代码生成所有数组:

for (int i=0; i < 16; i++) {
        System.out.println(Integer.toBinaryString(i));
}

命令的输出:

0 110 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111