added function to test containment

Containment uses the sumOfTri to determine if a point is inside of the
rectangle, r1.  It checks all four points of r2 (p1, p2, p3, p4) against
r1.  If they are all inside, then the rectangle is contained.
This commit is contained in:
Derek McQuay 2016-08-26 13:48:26 -07:00
parent 4ad50ba37c
commit 69aff8a038
2 changed files with 80 additions and 3 deletions

View File

@ -54,6 +54,40 @@ func (r Rectangle) Size() float64 {
return distance(r.P1, n1) * distance(r.P1, n2)
}
//
//func Containment(r1, r2, Rectangle) bool {
//}
func sumOfTri(r Rectangle, p Point) bool {
rsize := r.Size()
n1, n2 := r.Neighbors(r.P1)
x1, x2 := Point{}, Point{}
accross := &Point{}
if r.P2 != n1 || r.P2 != n2 {
accross = &r.P2
x1, x2 = r.Neighbors(r.P2)
}
if r.P3 != n1 || r.P3 != n2 {
accross = &r.P3
x1, x2 = r.Neighbors(r.P3)
}
if r.P4 != n1 || r.P4 != n2 {
accross = &r.P4
x1, x2 = r.Neighbors(r.P4)
}
sumTri := SizeTriangle(r.P1, n1, p) +
SizeTriangle(r.P1, n2, p) +
SizeTriangle(*accross, x1, p) +
SizeTriangle(*accross, x2, p)
if rsize == sumTri {
return true
}
return false
}
// Containment returns whether r2 is contained inside of r1
func Containment(r1, r2 Rectangle) bool {
if r1.Size() <= r2.Size() {
return false
}
if sumOfTri(r1, r2.P1) && sumOfTri(r1, r2.P2) && sumOfTri(r1, r2.P3) && sumOfTri(r1, r2.P4) {
return true
}
return false
}

View File

@ -52,3 +52,46 @@ func TestSize(t *testing.T) {
}
}
func TestContainment(t *testing.T) {
var containmentTest = []struct {
r []Rectangle
expected bool
}{
{
[]Rectangle{
Rectangle{Point{0, 0}, Point{0, 3}, Point{3, 0}, Point{3, 3}},
Rectangle{Point{1, 1}, Point{1, 2}, Point{2, 1}, Point{2, 2}}},
true,
},
{
[]Rectangle{
Rectangle{Point{0, 0}, Point{0, 3}, Point{3, 0}, Point{3, 3}},
Rectangle{Point{1, 1}, Point{1, 2}, Point{2, 1}, Point{2, 2}}},
true,
},
{
[]Rectangle{
Rectangle{Point{0, 0}, Point{0, 3}, Point{3, 0}, Point{3, 3}},
Rectangle{Point{0, 0}, Point{0, 3}, Point{3, 0}, Point{3, 3}}},
false,
},
{
[]Rectangle{
Rectangle{Point{0, 0}, Point{0, 3}, Point{3, 0}, Point{3, 3}},
Rectangle{Point{3, 3}, Point{3, 4}, Point{4, 3}, Point{4, 4}}},
false,
},
}
for _, rt := range containmentTest {
actual := Containment(rt.r[0], rt.r[1])
if actual != rt.expected {
t.Errorf(
"failed spiral:\n\texpected: %d\n\t actual: %d",
rt.expected,
actual,
)
}
}
}