Last active
November 20, 2016 22:43
-
-
Save akhenakh/59fb3b227426ab6567dfa9aeb1e050f9 to your computer and use it in GitHub Desktop.
Convex Hull Monotone chain https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain (lat,lng)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The MIT License (MIT) | |
Copyright (c) 2016 Fabrice Aneche | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
*/ | |
type Points [][]float64 | |
func (points Points) Len() int { | |
return len(points) | |
} | |
func (points Points) Less(i, j int) bool { | |
if points[i][0] == points[j][0] { | |
return points[i][1] < points[j][1] | |
} | |
return points[i][0] < points[j][0] | |
} | |
func (points Points) Swap(i, j int) { | |
points[i], points[j] = points[j], points[i] | |
} | |
func cross(o, a, b []float64) float64 { | |
return (a[0]-o[0])*(b[1]-o[1]) - (a[1]-o[1])*(b[0]-o[0]) | |
} | |
func (pts Points) ConvexHull() Points { | |
if len(pts) <= 3 { | |
return pts | |
} | |
sort.Sort(pts) | |
var lower [][]float64 | |
for _, p := range pts { | |
for len(lower) >= 2 && cross(lower[len(lower)-2], lower[len(lower)-1], p) <= 0 { | |
lower = lower[:len(lower)-1] | |
} | |
lower = append(lower, p) | |
} | |
var upper [][]float64 | |
sort.Sort(sort.Reverse(pts)) | |
for _, p := range pts { | |
for len(upper) >= 2 && cross(upper[len(upper)-2], upper[len(upper)-1], p) <= 0 { | |
upper = upper[:len(upper)-1] | |
} | |
upper = append(upper, p) | |
} | |
l := append(lower[:len(lower)-1], upper[:len(upper)-1]...) | |
return l | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment