Skip to content

add the jarvis march in go #404

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 9, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions contents/jarvis_march/code/golang/jarvis.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package main

import (
"fmt"
)

type point struct {
x, y float64
}

func leftMostPoint(points []point) point {
ret := points[0]

for _, p := range points {
if (p.x < ret.x) || (p.x == ret.x && p.y < ret.y) {
ret = p
}
}

return ret
}

func (p point) equal(o point) bool {
return p.x == o.x && p.y == o.x
}

func counterClockWise(p1, p2, p3 point) bool {
return (p3.y-p1.y)*(p2.x-p1.x) >= (p2.y-p1.y)*(p3.x-p1.x)
}

func jarvisMarch(points []point) []point {
hullPoints := make([]point, 0)
hullPoint := leftMostPoint(points)
hullPoints = append(hullPoints, hullPoint)

for {
endPoint := points[0]

for _, p := range points[1:] {
if endPoint.equal(hullPoint) || !counterClockWise(p, hullPoints[len(hullPoints)-1], endPoint) {
endPoint = p
}
}

hullPoint = endPoint

if endPoint.equal(hullPoints[0]) {
break
}

hullPoints = append(hullPoints, hullPoint)
}
return hullPoints
}

func main() {
points := []point{{-5, 2}, {5, 7}, {-6, -12}, {-14, -14}, {9, 9},
{-1, -1}, {-10, 11}, {-6, 15}, {-6, -8}, {15, -9},
{7, -7}, {-2, -9}, {6, -5}, {0, 14}, {2, 8},
}

hullPoints := jarvisMarch(points)
fmt.Println("The hull points are:")

for _, p := range hullPoints {
fmt.Printf("x=%f y=%f\n", p.x, p.y)
}
}
2 changes: 2 additions & 0 deletions contents/jarvis_march/jarvis_march.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ Since this algorithm, there have been many other algorithms that have advanced t
[import, lang:"python"](code/python/jarvisMarch.py)
{% sample lang="cpp" %}
[import, lang:"c_cpp"](code/c++/jarvis_march.cpp)
{% sample lang="go" %}
[import, lang:"go"](code/golang/jarvis.go)
{% endmethod %}

<script>
Expand Down