【问题标题】:Reading through an array 2d from center to corners从中心到角落读取二维数组
【发布时间】:2015-10-15 06:11:44
【问题描述】:

因此,对于我正在处理的这个 java 项目,我需要一个循环,该循环首先从中心读取 2d 数组,然后是 4 个相邻值,然后是角落,并一直这样做,直到它到达并完成最外层。我需要它来处理所有奇数大小的方形二维数组。我制作这张图片是为了阐明我的目标:http://gyazo.com/80ed4502cb16795d37b75a14ee57f565。我个人无法做到这一点。感谢您的时间!欢迎任何伪代码或java代码!

【问题讨论】:

    标签: 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);
        }
    
    }
    

    如果你想保证它在排序中选择左,右上,下,你可以稍微偏向中心。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      相关资源
      最近更新 更多