title: Algorithm for iterating over an outward spiral on a discrete 2D grid from the origin
body: <p>For example, here is the shape of intended spiral (and each step of the iteration)</p>
  
  <pre><code>          y
            |
            |
     16 15 14 13 12
     17  4  3  2 11
  -- 18  5  0  1 10 --- x
     19  6  7  8  9
     20 21 22 23 24
            |
            |
  </code></pre>
  
  <p>Where the lines are the x and y axes.</p>
  
  <p>Here would be the actual values the algorithm would "return" with each iteration (the coordinates of the points):</p>
  
  <pre><code>[0,0],
  [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1], [0,-1], [1,-1],
  [2,-1], [2,0], [2,1], [2,2], [1,2], [0,2], [-1,2], [-2,2], [-2,1], [-2,0]..
  </code></pre>
  
  <p>etc.</p>
  
  <p>I've tried searching, but I'm not exactly sure what to search for exactly, and what searches I've tried have come up with dead ends.</p>
  
  <p>I'm not even sure where to start, other than something messy and inelegant and ad-hoc, like creating/coding a new spiral for each layer.</p>
  
  <p>Can anyone help me get started?</p>
  
  <p>Also, is there a way that can easily switch between clockwise and counter-clockwise (the orientation), and which direction to "start" the spiral from? (the rotation)</p>
  
  <p>Also, is there a way to do this recursively?</p>
  
  <hr>
  
  <p><strong>My application</strong></p>
  
  <p>I have a sparse grid filled with data points, and I want to add a new data point to the grid, and have it be "as close as possible" to a given other point.</p>
  
  <p>To do that, I'll call <code>grid.find_closest_available_point_to(point)</code>, which will iterate over the spiral given above and return the first position that is empty and available.</p>
  
  <p>So first, it'll check <code>point+[0,0]</code> (just for completeness's sake).  Then it'll check <code>point+[1,0]</code>.  Then it'll check <code>point+[1,1]</code>.  Then <code>point+[0,1]</code>, etc.  And return the first one for which the position in the grid is empty (or not occupied already by a data point).</p>
  
  <p>There is no upper bound to grid size.</p>