我目前正在编写一个程序,其中效率非常重要。
在这个程序中,有时我会得到多达4个不同来源的值。我想检查最终得到的值是否相同,如果它们相同,我还想知道哪些来源给了我相同的数字。
我可以自行完成此操作,所以有人为我执行此操作不是我想要的,我只是想知道这样做的有效方法是什么。这是我考虑过的两件事,但我希望有一些更有效,更轻松的方法来完成此操作...
想法1:
struct box
{
char source; // because it won't be above 4
char value; // because it will be between 2 and 20
};
struct box boxes[4];
int box_count = 0, i;
for(i=0; i<4; i++)
{
if(hasValue(i))
{
boxes[box_count].source = i;
boxes[box_count++].value = getValue(i);
}
}
// idk what to do at this point, but here's how to access them...
for(i=0; i<box_count; i++)
{
printf("source, id : %d, %d\n", boxes[i].source, boxes[i].value);
}
想法2:
struct sources
{
char sources[4]; // because max 4 sources
char sources_count;
};
struct sources sources[19] = { 0 }; // because only values between 2 and 20
int i, j, v;
for(i=0; i<4; i++)
{
if(hasValue(i))
{
v = getValue(i)-2; // only between 2 and 20, and array of size 19
sources[v].sources[sources[v].sources_count++] = i;
}
}
for(i=0; i<19; i++)
{
if(sources[i].sources_count>0)
{
printf("Duplicate sources: %d", sources[i].sources[0]);
for(j=1; j<sources[i].sources_count; j++)
{
printf(", %d", sources[i].sources[j]);
}
printf("\n");
}
}
那么有没有更有效的方法?
您需要6个比较,假设数字是a,b,c,d,然后需要检查a == b,a == c,a == d,b == c,b == d,c = = d。
如果需要将其转换为状态,请尝试以下操作:
s = (a == b) ? 1 : 0;
s |= (a == c) ? 2 : 0;
s |= (a == d) ? 4 : 0;
s |= (b == c) ? 8 : 0;
s |= (b == d) ? 16 : 0;
s |= (c == d) ? 32 : 0;
或这个
s = (a ^ b) ? 0 : 1;
s |= (a ^ c) ? 0 : 2;
s |= (a ^ d) ? 0 : 4;
s |= (b ^ c) ? 0 : 8;
s |= (b ^ d) ? 0 : 16;
s |= (c ^ d) ? 0 : 32;
在X86上的Microsoft编译器上,任何一个序列都实现而没有任何分支。然后将开关用于0至63个64种情况。请注意,在64个状态中只有15个有效,其余状态无效,但是将所有这些无效情况设置为默认故障情况将允许开关情况使用单个情况。 64个入口分支目标表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句