Skip to content

Commit

Permalink
Fix incorrect Intersection algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
dsamarin committed May 11, 2018
1 parent 7b9719a commit 8e6537e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
12 changes: 7 additions & 5 deletions geofence.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"github.com/kellydunn/golang-geo"
)

// Geofence represents a point on the Earth with an accuracy radius.
// Geofence represents a point on the Earth with an accuracy radius in meters.
type Geofence struct {
Latitude, Longitude, Radius float64
}
Expand All @@ -29,17 +29,19 @@ func (mi *Geofence) Intersection(tu *Geofence) (i SetIntersection) {
tuPoint := geo.NewPoint(tu.Latitude, tu.Longitude)
distance := miPoint.GreatCircleDistance(tuPoint) * 1000

ourRadius := mi.Radius + tu.Radius
if ourRadius > distance {
radiusSum := mi.Radius + tu.Radius
radiusDiff := mi.Radius - tu.Radius

if distance-radiusSum > 0 {
i = IsDisjoint
return
}

if mi.Radius-tu.Radius > distance {
if -distance+radiusDiff >= 0 {
i |= IsSuperset
}

if tu.Radius-mi.Radius > distance {
if -distance-radiusDiff >= 0 {
i |= IsSubset
}

Expand Down
26 changes: 26 additions & 0 deletions geofence_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package main

import "testing"

func TestIntersection(t *testing.T) {
tests := []struct {
Mi Geofence
Tu Geofence
Result SetIntersection
}{
{Geofence{36.1699, -115.1398, 1000.0}, Geofence{36.1699, -115.1398, 10.0}, IsSuperset},
{Geofence{36.1699, -115.1398, 10.0}, Geofence{36.1699, -115.1398, 1000.0}, IsSubset},
{Geofence{36.1699, -115.1398, 10.0}, Geofence{37.7749, -122.4194, 1000.0}, IsDisjoint},
{Geofence{36.1699, -115.1398, 10.0}, Geofence{36.1699, -115.1398, 10.0}, IsSubset | IsSuperset},
{Geofence{36.1699, -115.13983, 100.0}, Geofence{36.1699, -115.1398, 100.0}, 0},
}

for _, test := range tests {
got := test.Mi.Intersection(&test.Tu)
want := test.Result
if want != got {
t.Errorf("With %s and %s: expected intersection code %b, got %b",
BlacklistRule{Geofence: &test.Mi}, BlacklistRule{Geofence: &test.Tu}, want, got)
}
}
}

0 comments on commit 8e6537e

Please sign in to comment.