A quick way to get integers 0, 1 and 2 for a given random from a set

So basically

int num = rand(2); //random number from 0-2 int otherNum, otherOtherNum; otherNum = implement this otherOtherNum = implement this 

For example, if num is 2, otherNum and otherOtherNum should be set to 0 and 1 (or 1 and 0).

How would you implement this? Suppose you cannot use branching or lookup tables. Yes, I need to manipulate the solution a bit. Yes, I would like the solution to be faster than the solution using the module operator (since this is essential division).

I think that the search may be the fastest, but not sure, I do not like this solution.

+5
source share
5 answers

You can also do this with XOR and bit masking.

 #include <stdio.h> void f(unsigned val, unsigned ary[3]) { ary[0] = val; ary[1] = (ary[0] ^ 1) & 1; ary[2] = (ary[0] ^ 2) & 2; } int main() { unsigned ary[3] = {0}; f(0, ary); printf("f(0) = %d %d %d\n", ary[0], ary[1], ary[2]); f(1, ary); printf("f(1) = %d %d %d\n", ary[0], ary[1], ary[2]); f(2, ary); printf("f(2) = %d %d %d\n", ary[0], ary[1], ary[2]); return 0; } 

This will print:

 f(0) = 0 1 2 f(1) = 1 0 2 f(2) = 2 1 0 
+8
source
 otherNum = (num + 1) % 3 otherOtherNum = (num + 2) % 3 
+8
source

You can use a lookup table in a register if the restriction on lookup tables means that access to memory is denied. An in-register lookup-table is just a compile-time constant.

 const int tab = ((1 << 0) | (2 << 4) | (0 << 8) | (2 << 12) | (0 << 16) | (1 << 20)); int num = rand(2); //random number from 0-2 int otherNum, otherOtherNum; otherNum = (tab >> num*8) & 0xf; otherOtherNum = (tab >> (num*8+4)) & 0xf; 
+6
source

My 2 piss.

 int main() { std::srand(std::time(0)); int num = std::rand() % 3; //random number from 0-2 int otherNum = (0b001001 >> (num << 1)) & 0b11; int otherOtherNum = (0b010010 >> (num << 1)) & 0b11; std::cout << num << '\n'; std::cout << otherNum << '\n'; std::cout << otherOtherNum << '\n'; } 

NOTES:

 0b001001 = 9 0b010010 = 18 0b11 = 3 

This method basically uses a table stored in integer bits and offsets the corresponding bits to the desired variavle.

+3
source

Another option is to use an array for searching, this avoids any additions and modules, although I'm not sure about this faster:

 int lookup[3] = {1, 2, 0}; int num = rand(2); //random number from 0-2 int otherNum, otherOtherNum; otherNum = lookup[num]; otherOtherNum = lookup[otherNum] 
+1
source

All Articles