Coordinate Algorithm - Rotate around the center

强颜欢笑 提交于 2019-12-01 13:12:35

Here's the closed-form solution that doesn't rely on a loop... I'm not handy with Java, so it's in C#, but it uses basic operations.

static void SpiralCalc(int i) {
    i -= 2;
    // Origin coordinates
    int x = 100, y = 100;
    if (i >= 0) {
        int v = Convert.ToInt32(Math.Truncate(Math.Sqrt(i + .25) - .5));
        int spiralBaseIndex = v * (v + 1);
        int flipFlop = ((v & 1) << 1) - 1;
        int offset = flipFlop * ((v + 1) >> 1);
        x += offset; y += offset;
        int cornerIndex = spiralBaseIndex + (v + 1);
        if (i < cornerIndex) {
            x -= flipFlop * (i - spiralBaseIndex + 1);
        } else {
            x -= flipFlop * (v + 1);
            y -= flipFlop * (i - cornerIndex + 1);
        }
    }
    // x and y are now populated with coordinates
    Console.WriteLine(i + 2 + "\t" + x + "\t" + y);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!