Browse Source

Use atan2

Which would've saved me lots of time and headbanging earlier.
master
Chris Smith 4 years ago
parent
commit
b2965d53fc
Signed by: Chris Smith <chris@chameth.com> GPG Key ID: 3A2D4BBDC4A3C9A9
2 changed files with 4 additions and 54 deletions
  1. 4
    20
      10/main.go
  2. 0
    34
      10/main_test.go

+ 4
- 20
10/main.go View File

@@ -22,25 +22,6 @@ func buildMap(input []string) []*asteroid {
22 22
 	return res
23 23
 }
24 24
 
25
-func angleBetween(asteroid1, asteroid2 *asteroid) float64 {
26
-	if asteroid1.y == asteroid2.y {
27
-		if asteroid2.x > asteroid1.x {
28
-			return math.Pi / 2
29
-		} else {
30
-			return 3 * math.Pi / 2
31
-		}
32
-	} else {
33
-		angle := math.Atan(float64(asteroid2.x-asteroid1.x) / float64(asteroid1.y-asteroid2.y))
34
-		if asteroid1.y < asteroid2.y {
35
-			angle += math.Pi
36
-		}
37
-		if angle < 0 {
38
-			angle += math.Pi * 2
39
-		}
40
-		return angle
41
-	}
42
-}
43
-
44 25
 func checkAngles(asteroid1 *asteroid, others []*asteroid, countVisible bool) map[float64][]*asteroid {
45 26
 	angles := make(map[float64][]*asteroid)
46 27
 	for _, asteroid2 := range others {
@@ -48,7 +29,10 @@ func checkAngles(asteroid1 *asteroid, others []*asteroid, countVisible bool) map
48 29
 			continue
49 30
 		}
50 31
 
51
-		angle := angleBetween(asteroid1, asteroid2)
32
+		angle := math.Atan2(float64(asteroid2.x-asteroid1.x), float64(asteroid1.y-asteroid2.y))
33
+		if angle < 0 {
34
+			angle += math.Pi * 2
35
+		}
52 36
 
53 37
 		if len(angles[angle]) == 0 && countVisible {
54 38
 			asteroid1.visible++

+ 0
- 34
10/main_test.go View File

@@ -1,34 +0,0 @@
1
-package main
2
-
3
-import (
4
-	"math"
5
-	"testing"
6
-)
7
-
8
-func Test_angleBetween(t *testing.T) {
9
-	type args struct {
10
-		asteroid1 *asteroid
11
-		asteroid2 *asteroid
12
-	}
13
-	tests := []struct {
14
-		name string
15
-		args args
16
-		want float64
17
-	}{
18
-		{"above", args{&asteroid{x: 5, y: 5}, &asteroid{x: 5, y: 0}}, 0},
19
-		{"below", args{&asteroid{x: 5, y: 5}, &asteroid{x: 5, y: 10}}, math.Pi},
20
-		{"right", args{&asteroid{x: 5, y: 5}, &asteroid{x: 10, y: 5}}, math.Pi / 2},
21
-		{"left", args{&asteroid{x: 5, y: 5}, &asteroid{x: 0, y: 5}}, 3 * math.Pi / 2},
22
-		{"quadrant1", args{&asteroid{x: 5, y: 5}, &asteroid{x: 10, y: 0}}, math.Pi / 4},
23
-		{"quadrant2", args{&asteroid{x: 5, y: 5}, &asteroid{x: 10, y: 10}}, 3 * math.Pi / 4},
24
-		{"quadrant3", args{&asteroid{x: 5, y: 5}, &asteroid{x: 0, y: 10}}, 5 * math.Pi / 4},
25
-		{"quadrant4", args{&asteroid{x: 5, y: 5}, &asteroid{x: 0, y: 0}}, 7 * math.Pi / 4},
26
-	}
27
-	for _, tt := range tests {
28
-		t.Run(tt.name, func(t *testing.T) {
29
-			if got := angleBetween(tt.args.asteroid1, tt.args.asteroid2); got != tt.want {
30
-				t.Errorf("angleBetween() = %v, want %v", got, tt.want)
31
-			}
32
-		})
33
-	}
34
-}

Loading…
Cancel
Save