我想在java中创建无穷无尽的螺旋:
我只是想从1-∞数字发送整数并得到它的螺旋图。例如:
getXZForMap(0); ----> (0; 0)
getXZForMap(5); ----> (-1; 0)
现在提出这个代码,但不知道如何进一步:
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;
}
答案 0 :(得分:2)
以算法方式思考。确定模式。
模式是你一次一个地走在圆周上。
(0,0)
。现在看模式:
所以,既然你看到了模式,你就可以这样做:
答案 1 :(得分:0)
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);
}
}
改编自这个答案:Algorithm for iterating over an outward spiral on a discrete 2D grid from the origin
演示:
$ java spiral 0
(0;0)
$ java spiral 5
(-1;0)