-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolutionMaths.cs
85 lines (69 loc) · 2.21 KB
/
SolutionMaths.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
namespace Salesman
{
class SolutionMaths
{
public static double DistanceBetweenSquared(Point pointA, Point pointB)
{
return Math.Pow(Math.Abs(pointA.X - pointB.X), 2) + Math.Pow(Math.Abs(pointA.Y - pointB.Y), 2);
}
public static double DistanceBetween(Point pointA, Point pointB)
{
return Math.Sqrt(DistanceBetweenSquared(pointA, pointB));
}
public static double DistanceTotal(Point[] points, int[] solution, bool isSquared = true)
{
if (!IsCongruent(points, solution)) return -1;
double distance = 0;
int count = 0;
int prev = 0;
while (count <= points.Length)
{
count++;
int next = solution[prev];
if (isSquared)
{
distance += DistanceBetweenSquared(points[prev], points[next]);
}
else
{
distance += DistanceBetween(points[prev], points[next]);
}
prev = next;
}
return distance;
}
public static bool IsCongruent(Point[] points, int[] solution)
{
if (points.Length <= 1) return false;
int count = 1;
int current = solution[0];
while (current != 0)
{
if (current == -1 || count > points.Length || current == solution[current]) return false;
count++;
current = solution[current];
}
return count == points.Length;
}
public static int[] NullPath(int pathLength)
{
int[] solution = new int[pathLength];
for (int i = 0; i < solution.Length; i++)
{
solution[i] = -1;
}
return solution;
}
public static int[] ChainPath(int pathLength)
{
int[] solution = new int[pathLength];
for (int i = 0; i < solution.Length; i++)
{
solution[i] = i + 1;
}
solution[^1] = 0;
return solution;
}
}
}