Looping in a spiral

前端 未结 30 2785
独厮守ぢ
独厮守ぢ 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:23

    Here is my solution (In Ruby)

    def spiral(xDim, yDim)
       sx = xDim / 2
       sy = yDim / 2
    
       cx = cy = 0
       direction = distance = 1
    
       yield(cx,cy)
       while(cx.abs <= sx || cy.abs <= sy)
          distance.times { cx += direction; yield(cx,cy) if(cx.abs <= sx && cy.abs <= sy); } 
          distance.times { cy += direction; yield(cx,cy) if(cx.abs <= sx && cy.abs <= sy); } 
          distance += 1
          direction *= -1
       end
    end
    
    spiral(5,3) { |x,y|
       print "(#{x},#{y}),"
    }
    

提交回复
热议问题