6

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.

Community
  • 1
  • 1
ricick
  • 5,694
  • 3
  • 25
  • 37

3 Answers3

8

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.

MBo
  • 77,366
  • 5
  • 53
  • 86
0

I want to throw in my function since it's a bit more concise than the last solution but more complex than the first. rather than have the indexes adjacent to each-other, my code opts for loops/layers where the first index of the next loop is always on the same axis.

like so:

23 24  9  10 11 +y
22  8  1  2  12
21  7  0  3  13
20  6  5  4  14
19 18 17 16  15 -y
-x           +x

it has set directions and uses the smaller vec2 value as the offset from these NSEW axes

func translate_vector2_to_spiral_index(vec2):
    #layer is the ring level the position is on
    var layer = max(abs(vec2.x),abs(vec2.y))
    if layer == 0: 
        return 0
    
    #the total interior positions before the edge
    var base_index = 0
    
    var i = 0
    while i < layer:
        base_index += 8 * i
        
        i+=1
    
    var current_layer_total = 8 * i
    #non_axis spaces at each corner (not directly any nesw axis)
    var non_axis_spaces = (current_layer_total - 4)/4
    
    
    #direct axes spaces on this layer
    var N = 1
    var E = N + non_axis_spaces + 1
    var S = E + non_axis_spaces + 1
    var W = S + non_axis_spaces + 1
    
    
    
    var spiral_index = base_index
    
    if abs(vec2.x) > abs(vec2.y):
        if vec2.x < 0:
            spiral_index+=W
            spiral_index += vec2.y
            
            
            
            
        elif vec2.x > 0:
            spiral_index+=E
            spiral_index -= vec2.y
            
            
        else:
            if vec2.y < 0:
                spiral_index+=S
            elif vec2.y > 0:
                spiral_index+=N
            #abs(y) must be equivalent to layers if x is 0
        
    else:
        if vec2.y < 0:
            spiral_index+=S
            spiral_index -= vec2.x
            
            
        elif vec2.y > 0:
            spiral_index
            var x = N
            x += vec2.x
            #if x goes into the negative on the iteration axis (N) it's a subtraction from the layer total
            if vec2.x < 0:
                x = current_layer_total + 1 + vec2.x
            
            spiral_index += x
            
        else:
            if vec2.x < 0:
                spiral_index+=W
            elif vec2.x > 0:
                spiral_index+=E
            #abs(x) must be equivalent to layers if y is 0
    
    return spiral_index

there's probably a way to shorten this but i thought to throw this out there.

DED
  • 391
  • 2
  • 12
0

I don't know if there is a concise mathematical equation to derive what you want, but I have a solution that computes what you want in O(1) time per query. No loops like you wanted.

My approach :

(i) For any given point (x,y), find the number of points which lie in the square of side length (2*a-1), where a = Max( |x|, |y| ). These are the interior points. i.e, the number of points lying in all spirals NOT including current spiral.

This is nothing but ( 2*a -1 )*( 2*a -1 )

Eg : Consider the following diagram :

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

For the point ( 2,1 ), a = 2. The interior points, here are labelled as 0, 1, 2, 3, 4, 5, 6, 7, 8 - The square with edge length 3

(ii) Now compute the points lying on the current spiral. The spiral has 4 "corner" points -

(a) The starting point ( where the current spiral starts )

(b) The point ( a, a )

(c) The point ( -a, a )

(d) The point ( -a, -a )

So, I compute the number of elements lying between each such pair [ i.e, between (a) and (b), (b) and (c), (c) and (d) ], such that all of these fall before the required input point in the spiral sequence. This can be done by simple subtraction of point co-ordinates.

This value, plus the number of interior points will give you the required answer.

I am not sure whether I have explained this very clearly. Do let me know if you require any clarifications or further explanation.

Attached is the JAVA code I wrote to test my logic. I am sorry but it is not very elegant, but it works :P

import java.io.IOException;
import java.util.Scanner;

class Pnt
{
    int x, y;

    public Pnt( int _x, int _y )
    {
        x = _x;
        y = _y;
    }
}

public class Spiral
{

    static int interior( Pnt p ) // returns points within interior square of side length MAX( x, y ) - 1
    {
        int a = Math.max( Math.abs( p.x ), Math.abs( p.y ));
        return ( 2*a - 1 )*( 2*a - 1 );
    }


    static Pnt startPnt( Pnt p ) // first point in that spiral
    {
        int a = Math.max( Math.abs( p.x ), Math.abs( p.y ));

        // last pnt in prev spiral = [ a-1, -( a-1 ) ]

        // next pnt  = [ a, -( a-1 ) ]

        return new Pnt( a, -( a-1 ));
    }

    static int offSetRow1( Pnt pStart, Pnt p )
    {

        return ( p.y - pStart.y ) + 1;
    }



    static int solve( Pnt curr )
    {
        // check location of curr
        // It may lie on 1st row, 2nd row, 3rd or 4th row

        int a = Math.max( Math.abs( curr.x ), Math.abs( curr.y ));
        int off=0;
        int interiorCnt = interior( curr );
        Pnt start = startPnt( curr );

        if( ( curr.x == a ) && ( curr.y >= start.y ) ) // row 1
        {
            off = offSetRow1( start, curr );
            return off+interiorCnt;
        }

         if( curr.y == a ) // row 2
        {
            Pnt start2 = new Pnt( a, a );
            int off1 = offSetRow1( start, start2 );

            // now add diff in x-coordinates

            int off2 = start2.x - curr.x;
            off = off1 + off2;
            return off+interiorCnt;

        }

        if( curr.x == -a ) // row 3
        {
            Pnt start2 = new Pnt( a, a );
            int off1 = offSetRow1( start, start2 );

            // now add diff in x-coordinates

            Pnt start3 = new Pnt( -a, a );
            int off2 = start2.x - start3.x;

            // now add diff in y co-ordinates


            int off3 = start3.y - curr.y;

            off = off1 + off2 + off3;
            return off+interiorCnt;

        }

        else // row 4
        {
             Pnt start2 = new Pnt( a, a );
            int off1 = offSetRow1( start, start2 );

            // now add diff in x-coordinates

            Pnt start3 = new Pnt( -a, a );
            int off2 = start2.x - start3.x;

            // now add diff in y co-ordinates


            int off3 = start3.y - curr.y;

            Pnt start4 = new Pnt( -a, -a );

            // add diff in x co-ordinates

            int off4 = curr.x - start4.x;
            off = off1 + off2 + off3 + off4;
            return interiorCnt + off;
        }


    }

    public static void main( String[] args ) throws IOException
    {
        Scanner s = new Scanner( System.in );

        while( true )
        {
            int x = s.nextInt();
            int y = s.nextInt();

            Pnt curr = new Pnt( x, y );
            System.out.println( solve( curr ));
        }
    }

}
arya
  • 565
  • 1
  • 6
  • 17