From fc4c1c820bc19a6496f2c26e6184f3abaf8976b3 Mon Sep 17 00:00:00 2001 From: Derek McQuay Date: Fri, 26 Aug 2016 11:37:55 -0700 Subject: [PATCH] determine size of rectangle To determine the size of rectangle, it was required to be able to determine who would be the neighboring points. A neighbor is a point that would make the exterior of the rectangle, not the cross-section. Finding the neighbors allows for a simple l*w to calculate size. --- rectangle.go | 37 ++++++++++++++++++++++++++++++++++++- rectangle_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/rectangle.go b/rectangle.go index cff09dc..eb138e4 100644 --- a/rectangle.go +++ b/rectangle.go @@ -1,6 +1,9 @@ package rect -import "math" +import ( + "math" + "sort" +) type Rectangle struct { P1, P2, P3, P4 Point @@ -22,3 +25,35 @@ func (r Rectangle) IsRect() bool { dd4 := math.Sqrt(math.Abs(cx-r.P4.X)) + math.Sqrt(math.Abs(cy-r.P4.Y)) return dd1 == dd2 && dd1 == dd3 && dd1 == dd4 } + +func (r Rectangle) Neighbors(p Point) (Point, Point) { + keys := []float64{distance(r.P1, p), distance(r.P2, p), distance(r.P3, p), distance(r.P4, p)} + sort.Float64s(keys) + n := []Point{} + d := distance(r.P1, p) + if keys[1] == d || keys[2] == d { + n = append(n, r.P1) + } + d = distance(r.P2, p) + if keys[1] == d || keys[2] == d { + n = append(n, r.P2) + } + d = distance(r.P3, p) + if keys[1] == d || keys[2] == d { + n = append(n, r.P3) + } + d = distance(r.P4, p) + if keys[1] == d || keys[2] == d { + n = append(n, r.P4) + } + return n[0], n[1] +} + +func (r Rectangle) Size() float64 { + n1, n2 := r.Neighbors(r.P1) + return distance(r.P1, n1) * distance(r.P1, n2) +} + +// +//func Containment(r1, r2, Rectangle) bool { +//} diff --git a/rectangle_test.go b/rectangle_test.go index 9f39c32..d9fb023 100644 --- a/rectangle_test.go +++ b/rectangle_test.go @@ -27,3 +27,28 @@ func TestIsRect(t *testing.T) { } } + +func TestSize(t *testing.T) { + var isRectTests = []struct { + r Rectangle + expected float64 + }{ + {Rectangle{P1: Point{1, 1}, P2: Point{1, 2}, P3: Point{2, 1}, P4: Point{2, 2}}, 1}, + {Rectangle{P1: Point{0, 0}, P2: Point{0, 1}, P3: Point{1, 0}, P4: Point{1, 1}}, 1}, + {Rectangle{P1: Point{0, 0}, P2: Point{0, -1}, P3: Point{-1, 0}, P4: Point{-1, -1}}, 1}, + {Rectangle{P1: Point{1.5, 1.5}, P2: Point{1.5, 3.5}, P3: Point{3.5, 1.5}, P4: Point{3.5, 3.5}}, 4}, + {Rectangle{P1: Point{0, 0}, P2: Point{0, 3}, P3: Point{2, 0}, P4: Point{2, 3}}, 6}, + {Rectangle{P1: Point{0, 0}, P2: Point{0, 100}, P3: Point{100, 0}, P4: Point{100, 100}}, 10000}, + } + for _, rt := range isRectTests { + actual := rt.r.Size() + if actual != rt.expected { + t.Errorf( + "failed spiral:\n\texpected: %d\n\t actual: %d", + rt.expected, + actual, + ) + } + + } +}