【发布时间】:2020-12-13 23:39:02
【问题描述】:
我编写了一个算法,可以在一个巨大的对象数组结构中找到一个六边形的每一行。
数组包含大约 80.000 - 100.000 个元素(从开始到结束的线坐标)。
六边形由 6 个线点组成。所以这个数组有大约 15000 个六边形的信息。
对象的结构(未排序!!!)如下所示:
const stamps = [
{
vertices: [
{x: 114.5116411118, y: 342.9815785601},
{x: 115.6663416502, y: 344.9815785601}
]
},
{
vertices: [
{x: 115.6663416502, y: 340.9815785601},
{x: 114.5116411118, y: 342.9815785601}
]
},
{
vertices: [
{x: 122.6663416502, y: 364.9815785601},
{x: 147.9757427269, y: 314.9815785601},
]
},
{
vertices: [
{x: 117.9757427269, y: 340.9815785601},
{x: 115.6663416502, y: 340.9815785601},
]
},
{
vertices: [
{x: 119.1304432653, y: 342.9815785601},
{x: 117.9757427269, y: 340.9815785601},
]
},
{
vertices: [
{x: 117.9757427269, y: 344.9815785601},
{x: 119.1304432653, y: 342.9815785601},
]
},
{
vertices: [
{x: 115.6663416502, y: 344.9815785601},
{x: 117.9757427269, y: 344.9815785601},
]
},
];
要找到每条线六边形,我的想法是必须有 2 个元素具有相同的坐标。如果是这种情况,我将跳转到该元素的索引并重复该过程,直到我拥有六边形的所有 6 行。
它是这样工作的,但它真的非常慢。对于包含 80.000 个元素的数组,大约需要 3 分钟。
算法:
function findHexPolyPoints() {
const hexCoordinates = [];
let activeArrayPos = 0;
let position = 0;
while (1) {
let foundPair = false;
if (stamps.length < 6) break;
for (let k = 0; k < stamps.length; ++k) {
if (k === position) continue;
if (stamps[position].vertices[0].x === stamps[k].vertices[1].x && stamps[position].vertices[0].y === stamps[k].vertices[1].y) {
if (hexCoordinates[activeArrayPos]) {
hexCoordinates[activeArrayPos].push(stamps[k].vertices[0].x, stamps[k].vertices[0].y);
} else {
hexCoordinates.push([stamps[position].vertices[0].x, stamps[position].vertices[0].y, stamps[k].vertices[0].x, stamps[k].vertices[0].y]);
}
foundPair = true;
} else if (stamps[position].vertices[1].x === stamps[k].vertices[0].x && stamps[position].vertices[1].y === stamps[k].vertices[0].y) {
if (hexCoordinates[activeArrayPos]) {
hexCoordinates[activeArrayPos].push(stamps[k].vertices[1].x, stamps[k].vertices[1].y);
} else {
hexCoordinates.push([stamps[position].vertices[1].x, stamps[position].vertices[1].y, stamps[k].vertices[1].x, stamps[k].vertices[1].y]);
}
foundPair = true;
}
if (foundPair) {
stamps.splice(position, 1);
if (k > position) {
position = k - 1;
} else {
position = k;
}
if (hexCoordinates[activeArrayPos].length < 12) break;
}
if (hexCoordinates[activeArrayPos] && hexCoordinates[activeArrayPos].length === 12) {
if (k > position) stamps.splice(k - 1, 1);
else stamps.splice(k, 1);
activeArrayPos += 1;
position = 0;
break;
}
if (k === stamps.length - 1) {
stamps.splice(position, 1);
break;
}
}
}
sortHexagons(hexCoordinates);
}
有什么方法可以加快我的算法?我读过一个简单的 for 循环仍然比一些 js 排序函数(如 .map .filter 或类似函数)更快。
【问题讨论】:
-
那么什么查询包含-line?协调?答案应该是什么?
-
sortHexagons 是做什么的?另外,所有的六边形都有相同的顶点坐标吗?
-
@WillJenkins 这几乎无关紧要。之后我只是对数组进行排序。
-
当我向下滚动时,哇,我不想阅读你的代码。圈复杂度非常高
-
再次...六边形是否具有相同的顶点坐标,如果不是,有多少个不同的集合?
标签: javascript algorithm performance for-loop