四个坐标点顺时针排序

主要思想就是先按照横坐标排个序,然后确定最左边的顶点为起点,分别跟其他顶点画一条之前,然后判断剩下的两个点是否在这条直线的两侧,如果在两侧,那么排好序的四个坐标点就是:
最左边的点,直线上侧的点,连线的点,跟直线下侧的点。
具体如下代码:

function ssort(points) {
  // points like [[1,2],[4,1],[5,-1],[10,3]]
  let path = points;
  path.sort((a, b) => a[0] - b[0]);

  for (let j = 1; j < 4; j++) {
    let a = (path[0][1] - path[j][1]) / (path[0][0] - path[j][0]);
    let b = path[0][1] - a * path[0][0];
    let p0, oppo, p1;
    if (j == 1) {
      oppo = path[1];
      p0 = path[2];
      p1 = path[3];
    } else if (j == 2) {
      p0 = path[1];
      oppo = path[2];
      p1 = path[3];
    } else if (j == 3) {
      p0 = path[1];
      p1 = path[2];
      oppo = path[3];
    }
    let c0 = a * p0[0] + b - p0[1];
    let c1 = a * p1[0] + b - p1[1];
    if (c0 * c1 < 0) {
      if (c0 > 0) {
        path = [path[0], p0, oppo, p1];
      } else {
        path = [path[0], p1, oppo, p0];
      }
      break;
    }
  }
  return path;
}

你可能感兴趣的:(其他,算法)