[英]Create endless grid spiral in java
I want to create endless spiral in java like this:我想像这样在 java 中创建无尽的螺旋:
I simply want to pass a number from 1-∞ and get it's spiral map.我只是想传递一个 1-∞ 的数字并得到它的螺旋形 map。
Example:例子:
getPoints(0);
Would result in answer (0;0)将导致答案 (0;0)
getPoints(5);
Would result in answer (-1;0)将导致答案 (-1;0)
Think algorithmically.用算法思考。 Identify the pattern.
识别模式。
The pattern is that you walk the circumference, one layer at a time.模式是你走圆周,一次一层。
(0,0)
.(0,0)
。 Now see the pattern:现在看模式:
So, now that you see the pattern, you can do it like this:所以,现在你看到了模式,你可以这样做:
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改编自这个答案: Algorithm for iterate over an outpiration on a discret 2D grid from the origin
Demo:演示:
$ java spiral 0
(0;0)
$ java spiral 5
(-1;0)
public int[] getPoints(int n){ int[] k = new int[2]; if(n == 0){ k[0] = 0; k[1] = 0; return k; } n--; int r = (int) (Math.floor((Math.sqrt(n + 1) -1) / 2) + 1); int p = (8 * r * (r - 1)) / 2; int a = (1 + n - p) % (r * 8); switch ((int) Math.floor(a / (r * 2))) { case 0: k[0] = a - r; k[1] = -r; return k; case 1: k[0] = r; k[1] = (a % (r * 2)) - r; return k; case 2: k[0] = r - (a % (r * 2)); k[1] = r; return k; case 3: k[0] = -r; k[1] = r - (a % (r * 2)); return k; } return null; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.