Algorithm for iterating over an outward spiral on a discrete 2D grid from the origin

前端 未结 12 1703
独厮守ぢ
独厮守ぢ 2020-12-05 06:54

For example, here is the shape of intended spiral (and each step of the iteration)

          y
          |
          |
   16 15 14 13 12
   17  4  3  2 11
--         


        
12条回答
  •  心在旅途
    2020-12-05 07:17

    I had a similar problem, but I didn't want to loop over the entire spiral each time to find the next new coordinate. The requirement is that you know your last coordinate.

    Here is what I came up with with a lot of reading up on the other solutions:

    function getNextCoord(coord) {
    
        // required info
        var x     = coord.x,
            y     = coord.y,
            level = Math.max(Math.abs(x), Math.abs(y));
            delta = {x:0, y:0};
    
        // calculate current direction (start up)
        if (-x === level)
            delta.y = 1;    // going up
        else if (y === level)
            delta.x = 1;    // going right
        else if (x === level)        
            delta.y = -1;    // going down
        else if (-y === level)
            delta.x = -1;    // going left
    
        // check if we need to turn down or left
        if (x > 0 && (x === y || x === -y)) {
            // change direction (clockwise)
            delta = {x: delta.y, 
                     y: -delta.x};
        }
    
        // move to next coordinate
        x += delta.x;
        y += delta.y;
    
        return {x: x,
                y: y};
    }
    
    coord = {x: 0, y: 0}
    for (i = 0; i < 40; i++) {
        console.log('['+ coord.x +', ' + coord.y + ']');
        coord = getNextCoord(coord);  
    
    }
    

    Still not sure if it is the most elegant solution. Perhaps some elegant maths could remove some of the if statements. Some limitations would be needing some modification to change spiral direction, doesn't take into account non-square spirals and can't spiral around a fixed coordinate.

提交回复
热议问题