javascript - 将 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);
}
解决方案
如果编号是这样的:(否则它可以映射到所需的坐标)
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
推荐阅读
- django - 从 django 中的 auth_group_permissions 表创建外键
- python - 替换元素的堆解决方案是否比弹出然后推送的更有效?
- python - 如何找到与二维中的一组点匹配的“四边形”网格?
- ruby-on-rails - 我想通过键创建一个组哈希并添加值
- angular - 我正在尝试编写将检查浏览器本地存储的代码,并查看是否有密钥或带有用户密钥的对象
- json - 为什么 VBA-JSON 解析错误?无法到达正确的节点
- c# - 如何知道该用户在 Windows 上截屏?
- javascript - 为什么使用 AJAX 表单方法时文件上传在 formsubmit.co 中不起作用?
- c# - 找不到路径“C:\inetpub\AspNetCoreWebApps\app\EmailTemplates\example.cshtml”的一部分
- python - 使用 MyPy 对 Python 进行类型检查会破坏测试覆盖率报告