-2

Please I have seen a lot of answers but I haven't seen the easiest solution to move around an array.

I want to continue moving to the next or previous element in the array (rows and column). Meaning if I reached the end of any rows or column, it takes me to the next or previous one, relative to the intialized size of the array.

Assuming I have a group of buttons to handle my directional events( left, right, up & down).

I have :

int twoD[][]= new int[3][3];

Output

0   1   2
3   4   5
6   7   8

I want to move right from

0,1,2,3,4,5,6,7,8 (Continuously)

I want to move left from

0,8,7,6,5,4,3,2,1 (Continuously)

I want to move up

0,8,5,2,7,4,1,6,3 (Continuously)

I want to move down

0,3,6,1,4,7,2,5,8,0 (Continuously)

ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
  • 2
    Your question is unclear. Typically, to iterate through a 2D array, you would use nested for-loops. – Mage Xy Dec 08 '15 at 14:42

1 Answers1

0

You should have current indices for the outer and the inner array and the length of the arrays

int innerIndex = 0;
int outerIndex = 0;
int innerMax = 3;
int outerMax = 3;

If the right button is pressed you'll have to increase the inner index. If the inner index reaches innerMax you'll increase outerIndex and set innerIndex to 0. (Best will be private methods for that)

private void increaseInner() {
    innerIndex++;
    if (innerIndex == innerMax) {
        innerIndex = 0;
        outerIndex++;
        if (outIndex == outerMax)
            outerIndex = 0;
    }
}

equivalent goes the decrase inner index: (left button pressed)

private void increaseInner() {
    innerIndex--;
    if (innerIndex < 0) {
        innerIndex = innerMax;
        outerIndex--;
        if (outIndex < 0)
            outerIndex = outerMax;
    }
}

The 2 methods for up button pressed and down button pressed are created similary to these methods.

ParkerHalo
  • 4,341
  • 9
  • 29
  • 51