Question

I have an array and I want to scroll the positions in it backward.

I have a boolean array and I need to count how many true are there from a given cell going forward and backward.

I know that if N is the number of elements into the array, I can go ahead doing i=(i+1)%N. But what if I need to scroll it in the opposite way?

Thank you in advance.

Was it helpful?

Solution 3

This should do it:

i--;
if (i == -1)
  i = N-1;

Or in 1 line:

i = ((i-1 == -1) ? N-1 : i-1);

But noise's variation of the above is probably better. A related if-statement version:

if (i == 0)
  i = N-1;
else
  i--;

A related 1-line version:

i = (i == 0 ? N-1 : i-1)

OTHER TIPS

I usually use i = (i - 1 + N) % N to prevent negative values.

int newRightShiftIndex = (curIndex + numOfPositions)%size;
int newLeftShiftIndex = (curIndex +(size-(numOfPositions%size)))%size;
  • curIndex - is your curent index
  • numOfPositions - number of positions you want to shift backwards or clockwise
  • size - length, size of array

How about i = (i == 0 ? N : i) - 1?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top