2D Spiral Outward Spiral

My question is very similar to these other questions:

Spiral cycle

Is there a formula on the two-dimensional grid that I can use for spiral coordinates using an external template?

However, what will you do if your grid / matrix is ​​irregular?

I am creating a game where there are certain “places” represented by a 2D grid. Each odd row has even less space / cell. When rendering, these lines are shifted by 1/2 place. I need an algorithm that displays the closest places to any input coordinate of the place i in descending order, for example (the blue cell is the initial coordinate, the translucent cells are out of the grid):

Visual presentation

The mesh of the seat is stored as a gear multidimensional array, so the previous visualization is a bit erroneous. From an “algorithmic” point of view, this actually looks more like this (again, the blue cell is the starting coordinate, the translucent cells are outside the bounds of the array):

Real performance

The result will be something like

[0,0][1,0][0,1][-1,1][-1,0][-1,-1][0,-1][1,-1][2,0][1,1]...
+4
source share
1 answer

It uses an iterative approach that breaks the spiral into 7 sublevels per spiral loop, one sub-layer to exit the previous spiral level and 6 sub-levels to track the hexagonal path around the boundary of the previous level:

static void spiralLoop(int startx, int starty, int levels)
{
    int level = 1, sublevel = 0, sublevelstep = 0;
    int x = startx, y = starty;
    while(level <= levels)
    {
        System.out.println("["+x+","+y+"]");

        switch(sublevel)
        {
            case 0:
                x++; // stepping up from previous (next innermost) loop
                break;
            case 1:
                x+=(y&1);y++; // up and right
                break;
            case 2:
                x-=(~y&1);y++; // up and left
                break;
            case 3:
                x--; // left
                break;
            case 4:
                x-=(~y&1);y--; // down and left
                break;
            case 5:
                x+=(y&1);y--; // down and right
                break;
            case 6:
                x++; // right
                break;
            default:
                break;
        }

        if(sublevel == 0) // (3)
            sublevel = 1;
        if(++sublevelstep >= level) // (1)
        {
            sublevelstep = 0;
            if(++sublevel > 6) // (2)
            {
                level++;
                sublevel = 0;
            }
        }
    }
}

(1) ( ) ( ). , , reset 0.

(2) (- > 6), , - reset 0.

(3) ( ) .

, , .

x, y x y. , , , .

, x , y . , x , y . . :

row 0:    0 1 2 3 4 5 6 7 8 9
row 1:     0 1 2 3 4 5 6 7 8
row 2:    0 1 2 3 4 5 6 7 8 9
row 3:     0 1 2 3 4 5 6 7 8
row 4:    0 1 2 3 4 5 6 7 8 9
row 5:     0 1 2 3 4 5 6 7 8
+2

Source: https://habr.com/ru/post/1650839/


All Articles