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

前端 未结 12 1687
独厮守ぢ
独厮守ぢ 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:29

    This is the javascript solution based on the answer at Looping in a spiral

    var x = 0,
        y = 0,
        delta = [0, -1],
        // spiral width
        width = 6,
        // spiral height
        height = 6;
    
    
    for (i = Math.pow(Math.max(width, height), 2); i>0; i--) {
        if ((-width/2 < x && x <= width/2) 
                && (-height/2 < y && y <= height/2)) {
            console.debug('POINT', x, y);
        }
    
        if (x === y 
                || (x < 0 && x === -y) 
                || (x > 0 && x === 1-y)){
            // change direction
            delta = [-delta[1], delta[0]]            
        }
    
        x += delta[0];
        y += delta[1];        
    }
    

    fiddle: http://jsfiddle.net/N9gEC/18/

提交回复
热议问题