当从集合中给出一个随机的整数时,快速获取整数0,1和2的方法

Tho*_*mas 5 c c++ bit-manipulation bitwise-operators

所以基本上

int num = rand(2); //random number from 0-2
int otherNum, otherOtherNum;
otherNum = implement this
otherOtherNum = implement this
Run Code Online (Sandbox Code Playgroud)

例如,如果num为2,则otherNum和otherOtherNum必须设置为0和1(或1和0).

你会如何实现这个?假设您不能使用分支或查找表.是的,我想要一点操纵解决方案.是的,我希望解决方案比使用模数运算符的解决方案更快(因为这实际上是一个划分).

我认为查找可能是最快但不确定的,我不喜欢那个解决方案.

Xia*_*Pei 8

otherNum = (num + 1) % 3
otherOtherNum = (num + 2) % 3
Run Code Online (Sandbox Code Playgroud)


D.S*_*ley 8

您也可以使用XOR和位掩码执行此操作.

#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;
}
Run Code Online (Sandbox Code Playgroud)

这将打印:

f(0) = 0 1 2
f(1) = 1 0 2
f(2) = 2 1 0
Run Code Online (Sandbox Code Playgroud)


nju*_*ffa 6

如果对查找表的限制意味着避免内存访问,则可以使用寄存器内查找表.寄存器内查找表只是一个编译时常量.

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;
Run Code Online (Sandbox Code Playgroud)