在java中创建无止境的网格螺旋
我想在java中创建这样的无止境螺旋: 我只想发送1的整数-∞ 编号并得到它的螺旋图。例如: getXZForMap(0);--->(0;0) getXZForMap(5);--->(-1;0) 我现在想到了这个代码,但不知道如何进一步:在java中创建无止境的网格螺旋,java,Java,我想在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)
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轮中,您位于中心点
(0,0)
- 在第1轮中,你绕着它走8个单元格
- 在第二轮中,你绕着16个单元格走
- 在第三轮中,你绕着它走24个单元格
- 在每一轮中,每边的行走多走2步,每轮总共多走8步
- 每轮从左上角右侧的1个单元格开始
- 每侧行走从角落开始一个单元
- 计算你在哪一轮
- 对于那一轮,计算你站在哪一边
- 然后计算一下你在那一边走了多少步
- 最后,从中计算坐标
public int[]getXZForMap(int index){int x=0,y=0,dist=0,direction=1;for(int i=0;true;i++{if((distance+1)*direction>index){x+=(((++dist index)*direction));break;}else{x+=(++dist*方向);if((distance+1)*direction>index){y++=((++dist index)*direction));break;}else{y++=(++dist*方向);direction*=-1;}}}}}int[]k=new int[2];k[0]=x;k[1]=y;返回k;}
在注释中不显示代码。如果您已经有代码:1)为什么不在问题中显示它。2) 你的问题是什么,即你在寻找什么答案?@TerZer Cool。你想到了什么?把它贴在你的问题上,然后你会得到你喜欢的答案。你在写问题上投入的精力越多,我们在回答问题上投入的精力就越多。@Andreas这段代码并不能满足我的要求。我只想发送1的整数-∞ 编号并得到它的螺旋图。示例:getXZForMap(0);--->(0;0)getXZForMap(5);--->(-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);
}
}
$ java spiral 0
(0;0)
$ java spiral 5
(-1;0)