Algorithm 给定一组四位中的两位,找出另外两位的位置
我正在研究一个简单的组合数学部分,发现我需要恢复两个位的位置,给定其他两个位在4位srring中的位置 例如,(0,1)映射到(2,3),(0,2)映射到(1,3)等,总共有六种组合 我的解决方案是使用四个嵌套的三值运算符测试位:Algorithm 给定一组四位中的两位,找出另外两位的位置,algorithm,language-agnostic,bits,Algorithm,Language Agnostic,Bits,我正在研究一个简单的组合数学部分,发现我需要恢复两个位的位置,给定其他两个位在4位srring中的位置 例如,(0,1)映射到(2,3),(0,2)映射到(1,3)等,总共有六种组合 我的解决方案是使用四个嵌套的三值运算符测试位: ab is a four bit string, with two bits set. c = ((((ab & 1) ? (((ab & 2) ? ... ))) : 0) abc = ab | c recover the last bit in t
ab is a four bit string, with two bits set.
c = ((((ab & 1) ? (((ab & 2) ? ... ))) : 0)
abc = ab | c
recover the last bit in the same fashion from abc.
我必须澄清,不使用循环,我的目标语言是C++元编程模板。我知道我明确指定了语言,但在我看来它仍然是不可知论的
你能想出一个更好的方法/更聪明的方法吗?
谢谢问题空间非常小,因此基于LUT的解决方案既快速又简单 Python:
fourbitmap = {
3: (2, 3),
5: (1, 3),
6: (0, 3),
9: (1, 2),
10: (0, 2),
12: (0, 1),
}
def getother2(n):
return fourbitmap.get(n, None)
def unset_bits(input=0x5):
for position in range(4):
if not (2**position) & input:
yield position
问题空间相当小,因此基于LUT的解决方案既快速又简单 Python:
fourbitmap = {
3: (2, 3),
5: (1, 3),
6: (0, 3),
9: (1, 2),
10: (0, 2),
12: (0, 1),
}
def getother2(n):
return fourbitmap.get(n, None)
def unset_bits(input=0x5):
for position in range(4):
if not (2**position) & input:
yield position
只需将值与二进制1111进行异或运算-这将翻转四位,得到另外两位
cd = ab ^ 0xF;
只需将值与二进制1111进行异或运算-这将翻转四位,得到另外两位
cd = ab ^ 0xF;
Python:
fourbitmap = {
3: (2, 3),
5: (1, 3),
6: (0, 3),
9: (1, 2),
10: (0, 2),
12: (0, 1),
}
def getother2(n):
return fourbitmap.get(n, None)
def unset_bits(input=0x5):
for position in range(4):
if not (2**position) & input:
yield position
收益率:
>>> list( unset_bits(0x1) )
[1, 2, 3]
>>> list( unset_bits(0x2) )
[0, 2, 3]
>>> list( unset_bits(0x3) )
[2, 3]
Python:
fourbitmap = {
3: (2, 3),
5: (1, 3),
6: (0, 3),
9: (1, 2),
10: (0, 2),
12: (0, 1),
}
def getother2(n):
return fourbitmap.get(n, None)
def unset_bits(input=0x5):
for position in range(4):
if not (2**position) & input:
yield position
收益率:
>>> list( unset_bits(0x1) )
[1, 2, 3]
>>> list( unset_bits(0x2) )
[0, 2, 3]
>>> list( unset_bits(0x3) )
[2, 3]
对,我对某种位/递归方法感兴趣对,我对某种位/递归方法感兴趣approach@aaa你希望这个职位怎么样?给我们您希望看到的功能界面。函数返回什么?@aaa您希望该位置如何?给我们您希望看到的功能界面。函数返回什么?