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

2019-02-07 02:16发布

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!

7条回答
唯我独甜
2楼-- · 2019-02-07 03:21

Unless your grid is sorted in some way then you probably won't do any better than a brute force search.

For iterating, I think it would be something like this (syntax might be off a bit, I haven't dealt with arrays in java for a while.):

int[][] grid;  // just assuming this is already assigned somewhere

for(int x = 0 ; x < grid.length ; x++) {
  int[] row = grid[x];
  for(int y = 0 ; y < row.length ; y++) {
    int value = row[y];
    // Here you have the value for grid[x][y] and can do what you need to with it
  }
}

For searching you'd probably need to use that to iterate, then return once you've found it.

If you might be looking up the position of the same value multiple times then you might want to memoize the results using a hashtable.

查看更多
登录 后发表回答