Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java int[][] array - iterating and finding value

I have an array in the form of 'int[][]' that represents the co-ordinates of a small grid. Each co-ordinate has been assigned its own value. eg array[0][4] = 28......

I have two questions. Firstly, how do I iterate through all the stored values. Secondly, I want to be able to input a value and have its specific co-ordinates in the grid returned. What would be the best way to approach this?

Thank you for any help!

like image 249
Tray Avatar asked Jan 23 '09 20:01

Tray


2 Answers

You can iterate with either for loops or enhanced for loops:

for (int row=0; row < grid.length; row++)
{
    for (int col=0; col < grid[row].length; col++)
    {
        int value = grid[row][col];
        // Do stuff
    }
}

or

// Note the different use of "row" as a variable name! This
// is the *whole* row, not the row *number*.
for (int[] row : grid)
{
    for (int value : row)
    {
         // Do stuff
    }
}

The first version would be the easiest solution to the "find the co-ordinates" question - just check whether the value in the inner loop is correct.

like image 161
Jon Skeet Avatar answered Oct 09 '22 12:10

Jon Skeet


to iterate over the values use loops:

 int[][] matrix   
 //...
 for(int row[] : matrix)
     for(int cell : row){
      //do something with cell
    }

to access the coordinates based on the value you would need some sort of double hashmap (look a at java.util.HashMap) but i am aware of nothing that does so directly

like image 25
user54579 Avatar answered Oct 09 '22 10:10

user54579