Wezl算法最小的包围圆给出了错误的答案

时间:2018-06-08 13:56:28

标签: algorithm typescript

我在打字稿中实现了Welzl算法,每次都会给出不同的结果,并且圆圈并不总是包含所有点。

以下是代码:

solve(reports: Report[], reports1: Report[]) {
    let res = [];

    if (reports1.length === 3 || reports.length === 0) {
        res = this.calculateCircle(reports1);
    } else {
        const idx = Math.floor(Math.random() * reports.length);
        const rep = reports[idx];
        const newReports = reports;
        newReports.splice(idx, 1);
        res = this.solve(newReports, reports1);

        if (res.length === 0 || !this.isInCircle(rep, res)) {
            const newReports1 = reports1;
            newReports1.push(rep);
            res = this.solve(newReports, newReports1);
        }
    }
    return res;
}

isInCircle(rep: Report, circle: any) {
    return ((rep.xCoordinate * circle[0]) * (rep.xCoordinate * circle[0]) - (rep.yCoordinate * circle[1]) * (rep.yCoordinate * circle[1])
      < circle[2] * circle[2]);
  }

  calculateCircle(points: Report[]) {

    if (points.length < 3) {
        return [];
    }

    console.log(points);
    const p1x = points[0].xCoordinate;
    const p1y = points[0].yCoordinate;
    const p2x = points[1].xCoordinate;
    const p2y = points[1].yCoordinate;
    const p3x = points[2].xCoordinate;
    const p3y = points[2].yCoordinate;

    const a = p2x - p1x;
    const b = p2y - p1y;
    const c = p3x - p1x;
    const d = p3y - p1y;
    const e = a * (p2x + p1x) * 0.5 + b * (p2y + p1y) * 0.5;
    const f = c * (p3x + p1x) * 0.5 + d * (p3y + p1y) * 0.5;
    const det = a * d - b * c;

    const cx = (d * e - b * f) / det;
    const cy = (-c * e + a * f) / det;
    return [cx, cy, Math.sqrt((p1x - cx) * (p1x - cx) + (p1y - cy) * (p1y - cy))];
}

我似乎无法找到问题,请帮助!

0 个答案:

没有答案