y**c 发帖数: 6307 | 1 我有一个程序计算CRC码,需要求任意2项或者以上的合并项,
比如,计算2项的合并:
void printCRCComb2(itemType *CRC, int n)
{
for(int i = 0; i < n; ++i){
for(int j = i+1; j < n; ++j){
itemType tmp = XOR(CRC[i],CRC[j]);
printCRC(&tmp,1);
}
}
}
}
但是如果计算3项,就有3个loop:
for(int i = 0; i < n; ++i){
for(int j = i+1; j < n; ++j){
itemType tmp1 = XOR(CRC[i],CRC[j]);
for(int k = j+1; k < n; ++k){
itemType tmp2 = XOR(tmp1,CRC[k]);
...
}
}
}
如果更多项,loop就更多了,容易出错,程序也不通用。有没有更好的办法?谢谢! | i***c 发帖数: 26 | | h*******u 发帖数: 15326 | 3 用一个vector存循环变量,可以做n维的
★ 发自iPhone App: ChineseWeb 7.8
【在 y**c 的大作中提到】 : 我有一个程序计算CRC码,需要求任意2项或者以上的合并项, : 比如,计算2项的合并: : void printCRCComb2(itemType *CRC, int n) : { : for(int i = 0; i < n; ++i){ : for(int j = i+1; j < n; ++j){ : itemType tmp = XOR(CRC[i],CRC[j]); : printCRC(&tmp,1); : } : }
| y**c 发帖数: 6307 | 4 嗯,这是一个办法。
【在 i***c 的大作中提到】 : 递归?
| y**c 发帖数: 6307 | 5 具体一点?
【在 h*******u 的大作中提到】 : 用一个vector存循环变量,可以做n维的 : : ★ 发自iPhone App: ChineseWeb 7.8
| b*****e 发帖数: 474 | 6 The sketch:
int K = number of loop variables
Stack p = { 0, 1, 2..., K-1 };
// initialize i, j, k, ..., since the constraint is i
// also declare necessary intermediate
// values v[] based on i,j,k values
while ( true ) {
do something with current content of p and v;
// print out p[], v[] for debugging
int t = n-1;
while (p.peek() == t-- )
{ p.pop(); /* also adjust v[p.size()-1] accordingly */ }
if ( p.empty() ) break; // done!
int c = ++p[p.size()-1]; // increment the stack top value
while (p.size() < K ) // fill up the rest of the stack
{ p.push(++c); /* also adjust v[p.size()-1] accordingly */ }
}
}
【在 y**c 的大作中提到】 : 我有一个程序计算CRC码,需要求任意2项或者以上的合并项, : 比如,计算2项的合并: : void printCRCComb2(itemType *CRC, int n) : { : for(int i = 0; i < n; ++i){ : for(int j = i+1; j < n; ++j){ : itemType tmp = XOR(CRC[i],CRC[j]); : printCRC(&tmp,1); : } : }
| O*******d 发帖数: 20343 | 7 如果有不确定的循环套循环,用递归比较好。
【在 y**c 的大作中提到】 : 我有一个程序计算CRC码,需要求任意2项或者以上的合并项, : 比如,计算2项的合并: : void printCRCComb2(itemType *CRC, int n) : { : for(int i = 0; i < n; ++i){ : for(int j = i+1; j < n; ++j){ : itemType tmp = XOR(CRC[i],CRC[j]); : printCRC(&tmp,1); : } : }
| w****6 发帖数: 796 | 8 does this work:
void printCRCCombs()
{
for(int ii=0; ii
printCRCCombs_2(CRC,N,CRC[ii],ii);
}
}
void printCRCCombs_2(const itemType *CRC,int N,cont itemType &val,int idx)
{
for(int jj=idx+1; jj
itemType tmp = XOR(val,CRC[jj]);
printCRC(&tmp,1);
printCRCCombs_2(CRC,N,tmp,jj);
}
} |
|