Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Most likely not the most efficient way of solving this, but I wanted to play with it:</p> <p>You could iterate over all the points in your grid, calculate their distances to the center point and then sort the points by this distance. The advantage over the algorithmic solutions is that you can use all sorts of distance functions:</p> <pre><code>// Setup constants var arraySize = 11; var centerPoint = {x:5, y:5}; // Calculate the Euclidean Distance between two points function distance(point1, point2) { return Math.sqrt(Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2)); } // Create array containing points with distance values var pointsWithDistances = []; for (var i=0; i&lt;arraySize; i++) { for (var j=0; j&lt;arraySize; j++) { var point = {x:i, y:j}; point.distance = distance(centerPoint, point); pointsWithDistances.push(point); } } // Sort points by distance value pointsWithDistances.sort(function(point1, point2) { return point1.distance == point2.distance ? 0 : point1.distance &lt; point2.distance ? -1 : 1; }); </code></pre> <p>The resulting <code>pointsWithDistances</code> array will look like this:</p> <pre><code>[ {x:5, y:5, distance:0}, {x:4, y:5, distance:1}, {x:5, y:4, distance:1}, ... {x:4, y:4, distance:1.4142135623730951}, {x:4, y:6, distance:1.4142135623730951}, ... {x:3, y:5, distance:2}, ... ] </code></pre> <p>By iterating over the array in this order you are effectively filling the grid from the center outwards.</p> <p><img src="https://i.stack.imgur.com/QnQgf.png" alt="Using Euclidean Distances"></p> <p>(Thanks for Andreas Carlbom's idea how to display this structure.)</p> <p>Check out the difference to using Rectilinear Distances:</p> <pre><code>// Rectilinear Distance between two points function distance(point1, point2) { return Math.abs(point1.x - point2.x) + Math.abs(point1.y - point2.y); } </code></pre> <p><img src="https://i.stack.imgur.com/6sO6n.png" alt="Using Rectilinear Distances"></p> <p>For the shell-like structure of the algorithmic approaches you can use the Maximum Metric:</p> <pre><code>// 'Maximum Metric' Distance between two points function distance(point1, point2) { return Math.max(Math.abs(point1.x - point2.x), Math.abs(point1.y - point2.y)); } </code></pre> <p><img src="https://i.stack.imgur.com/iQHGp.png" alt="Using &#39;Maximum Metric&#39; distances"></p> <p>You can play with the code here: <a href="http://jsfiddle.net/green/B3cF8/" rel="nofollow noreferrer">http://jsfiddle.net/green/B3cF8/</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload