1

我有以下逻辑,需要简化以使其看起来更清晰和简洁:

 if (x1 < y1)
    return 1;
 else if (x1 == y1)) {
     if (x2 < y2)
         return 1;
     else if (x2 == y2) {
         if (x3 < y3)
             return 1;
     } else 
         return 0;
     }
 } else
    return 0;

为了解决上述问题,我应用了逻辑表达式来进一步简化这几行条件:

if (x1 < y1 || (x1 == y1 && x2 < y2) || (x1 == y1 && x2 == y2 && x3 < y3))
    return 1;
else
    return 0;

我不确定如何从这里进一步简化。谁能帮我?

更新: 为了进一步简化,我尝试将布尔代数应用于此表达式,但没有运气!我想出了这个:

A + (A1 * B) + (A1 * B1 * C)

whereA表示x1 < y1A1表示x1 == y2

4

1 回答 1

0

IMO the cleanest way to do this sort of chained relation in C is with ?::

return x1 == y1 ? x2 == y2 ? x3 < y3 : x2 < y2 : x1 < y1;

As noted in the question comments, if you really care about performance, and the values have limited range, you can use bit twiddling to combine them into a single value for comparison. If the fields are all uint16_t (unsigned 16-bit values), for example, you can do:

uint64_t x = ((uint64_t)x1 << 32) + ((uint64_t)x2 << 16) + x3;
uint64_t y = ((uint64_t)y1 << 32) + ((uint64_t)y2 << 16) + y3;
return x < y;

but this is probably less clear and probably a premature optimization.

于 2019-08-20T00:51:30.840 回答