How can I increase and decrease an integer using the modulo operator

I am trying to increase the number based on click. How the click occurs does not matter, so I will adhere to the logic. I am doing this in Java, but the logic should be the same.

int index = 0;

// then within the click event
//arrySize holds the size() of an ArrayList which is 10

index = (index + 1) % arrySize;

With this logic, every time the user clicks, it indexwill increase by 1. Then it modulo arrySizecauses it indexto return to 0 when it indexmatchesarrySize

(10% 10 will force the index to return to 0). This is great because it looks like a loop that goes from 0 to 10, and then back to 0 and no more than 10.

I try to do the same logic, but back where, based on the click, the number will decrease and go down to 0, then it returns to arrySizeinstead-1

How can I achieve this logic?

+4
3
(index + arraySize - 1) % arraySize

, .

+4

Java 8, Math.floorMod(x, y). Javadoc ( ):

x - (floorDiv(x, y) * y), , y, -abs(y) < r < +abs(y).

System.out.println(Math.floorMod(-1, 5)); // prints 4

, :

index = Math.floorMod(index - 1, arrySize);

-1 % 5, -1 , % .

+2

index = arraySize - ((index + 1)% arrySize)

0

Source: https://habr.com/ru/post/1622380/


All Articles