Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java integer cyclic iteration shorthand

Tags:

java

iteration

When coding I find myself doing the following very often:

corner++; 
if(corner == 4) corner = 0;

Is there anyway do this in one line?

In this example corner should be 0, 1, 2, 3, 0, 1, 2, 3, 0....

like image 682
TheJohnMajor01 Avatar asked Jan 31 '16 13:01

TheJohnMajor01


Video Answer


5 Answers

You can use this short and kind of readable line (Demo):

corner = (corner + 1) % 4;

Or, even a tiny bit shorter (Demo):

corner = ++corner % 4;
like image 74
4 revs Avatar answered Oct 09 '22 11:10

4 revs


Use remainder. It's two lines but clean.

corner++;
corner %= 4;
like image 8
2 revs Avatar answered Oct 09 '22 13:10

2 revs


You can do this:

corner = ++corner == 4 ? 0 : corner;

This would give you the possibility to assign something else to the corner variable in case your corner == 4 test didn't pass.

like image 4
Mohammed Aouf Zouag Avatar answered Oct 09 '22 13:10

Mohammed Aouf Zouag


I use:

if (++corner == 4) corner = 0;
like image 3
Boann Avatar answered Oct 09 '22 13:10

Boann


It is not so obvious but much faster, since division generally executes slower than any bitwise operation.

corner = ++corner & 3;

EDIT: And surprisingly I discovered one more awesome way to make cycling - using shifts, and it runs even faster!

corner = ++corner << 30 >>> 30;

And this trick only works for any power of 2.

This benchmark shows all the results (though it's javascript, not java)

like image 1
Vasily Liaskovsky Avatar answered Oct 09 '22 12:10

Vasily Liaskovsky