Is there a general approach for optimizing bitwise expressions that distinguish two arbitrary sets of integers?

  Kiến thức lập trình

For context, I need to write a test for an integer between 0 and 7 inclusive, that evaluates to true for {1,3,4,6} and false for {0,2,5,7}. I thought for a couple minutes about whether there might be a short expression combining a few bitwise operations that would do the job (similar to how n & 1 would work on {1,3,5,7}, for example) but none jumped out at me.

In practice, there’s no pressing need to use bitwise arithmetic here, something like a switch or lookup table will work fine, but it did lead to me wondering whether there exists a deterministic way to find such an expression: such that inputting numbers from the first set results in a non-zero value, while numbers of the second set evaluate to zero.

I don’t have the mathematical background to substantiate it, but it feels reasonable to assume that it should be possible to write some kind of “brute force” expression, whatever the upper bound, where each case is evaluated separately, chained together by |, but is there a more efficient approach, either to simplify a “worst case” implementation or to build one up from nothing?

LEAVE A COMMENT