26……
25 10 11 12 13
24 9 2 3 14
23 8 1 4 15
22 7 6 5 16
21 20 19 18 17
问题描述:
如果有这么个矩正(无限大)。起点1坐标是(0,0),2是(0,1),3是(1,1),4是(1,0),5是(-1,-1)……
现给出a点坐标(x,y) 求a点数值?
JAVA算法如下:
public static long getPointNumber(int a, int b) {
if (a == b && a == 0) { //特别情况
return 1;
}
int CircleN = Math.max(Math.abs(a), Math.abs(b)); //坐标所在的是第几圈 0、1、2、3……
long start = 4 * CircleN * (CircleN - 1) + 2; //所在圈最小的那个数字,即左上角右边那个数字
//根据a b算出距离加到start上,即所求
if (b == CircleN && a != -CircleN) {
return start + a + CircleN - 1;
} else if (a == CircleN) {
return start + 3 * CircleN - b - 1;
} else if (b == -CircleN) {
return start + 5 * CircleN - a - 1;
} else {
return start + 7 * CircleN + b - 1;
}
}
另外附加反向问题代码,己知一个点的数值,求出这个点的坐标:
void getNumberPoint(long number) {
//在此不return了,打印出来吧
if (number <= 0) {
System.out.println("Error! Can't be Negative or ZERO!");
return;
} else if (number == 1) {
System.out.println(number + "'s position is : " + "(0,0)");
return;
}
long startCircleN = (long)Math.floor(Math.sqrt(number)); //取number平方根的整数部分
long CircleN = getRightCircleIndex(number, startCircleN); //求出number在第几圈
long start = getStartNumber(CircleN); //所在圈最小的那个数字,即左上角右边那个数字
long distance = number - start;
long sideLen = 2 * CircleN + 1; //一条边上有几个数字
String outPut = number + "'s position is : " + "(";
if (distance <= sideLen - 2) {
outPut += (-CircleN + 1 + distance) + "," + CircleN + ")";
} else if (distance <= 2 * sideLen - 3) {
outPut += CircleN + "," + (CircleN - (distance - (sideLen - 2))) + ")";
} else if (distance <= 3 * sideLen - 4) {
outPut += (CircleN - (distance - (2 * sideLen - 3))) + "," + -CircleN + ")";
} else {
outPut += -CircleN + "," + (-CircleN + (distance - (3 * sideLen - 4))) + ")";
}
System.out.println(outPut);
}
long getRightCircleIndex(long number, long N) {
if (number >= getStartNumber(N)) {
if (number < getStartNumber(N + 1)) {
return N;
}
return getRightCircleIndex(number, N + 1);
} else {
return getRightCircleIndex(number, N - 1);
}
}
long getStartNumber(long N) {
return 4 * N * (N - 1) + 2;
}