Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...