我想找出 x,y 整数是否满足螺旋正方形的点 (x,y)。(0,0) (0,1) (1,1) (1,2) (0,2) (-1,2) (-2,2) (-2,1) (-2,0)很快.....
我该怎么做?我想要 java 或 c++ 函数的逻辑。
这是一些伪代码逻辑:
Start with x=0, y=0, dist=0, direction=1
Loop
x += (++dist * direction)
WritePoint(x,y)
y += (++dist * direction)
WritePoint(x,y)
direction *= -1
LoopEnd
从那里拿走它。
执行此操作:
(operator)(operation)(amount)
其中运算符交替为 x,y,x,y,...(使用 % 运算符),操作交替为 +,+,-,-,+,+,-,-,+,+...(再次为此使用 % 运算符)并且数量更改为 1,2,3,...
这是我的回答。为了解决这个问题,我找到了你需要通过绘制它来改变方向的索引(最多〜i = 36),然后像在模式识别智商测试中一样找到公式。
const size = 100;
let x = 500; // 500 is center x
let y = 500; // 500 is center y
let d = 'right';
let n = 1;
for (let i = 0; i < 10; i++) {
// change the direction
if (i === Math.pow(n, 2) - n) {
d = 'right';
} else if (i === Math.pow(n, 2)) {
d = 'down';
} else if (i === Math.pow(n, 2) + n) {
d = 'left';
} else if (i === Math.pow(n, 2) + (n * 2 + 1)) {
d = 'up';
n += 2;
}
// get the current x and y.
if (d === 'right') {
x += size;
} else if (d === 'left') {
x -= size;
} else if (d === 'down') {
y += size;
} else {
y -= size;
}
}