Hello,
I want to create an index that wraps around in a "*Ring*" type fashion. For instance,
{
int index = 0;
int[] array = new int[ 5 ];
index = 0;
index = (index - 1) % array.length;
// index is now equal to '-1' however, I want it to wrap around to array.length -1
index = 4;
index = (index + 1) % array.length;
// index is now equal to '0' and this is OK!
}
The statement "index = (index - 1) % array.length;" returns -1 when index == 0, however, I would like it to return 4; as it would in C Language. I know that Java modulus operator is different but is there an elegant way to do what I want to do? I was told to replace the statement with "index = ((index- 1) + array.length) % array.length;" this actually works but can the same result be achieved with fewer operations? I know that it is optimal compare to
index = (index - 1);
if (index < 0)
index = array.length - 1;
but it would be nice if I can do it with fewer operations. Actually, I would not even have a problem is Java had "*unsigned int*".
I am willing to entertain any ideas and if nothing else I did get an understanding of Java handles '/' and why '%' functions the way it does!
Thanks!