5

I am trying to increment an integer based on a click. How the click happens does not matter so I'll stick to the logic. I am doing this in Java but the logic should be the same all around.

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, index will increment by 1. Then its modulo of arrySize causes index to go back to 0 when index matches arrySize

(10 % 10 would make the index go back to 0) Which is great because it's kind of like a loop that goes from 0 to 10 then back to 0 and never over 10.

I am trying to do the same logic but backwards where based on the click the number will decrement and get to 0 then goes back to the arrySize instead of -1

How can I achieve this logic?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Lucas Santos
  • 1,359
  • 3
  • 24
  • 43

4 Answers4

6
(index + arraySize - 1) % arraySize

Does what you want.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
2

Starting with Java 8, you can use the Math.floorMod(x, y) method. Quoting its Javadoc (emphasis mine):

The floor modulus is x - (floorDiv(x, y) * y), has the same sign as the divisor y, and is in the range of -abs(y) < r < +abs(y).

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

So you will have:

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

You can't have directly -1 % 5 because that will output -1 based on how the operator % operates with negatives numbers.

Community
  • 1
  • 1
Tunaki
  • 132,869
  • 46
  • 340
  • 423
0

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

Toni Pujol
  • 13
  • 2
  • That doesn't quite work. That'll simply move you to the opposite side of the range from 0 to arraySize, then go down by 1. So, while it does work when index = 0, and it also happens to work when index = arraySize/2 (when arraySize is even), it doesn't work for any other values. I think the correct way of doing this with the % operator is just with (index+arraySize-1)%arraySize. And, in general, floor modding Math.floorMod(a,b) can be done with (a%b+b)%b, or with the probably less expensive 2 lines of code c = a%b; if(c<0) { c+=b; }. Also you misspelled arraySize the second time – Math Machine Nov 30 '22 at 23:12
0

Use this if you want 1-based indexing. For example if you wanted to step backwards through months where 1 is January.

int previous = ((index - 1 - arraySize) % arraySize) + arraySize

Results

index    previous
1        12
2        1
3        2
4        3
5        4
6        5
7        6
8        7
9        8
10        9
11        10
12        11

Example Fiddle

xr280xr
  • 12,621
  • 7
  • 81
  • 125