c++ - fast way to get integers 0, 1, and 2 when given a random one from the set -
so basically
int num = rand(2); //random number 0-2 int othernum, otherothernum; othernum = implement otherothernum = implement
for example, if num 2, othernum , otherothernum must set 0 , 1 (or 1 , 0).
how implement this? assume can't use branching or tables. yes i'd bit manipulation solution. yes i'd solution faster solution uses modulus operator (as essentialy division).
i think lookup might fastest not sure, dont solution though.
you can xor , 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 print:
f(0) = 0 1 2 f(1) = 1 0 2 f(2) = 2 1 0
Comments
Post a Comment