首页 > 解决方案 > 将 2D 圆表示为 1D 数组(出租车几何,冯诺依曼邻域)

问题描述

在出租车几何(冯诺依曼邻域)中有一个半径和一个圆的面积,我想将所有“字段”(图像上的“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);
}

标签: javascriptarraysgeometrygraph-algorithm

解决方案


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

      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

推荐阅读