我搜索了这个主题,但找不到。问题是:给定一个整数n
,生成一个包含2^n
和0
的所有1
组合的数组。
例如,当n = 2
时,我们应该{{0, 0}, {0, 1}, {1, 0}, {1, 1 }}
。我发现itertools.product
在Python
中使用参数repeat
执行此操作(但我的雇主严格要求C
)。
我需要代码适合n = 24, 25
个案例(并且 足够快 - 这是我雇主的要求)。
此外,我有另一个问题。 C
Generator
与Python
中的160
有什么相似之处吗?
修改
我在这里看到了很多 -ve 的反馈。我很抱歉这种困惑。在这里,我尝试重新构建我的问题:
我有一个24
元素数组,其中只标记25
(或160
)(这些标记元素的索引存储在一个单独的数组中)。我需要花费所有2^24
个元素160
次 - 每次一个或多个标记元素将被其 dual 替换,并执行一些操作(此操作需要{{ 1}}元素并且每次都产生二进制响应,我需要所有响应的XOR)。我怎样才能有效地做到这一点?
我工作的农场经理除C
以外不知道。所以,他希望在C
中完成。
*每个元素都是2D数组。
编辑#2
可能是,我仍然无法澄清我遇到的问题。我在伪代码的基础上工作:all_elements = { <collection of elements> };
all_marked_elements = { <collection of 24 marked elements> };
all_combinations = { <all 0, 1 combinations of length 2^24> };
int operation (<160 elements>) {
...
return 0 or 1;
}
x = 0;
foreach (c in all_combinations) {
e = {};
for (i >= 0; i <= 23; i=i+1) {
if (c[i] == 1) {
append all_marked_elements[i] to e;
}
}
d = get dual of all elements in e;
x xor= operation ( <all_elements with e replaced by d>);
}
show x;
答案 0 :(得分:1)
实际上,您只需要查找整数中的位。如果你有25位,那么你的排列对应于所有数字0<= i < 2^25
的位序列,它们适合简单的unsigned int
。您不需要“生成”并存储这些数字,只需在需要排列的地方使用它们。
答案 1 :(得分:1)
答案是这样的。
像这样。
int all_elements[160] = { ??? };
int all_marked_elements[24] = { ??? };
unsigned combo;
for (combo = 0; combo < 0x1000000; ++combo) {
/* you probably want to take a copy of all_elements here */
for (i = 0; i < 23; ++i) {
unsigned bit = 1 << i;
if (combo & bit) {
int marked_element = all_marked_elements[i];
/* do something I didn't understand, replacing element by its dual */
}
/* now call the operation and do something with the result */
}
}
答案 2 :(得分:-2)
#include<stdio.h>
#include<math.h>
#include<string.h>
main()
{
int i,n=2;
char arr[500];
for(i=0;i<pow(2,n);i++)
printf("%s\n",itoa(i,arr,2));
}