【问题标题】:Reading through an array 2d from center to corners从中心到角落读取二维数组
【发布时间】:2015-10-15 06:11:44
【问题描述】:
【问题讨论】:
标签:
java
arrays
loops
2d
center
【解决方案1】:
您可以在逻辑上重新定义网格,使中心为 0,0。
然后,根据与中心的距离对每个网格坐标进行排序。
这假设网格是奇数宽度。
例如:
class Point
{
int x;
int y;
}
Point gridCenter;
Comparator<Point> comparator = new Comparator<Point>()
{
@Override
public int compare(Point arg0, Point arg1)
{
int x = arg0.x - gridCenter.x;
int y = arg0.y - gridCenter.y;
int distance0 = x*x + y*y;
x = arg1.x - gridCenter.x;
y = arg1.y - gridCenter.y;
int distance1 = x*x + y*y;
return distance0 - distance1;
}
};
void test()
{
int width = 11;
int height = 13;
gridCenter = new Point();
gridCenter.x = width/2;
gridCenter.y = height/2;
List<Point> points = new ArrayList<>();
for(int x=0;x<width;x++)
{
for(int y=0;y<height;y++)
{
Point p = new Point();
p.x = x;
p.y = y;
points.add(p);
}
}
Collections.sort(points, comparator);
for(Point p : points)
{
System.out.println(p.x + "," + p.y);
}
}
如果你想保证它在排序中选择左,右上,下,你可以稍微偏向中心。