TerZer TerZer - 3 years ago 98
Java Question

Create endless grid spiral in java

I want to create endless spiral in java like this:

Endless spiral

I simply want to send integer from 1-∞ number and get it's spiral map. Example:

getXZForMap(0); ----> (0;0)

getXZForMap(5); ----> (-1;0)

Came up with this code now, but do not know how to go further:

public int[] getXZForMap(int i){

int[] k = new int[2];

if(i > 0){

double s = i/8;
int stage = (int) Math.ceil(s);
int corner_size = ((stage*8)+4)/4;



}
else{
k[0] = 0;
k[1] = 0;
}

return k;
}

Answer Source
import java.util.Scanner;

class spiral 
{
    private static String getXZForMap(int np)
    {         
        // (dx, dy) is a vector - direction in which we move right now
        int dx = 0;
        int dy = 1;
        // length of current segment
        int segment_length = 1;

        // current position (x, y) and how much of current segment we passed
        int x = 0;
        int y = 0;
        int segment_passed = 0;
        if (np == 0){
            return ("(" + y + ";" + x + ")");
        }
        for (int n = 0; n < np; ++n) {
            // make a step, add 'direction' vector (dx, dy) to current position (x, y)
            x += dx;
            y += dy;
            ++segment_passed;

            if (segment_passed == segment_length) {
                // done with current segment
                segment_passed = 0;

                // 'rotate' directions
                int buffer = dy;
                dy = -dx;
                dx = buffer;

                // increase segment length if necessary
                if (dx == 0) {
                    ++segment_length;
                }
            }
        }
        return("(" + y + ";" + x + ")");
    }

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);
        int NUMBER_OF_POINTS = Integer.valueOf(args[0]);   // or delete this line  
        String spiral_map = getXZForMap(NUMBER_OF_POINTS); // and put your int here
        System.out.println(spiral_map);
    } 
}

Adapted from this answer: Algorithm for iterating over an outward spiral on a discrete 2D grid from the origin

Demo:

$ java spiral 0
(0;0)
$ java spiral 5
(-1;0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download