# Return to Revisions

3 of 5
added some mapstp
Vogel612
• 25.2k
• 7
• 56
• 140

The arithmetic solution to this is relatively simple.. we're talking modulo here:

the solution will be:

return i % N;


this should produce the same results for your adjusted index.

When I ran a few calculations on the modulo operator through wolfram-alpha, I got following results:

for $$\F(x) = x \mod 3\$$
$$\ 5 \mapsto 2 \$$
$$\ 4 \mapsto 1 \$$
$$\ 3 \mapsto 0 \$$
$$\ 2 \mapsto 2 \$$
$$\ 1 \mapsto 1 \$$
$$\ 0 \mapsto 0 \$$
$$\-1 \mapsto 2 \$$
$$\-2 \mapsto 1 \$$
$$\-3 \mapsto 0 \$$

the pattern we see here is exactly what you describe.

@Schism pointed out, that this behavior is only that of "mathematical modulo". It seems that some implementations are unfriendly in that concern. We can thus assume, we need to actually do the switching of negative numbers ourselves. this leads to following implementation:

if (i < 0) {
//assuming the behavior described by Schism (-1 % 3 = -1)
i = N + (i % N);
} else {
i = i % n;
}


Unfortunately this is still implementation dependent, so what we need to do now is: eliminate the sign in our modulo calculations to have the same behavior, regardless of implementation.

if (i < 0) {
wasNegative = true;
i = -i; //there's definitely a bithack for this. I just don't know it ;)
}
int offset = i % N
return (wasNegative) ? N - offset : offset;


so here's your mathematical solution ;)

Vogel612
• 25.2k
• 7
• 56
• 140