diff --git a/cmd/recty/main.go b/cmd/recty/main.go new file mode 100644 index 0000000..66696ee --- /dev/null +++ b/cmd/recty/main.go @@ -0,0 +1,31 @@ +package main + +import ( + "fmt" + + "s.mcquay.me/dm/rect" +) + +func main() { + r := rect.Rectangle{ + P1: rect.Point{1, 1}, + P2: rect.Point{1, 2}, + P3: rect.Point{2, 1}, + P4: rect.Point{2, 2}, + } + fmt.Println(r.IsRect()) + r1 := rect.Rectangle{ + P1: rect.Point{0, 0}, + P2: rect.Point{0, 1}, + P3: rect.Point{1, 0}, + P4: rect.Point{1, 1}, + } + fmt.Println(r1.IsRect()) + r1 := rect.Rectangle{ + P1: rect.Point{0, 0}, + P2: rect.Point{0, 1}, + P3: rect.Point{1, 0}, + P4: rect.Point{1, 1}, + } + fmt.Println(r1.IsRect()) +} diff --git a/point.go b/point.go new file mode 100644 index 0000000..e0b5e15 --- /dev/null +++ b/point.go @@ -0,0 +1,5 @@ +package rect + +type Point struct { + X, Y float64 +} diff --git a/rectangle.go b/rectangle.go new file mode 100644 index 0000000..cff09dc --- /dev/null +++ b/rectangle.go @@ -0,0 +1,24 @@ +package rect + +import "math" + +type Rectangle struct { + P1, P2, P3, P4 Point +} + +func (r Rectangle) IsRect() bool { + // make sure they aren't all just the same point + if (r.P1.X == r.P2.X && r.P1.X == r.P3.X && r.P1.X == r.P4.X) && + (r.P1.Y == r.P2.Y && r.P1.Y == r.P3.Y && r.P1.Y == r.P4.Y) { + return false + } + + cx := (r.P1.X + r.P2.X + r.P3.X + r.P4.X) / 4.0 + cy := (r.P1.Y + r.P2.Y + r.P3.Y + r.P4.Y) / 4.0 + + dd1 := math.Sqrt(math.Abs(cx-r.P1.X)) + math.Sqrt(math.Abs(cy-r.P1.Y)) + dd2 := math.Sqrt(math.Abs(cx-r.P2.X)) + math.Sqrt(math.Abs(cy-r.P2.Y)) + dd3 := math.Sqrt(math.Abs(cx-r.P3.X)) + math.Sqrt(math.Abs(cy-r.P3.Y)) + dd4 := math.Sqrt(math.Abs(cx-r.P4.X)) + math.Sqrt(math.Abs(cy-r.P4.Y)) + return dd1 == dd2 && dd1 == dd3 && dd1 == dd4 +} diff --git a/rectangle_test.go b/rectangle_test.go new file mode 100644 index 0000000..9f39c32 --- /dev/null +++ b/rectangle_test.go @@ -0,0 +1,29 @@ +package rect + +import "testing" + +func TestIsRect(t *testing.T) { + var isRectTests = []struct { + r Rectangle + expected bool + }{ + {Rectangle{P1: Point{1, 1}, P2: Point{1, 2}, P3: Point{2, 1}, P4: Point{2, 2}}, true}, + {Rectangle{P1: Point{0, 0}, P2: Point{0, 1}, P3: Point{1, 0}, P4: Point{1, 1}}, true}, + {Rectangle{P1: Point{0, 0}, P2: Point{0, -1}, P3: Point{-1, 0}, P4: Point{-1, -1}}, true}, + {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}}, true}, + {Rectangle{P1: Point{0, 0}, P2: Point{0, 3}, P3: Point{2, 0}, P4: Point{2, 3}}, true}, + {Rectangle{P1: Point{0, 0}, P2: Point{0, 100}, P3: Point{-1, 0}, P4: Point{0, 23}}, false}, + {Rectangle{P1: Point{0, 0}, P2: Point{0, 0}, P3: Point{0, 0}, P4: Point{0, 0}}, false}, + } + for _, rt := range isRectTests { + actual := rt.r.IsRect() + if actual != rt.expected { + t.Errorf( + "failed spiral:\n\texpected: %d\n\t actual: %d", + rt.expected, + actual, + ) + } + + } +}