|
| 1 | +struct Point { |
| 2 | + x int |
| 3 | + y int |
| 4 | +} |
| 5 | + |
| 6 | +fn left_most_point(points []Point) Point { |
| 7 | + mut ret := points[0] |
| 8 | + |
| 9 | + for p in points { |
| 10 | + if (p.x < ret.x) || (p.x == ret.x && p.y < ret.y) { |
| 11 | + ret = p |
| 12 | + } |
| 13 | + } |
| 14 | + |
| 15 | + return ret |
| 16 | +} |
| 17 | + |
| 18 | +fn (p Point) equal(o Point) bool { |
| 19 | + return p.x == o.x && p.y == o.x |
| 20 | +} |
| 21 | + |
| 22 | +fn counter_clock_wise(p1, p2, p3 Point) bool { |
| 23 | + return (p3.y-p1.y) * (p2.x-p1.x) >= (p2.y-p1.y) * (p3.x-p1.x) |
| 24 | +} |
| 25 | + |
| 26 | +fn jarvis_march(points []Point) []Point { |
| 27 | + mut hull_point := left_most_point(points) |
| 28 | + mut hull_points := [hull_point] |
| 29 | + |
| 30 | + |
| 31 | + for { |
| 32 | + mut end_point := points[0] |
| 33 | + |
| 34 | + for i := 1; i < points.len; i++ { |
| 35 | + if end_point.equal(points[i]) || !counter_clock_wise(points[i], hull_points[hull_points.len-1], end_point) { |
| 36 | + end_point = points[i] |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + hull_point = end_point |
| 41 | + if end_point.equal(hull_points[0]) { |
| 42 | + break |
| 43 | + } |
| 44 | + |
| 45 | + hull_points << hull_point |
| 46 | + } |
| 47 | + return hull_points |
| 48 | +} |
| 49 | + |
| 50 | +fn main() { |
| 51 | + points := [ |
| 52 | + Point{-5, 2}, Point{5, 7}, Point{-6, -12}, Point{-14, -14}, Point{9, 9}, |
| 53 | + Point{-1, -1}, Point{-10, 11}, Point{-6, 15}, Point{-6, -8}, Point{15, -9}, |
| 54 | + Point{7, -7}, Point{-2, -9}, Point{6, -5}, Point{0, 14}, Point{2, 8} |
| 55 | + ] |
| 56 | + |
| 57 | + hull_points := jarvis_march(points) |
| 58 | + |
| 59 | + println('The hull points are:') |
| 60 | + for p in hull_points { |
| 61 | + println('x=$p.x y=$p.y') |
| 62 | + } |
| 63 | +} |
0 commit comments