Looping in a spiral

前端 未结 30 2678
独厮守ぢ
独厮守ぢ 2020-11-22 15:07

A friend was in need of an algorithm that would let him loop through the elements of an NxM matrix (N and M are odd). I came up with a solution, but I wanted to see if my fe

30条回答
  •  迷失自我
    2020-11-22 15:12

    Just for fun in Javascript:

    function spiral(x, y) {
      var iy = ix = 0
        , hr = (x - 1) / 2
        , vr = (y - 1) / 2
        , tt = x * y
        , matrix = []
        , step = 1
        , dx = 1
        , dy = 0;
    
      while(matrix.length < tt) {
    
        if((ix <= hr && ix >= (hr * -1)) && (iy <= vr && (iy >= (vr * -1)))) {
          console.log(ix, iy);
          matrix.push([ix, iy]);
        }
    
        ix += dx;
        iy += dy;
    
        // check direction
        if(dx !== 0) {
          // increase step
          if(ix === step && iy === (step * -1)) step++;
    
          // horizontal range reached
          if(ix === step || (ix === step * -1)) {
            dy = (ix === iy)? (dx * -1) : dx;
            dx = 0;  
          }
        } else {
          // vertical range reached
          if(iy === step || (iy === step * -1)) {
            dx = (ix === iy)? (dy * -1) : dy;
            dy = 0;
          }
        }
      }
    
      return matrix;
    }
    
    var sp = spiral(5, 3);
    

提交回复
热议问题