views:

109

answers:

3

hello I am working on a simple combinatorics part, and found that I need to recover position of two bits given position of other two bits in 4-bits srring.

for example, (0,1) maps to (2,3), (0,2) to (1,3), etc. for a total of six combinations.

My solution is to test bits using four nested ternary operators:

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.

I have to clarify, without using for loops, my target language is C++ meta-programming templates. I know I specified language explicitly, but it's still agnostic in my opinion

can you think of a better way/more clever way? thanks

+2  A: 

The problem space is rather small, so a LUT-based solution is fast and easy.

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)
Ignacio Vazquez-Abrams
right, I am interested though in some sort of bit / recursive approach
aaa
+3  A: 

Just xor the value with binary 1111 - this will flip the four bits, giving you the other two.

cd = ab ^ 0xF;
interjay
does not give positions
aaa
@aaahow you do you want the position?give us the function interface that you wish to see. What does the function return?
Pyrolistical
A: 

Python:

def unset_bits(input=0x5):
    for position in range(4):
        if not (2**position) & input:
            yield position

Yields:

>>> list( unset_bits(0x1) )
[1, 2, 3]

>>> list( unset_bits(0x2) )
[0, 2, 3]

>>> list( unset_bits(0x3) )
[2, 3]
Joe Koberg