I'm using Alberto Santini's solution to this question to get a spiral grid reference based on an items index
Algorithm for iterating over an outward spiral on a discrete 2D grid from the origin
It's not the accepted solution, but it's the best for my needs as it avoids using a loop.
It's working well, but what I want now is to do the inverse. Based on a known x and y coordinate return the index of a location.
This is as a precursor to returning the items surrounding a given location.
Given the order of the matrix N and M, and a source location ( X, Y ), the task is to find all the coordinates of the matrix in order when visited in clockwise spiral order ( (i.e. East-> South-> West-> North). Whenever moved outside the matrix, continue the walk outside it to return to the matrix later.
Approach: The given problem can be solved by traversing the matrix from the position (X, Y) in a clockwise spiral direction, and whenever reached outside the matrix, don’t include the coordinates in the solution but continue traversing outside to reach again inside the matrix.
So the formula will be i2 – (j-1). In this case, the first number of row i will be (i – 1)2 + 1. Now by adding (j – 1) to the first number of the row calculate the value present at the given index. So the formula will be (i – 1)2 + 1 + (j – 1).
The value of the index at the matching location must satisfy the equation abs (index [loc] - key) <= tolerance.
Pascal code:
if y * y >= x * x then begin
p := 4 * y * y - y - x;
if y < x then
p := p - 2 * (y - x)
end
else begin
p := 4 * x * x - y - x;
if y < x then
p := p + 2 *(y - x)
end;
Description: Left-upper semi-diagonal (0-4-16-36-64) contains squared layer number (4 * layer^2). External if-statement defines layer and finds (pre-)result for position in corresponding row or column of left-upper semi-plane, and internal if-statement corrects result for mirror position.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With