Generating a wanted number by bitwise OR

做~自己de王妃 提交于 2019-12-07 09:38:17

问题


Given N integer intervals [lo_i,hi_i].

From each interval chose a number such that bitwise OR of them become given number X.(It doesn't matter if the result has more 1 bits than X; i.e. if the generated number is Y, (X&Y)==X should hold)


回答1:


I guess this problem is NP complete, though I haven't found an NP hard problem easily reducible to this.

But for those sets that contain 2^(mostSignificantDigit) - 1, I would do as a heuristic: Firstly, try the number 1...1 (mostSignificantDigit-1 ones), secondly a number with the most significant bit and as many other bits as possible set. This heuristic is only bad in the case that you would have required a number from the set with the most significant bit set and a few different less significant bits.

With this heuristic, you can also pick amongst those sets the largest number 1....1 as a further heuristic.




回答2:


Let's generalize the problem a little. I'm going to write bitwise operators like OR and AND and SR (shift right).

Given a natural number X, intervals [lo_1, hi_1], ..., [lo_N, hi_N] consisting of natural numbers, and a bit b in {0, 1}, determine whether there exist natural numbers y_1 in [lo_1, hi_1], ..., y_N in [lo_N, hi_N] such that, letting Y = y_1 OR ... OR y_N, it holds that (X AND Y) = X and that there exists i such that x_i <= hi_i - b.

The base case for my recursive algorithm is when lo_1 = hi_1 = lo_2 = ... = hi_n = 0. There exists a solution if and only if X = 0 and b = 0.

Inductively, prepare a subproblem by letting X' = X SR 1 and lo_i' = lo_i SR 1 and hi_i' = hi_i SR 1. Let Odd(i) be true if and only if hi_i AND 1 = 1. Let Odd+(i) be true if and only if Odd(i) and lo_i < hi_i. If X AND 1 = 0:

If there exists i such that Odd+(i), then let b' = 0. Otherwise, let b' = b.

If X AND 1 = 1:

If there exist distinct i and j such that Odd+(i) and Odd(j), then let b' = 0. If there exists no j such that Odd(j), then let b' = 1. Otherwise, let b' = b.

Return the answer for the subproblem.



来源:https://stackoverflow.com/questions/9497845/generating-a-wanted-number-by-bitwise-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!