diff --git a/geom.go b/geom.go index 33273d0..cb253c6 100644 --- a/geom.go +++ b/geom.go @@ -31,6 +31,12 @@ func (err DistError) Error() string { // Point represents a point in n-dimensional Euclidean space. type Point []float64 +func (p Point) Copy() Point { + result := make(Point, len(p)) + copy(result, p) + return result +} + // Dist computes the Euclidean distance between two points p and q. func (p Point) dist(q Point) float64 { if len(p) != len(q) { @@ -188,9 +194,15 @@ func NewRectFromPoints(minPoint, maxPoint Point) (r Rect, err error) { return } - //checking that min and max points is swapping + // check that min and max point coordinates require swapping + copied := false for i, p := range minPoint { if minPoint[i] > maxPoint[i] { + if !copied { + minPoint = minPoint.Copy() + maxPoint = maxPoint.Copy() + copied = true + } minPoint[i] = maxPoint[i] maxPoint[i] = p } diff --git a/geom_test.go b/geom_test.go index 13d8611..96418fc 100644 --- a/geom_test.go +++ b/geom_test.go @@ -59,14 +59,13 @@ func TestNewRectFromPointsWithSwapPoints(t *testing.T) { rect, err := NewRectFromPoints(q, p) if err != nil { - t.Errorf("Error on NewRect(%v, %v): %v", p, q, err) + t.Errorf("Error on NewRect(%v, %v): %v", q, p, 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 := p.dist(rect.p); d > EPS { + t.Errorf("Expected p == rect.") } - if d := q.dist(rect.p); d > EPS { + if d := q.dist(rect.q); d > EPS { t.Errorf("Expected q == rect.q") } }