离散的坐标点求最小凸包的算法JS版

参考 https://www.geeksforgeeks.org/convex-hull-set-1-jarviss-algorithm-or-wrapping/

以上只有C++和Java的版本,自己做了个JS的版本,仅供参考:

function convexHull (arr) {

 

const n = arr.length;

// There must be at least 3 points

 

if(n < 3) {

return;

}

 

const hull = [];

let l = 0;

 

for(let i = 0; i < n; i++) {

if(arr[i].x < arr[l].x) {

l = i;

}

}

 

let p = l,

q;

 

do{

hull.push(arr[p]);

q = (p + 1) % n;

 

for(let i = 0; i < n; i++) {

if(orientation(arr[p], arr[i], arr[q]) === 2) {

q = i;

}

}

 

p = q;

}while(p !== l);

 

return hull;

}

 

function orientation (p, q, r) {

const val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);

 

if(val === 0) {

return 0;

}

 

return (val > 0) ? 1 : 2;

}

 

你可能感兴趣的:(JS)