How to get an element from a 2D array without looping the entire array?

问题: I have a simple class: public class XYPoint { public int x, y; } And a 2D array that contains arrays of Point objects: (-2, 2)(-1, 2)(0, 2)(1, 2)(2, 2) (-2,...

问题:

I have a simple class:

public class XYPoint {
    public int x, y;
}

And a 2D array that contains arrays of Point objects:

(-2,  2)(-1,  2)(0,  2)(1,  2)(2,  2)
(-2,  1)(-1,  1)(0,  1)(1,  1)(2,  1)
(-2,  0)(-1,  0)(0,  0)(1,  0)(2,  0)
(-2, -1)(-1, -1)(0, -1)(1, -1)(2, -1)
(-2, -2)(-1, -2)(0, -2)(1, -2)(2, -2)

The correspond ids are:

 0  1  2  3  4 
 5  6  7  8  9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24

Let's say I want to get the element at id 0, then it will return -2, 2. If I want to get from 6, it will return -1, 1 and so on.

Is there any way I can get an element without looping the entire array?


回答1:

you essentially imagine a 1d array, structured in a 2d manner. with that in mind you can map the 1d coordinate (in your case 7 for instance) onto 2d like this:

[1d/width][1d mod width]

1d being your "id" and width being the 2d array length

1d/width results in the corresponding "row" of your id, and 1d mod width in the corresponding "column"

  • 发表于 2019-02-20 17:37
  • 阅读 ( 196 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除