diff --git a/geom.go b/geom.go index bee6b54..06e83a3 100644 --- a/geom.go +++ b/geom.go @@ -182,6 +182,25 @@ func NewRect(p Point, lengths []float64) (r *Rect, err error) { return } +// NewRectFromPoints constructs and returns a pointer to a Rect given a corner points. +func NewRectFromPoints(minPoint, maxPoint Point) (r *Rect, err error) { + if len(minPoint) != len(maxPoint) { + err = &DimError{len(minPoint), len(maxPoint)} + return + } + + //checking that min and max points is swapping + for i, p := range minPoint { + if minPoint[i] > maxPoint[i] { + minPoint[i] = maxPoint[i] + maxPoint[i] = p + } + } + + r = &Rect{p: minPoint, q: maxPoint} + return +} + // Size computes the measure of a rectangle (the product of its side lengths). func (r *Rect) Size() float64 { size := 1.0 diff --git a/geom_test.go b/geom_test.go index 015ea13..d43dd5f 100644 --- a/geom_test.go +++ b/geom_test.go @@ -37,6 +37,40 @@ func TestNewRect(t *testing.T) { } } +func TestNewRectFromPoints(t *testing.T) { + p := Point{1.0, -2.5, 3.0} + q := Point{3.5, 5.5, 4.5} + + rect, err := NewRectFromPoints(p, q) + if err != nil { + t.Errorf("Error on NewRect(%v, %v): %v", p, q, err) + } + if d := p.dist(rect.p); d > EPS { + t.Errorf("Expected p == rect.p") + } + if d := q.dist(rect.q); d > EPS { + t.Errorf("Expected q == rect.q") + } +} + +func TestNewRectFromPointsWithSwapPoints(t *testing.T) { + p := Point{1.0, -2.5, 3.0} + q := Point{3.5, 5.5, 4.5} + + rect, err := NewRectFromPoints(q, p) + if err != nil { + t.Errorf("Error on NewRect(%v, %v): %v", p, q, err) + } + + // we must swap p and q because in function it was swapped + if d := p.dist(rect.q); d > EPS { + t.Errorf("Expected p == rect.p") + } + if d := q.dist(rect.p); d > EPS { + t.Errorf("Expected q == rect.q") + } +} + func TestNewRectDimMismatch(t *testing.T) { p := Point{-7.0, 10.0} lengths := []float64{2.5, 8.0, 1.5}