Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get spiral index from location

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.

like image 982
ricick Avatar asked Apr 02 '12 02:04

ricick


People also ask

How to find the coordinates of a matrix in Spiral order?

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.

How do you solve a spiral problem in MATLAB?

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.

What is the formula to find the value of a given index?

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).

What is the value of the index at the matching location?

The value of the index at the matching location must satisfy the equation abs (index [loc] - key) <= tolerance.


1 Answers

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.

like image 112
MBo Avatar answered Sep 28 '22 06:09

MBo