add more polygon tests (also they pass now)
This commit is contained in:
parent
b08cb774e1
commit
b2e2a370fc
2 changed files with 43 additions and 8 deletions
|
@ -4,11 +4,11 @@ import "image"
|
|||
|
||||
// PolygonContains reports if a polygon contains a point
|
||||
func PolygonContains(polygon []image.Point, p image.Point) bool {
|
||||
for i, p1 := range polygon {
|
||||
p2 := polygon[(i+1)%len(polygon)]
|
||||
// ∆(p p1 p2) should have positive signed area
|
||||
p1, p2 = p1.Sub(p), p2.Sub(p)
|
||||
if p2.X*p1.Y-p1.X*p2.Y < 0 {
|
||||
for i, q := range polygon {
|
||||
r := polygon[(i+1)%len(polygon)]
|
||||
// ∆(p q r) should have positive signed area
|
||||
q, r = q.Sub(p), r.Sub(p)
|
||||
if q.X*r.Y > r.X*q.Y {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,21 +8,56 @@ import (
|
|||
func TestPolygonContains(t *testing.T) {
|
||||
square5 := []image.Point{
|
||||
{X: 0, Y: 0},
|
||||
{X: 5, Y: 0},
|
||||
{X: 5, Y: 5},
|
||||
{X: 0, Y: 5},
|
||||
{X: 5, Y: 5},
|
||||
{X: 5, Y: 0},
|
||||
}
|
||||
pentagon := []image.Point{
|
||||
{X: -5, Y: -4},
|
||||
{X: -7, Y: 2},
|
||||
{X: 0, Y: 7},
|
||||
{X: 7, Y: 2},
|
||||
{X: 5, Y: -4},
|
||||
}
|
||||
hexagon := []image.Point{
|
||||
{X: 8, Y: 0},
|
||||
{X: 0, Y: 8},
|
||||
{X: 8, Y: 16},
|
||||
{X: 23, Y: 16},
|
||||
{X: 31, Y: 8},
|
||||
{X: 23, Y: 0},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
polygon []image.Point
|
||||
point image.Point
|
||||
want bool
|
||||
}{
|
||||
{square5, image.Pt(2, 3), true},
|
||||
{square5, image.Pt(0, 0), true},
|
||||
{square5, image.Pt(5, 5), true},
|
||||
{square5, image.Pt(-5, 0), false},
|
||||
{square5, image.Pt(0, -5), false},
|
||||
{square5, image.Pt(6, 6), false},
|
||||
|
||||
{pentagon, image.Pt(0, 0), true},
|
||||
{pentagon, image.Pt(8, 0), false},
|
||||
{pentagon, image.Pt(1, 1), true},
|
||||
{pentagon, image.Pt(-1, -1), true},
|
||||
{pentagon, image.Pt(-10000, 10000), false},
|
||||
|
||||
{hexagon, image.Pt(0, 0), false},
|
||||
{hexagon, image.Pt(16, 8), true},
|
||||
{hexagon, image.Pt(0, 8), true},
|
||||
{hexagon, image.Pt(-1, 8), false},
|
||||
{hexagon, image.Pt(31, 8), true},
|
||||
{hexagon, image.Pt(32, 8), false},
|
||||
{hexagon, image.Pt(10000, 10000), false},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
if got, want := PolygonContains(test.polygon, test.point), test.want; got != want {
|
||||
t.Errorf("polygonContains(%v, %v) = %v, want %v", test.polygon, test.point, got, want)
|
||||
t.Errorf("PolygonContains(%v, %v) = %v, want %v", test.polygon, test.point, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue