将二维圆表示为一维数组(出租车几何、冯诺依曼邻域)

Represent a 2D circle as a 1D array (taxicab geometry, Von Neumann neighborhood)

在出租车几何(冯·诺依曼附近)中有一个半径和一个圆的面积,我想将所有 "fields"(图像上的 "o" 个字母)映射到一维数组索引和返回。

我想将基于 0 的一维数组索引转换为 x、y 坐标并返回(假定 0、0 为中心)。

   o  radius=0, area=1

   o
  ooo  radius=1, area=5
   o

   o
  ooo
 ooooo  radius=2, area=13
  ooo
   o

   o
  ooo
 ooooo
ooooooo  radius=3, area=25
 ooooo
  ooo
   o


x, y = taxicab.circlePositionFromIndex(index, radius)

index = taxicab.circleIndexFromPosition(x, y, radius)

到目前为止我完成的是这个函数,它通过在一个圆上迭代来计算 x、y 坐标:

var _DIRECTIONS = [1, -1, -1, -1, -1, 1, 1, 1];

function indexToPosition(index, radius) {
    var i = 0;

    for (var r = 0; r <= radius; r++) {
        var x = 0, y = r;
        var direction = 0;
        var segment = 0;

        do {
            if (i === index)
                return [x, y];

            segment += 1;
            x += _DIRECTIONS[direction];
            y += _DIRECTIONS[direction+1];
            i += 1;

            if (segment === radius) {
                direction += 2;
                segment = 0;
            }
        } while (x !== 0 || y !== r);
    }

    return -1;
};

这个函数对于任务来说似乎过于复杂,必须有更简单的方法。而且它只能以一种方式工作。

为了计算圆的面积,我使用了这个函数:

function area(radius) {
    return 1 + 2 * radius * (radius + 1);
}

如果编号是这样的:(否则可以映射到想要的坐标)

      0
   1  2  3
4  5  6  7  8   
   9 10 11
     12

               (0,0)
        (1,0)  (1,1)   (1,2)
 (2,0)  (2,1)  (2,2)   (2,3)  (2,4)
        (3,0)  (3,1)   (3,2)
               (4,0)

那么上三角的行数是

 row = Floor(Sqrt(index))

列是

 col = index - row * row

如果计算出的行大于半径,则进行镜像:

id = area - 1 - index
row_m  = Floor(Sqrt(id))
col_m = id - row_m * row_m

row = radius * 2 - row_m
col = row_m * 2 - col_m

quick check:
index = 6
row = 2
col = 6-4=2

index = 10
id = 2
row_m = 1
col_m = 1
row = 2*2-1 = 3
col = 2*1-1 = 1