For a sequence of just two numbers (A and B) it's easy. The following code will toggle between them:For three or more, a simple option is to use a lookup table. That table can either be explicitly written out the long way, which is highly readable:
Code:
// 1, 0, -1, 0
const int table[] = {1, 0, -1, 0};
n = table[index];
index = (index+1) % (sizeof(table)/sizeof(table[0]));
or can be just packed into an int:
Code:
// 1, 0, -1, 0
n = (char)(0x00FF0001 >> (((index++)&3)*8));
Of course for a lot of common sequences, there are arithmetic ways that you are thinking of, such as:
Code:
// 0, 1, 1, 0
n = (index ^ (index>>1)) & 1;
++index;
Which yes I just wrote on the spot.
Generating code for such sequences can take a bit of clever thinking and/or some experience in doing so. But whenever that is too hard, just use the lookup table way of doing it.