给定:2个数组,每个数组包含4个点的坐标:
point_array_a = [point_a_1_x, point_a_1_y, point_a_2_x, ..., point_a_4_y]
point_array_b = [point_b_1_x, ... ..., point_b_4_y]
任务:
对point_array_a进行排序,以便最终按以下顺序列出各点:
point_array_a_sorted = [top-left_x, top_left_y, top-right_x, top-right_y, bottom-right_x, bottom_right_y, bottom-left_x, bottom_left_y]
以相同的方式对point_array_b进行排序,使得point_a_k_l对应于开头的point_b_k_l。
答案 0 :(得分:1)
我担心没有简单的算法。但是下面的片段将完成这项工作(假设y坐标较大的点低于y坐标较低的点):
var i, points = [], leftX = point_array_a[0], topY = point_array_a[1];
for (i = 0; i < 4; i++)
{
leftX = Math.min(leftX, point_array_a[i * 2]);
topY = Math.min(topY, point_array_b[i * 2]);
points.push([
[point_array_a[i * 2], point_array_a[i * 2 + 1]],
[point_array_b[i * 2], point_array_b[i * 2 + 1]]
]);
}
points.sort(function(first, second){
if (first[0][0] == leftX)
return first[0][1] == topY ? -1 : 1;
if (second[0][0] == leftX)
return second[0][1] == topY ? 1 : -1;
return first[0][1] < second[0][1] ? -1 : 1;
});
var point_array_a_sorted = [], point_array_b_sorted = [];
for (i = 0; i < 4; i++)
{
point_array_a_sorted.push(points[i][0][0], points[i][0][1]);
point_array_b_sorted.push(points[i][1][0], points[i][1][1]);
}
我们利用现有的Array.sort
函数,只提供正确的对象来比较和交换点对。