Reputation: 123
I calculate euclidean distance in c#.
Point[] points = new Point[100];
I have the coordinates of the points I created in this array.I want to calculate the distance between all points.
for (int i = 1; i < k+1; i++)
{
X1 = points[i].X;
X2 = points[i + 1].X;
Y1 = points[i].Y;
Y2 = points[i + 1].Y;
result = Math.Sqrt((X1 - X2) * (X1 - X2) + (Y1 - Y2) * (Y1 - Y2));
}
With this code I have calculated the distance between points (eg: distance between points a and b, distance between points c and d, etc.) but I couldn't calculate the distance between points a and c or the points b and b I want to calculate the distance between all points in this array. How do I do that?
Upvotes: 0
Views: 3177
Reputation: 123
public void Euclidea()
{
double result;
int X1,X2,Y1,Y2;
for (int i = 1; i < k+1; i++)
{
X1 = points[i].X;
Y1 = points[i].Y;
for (int j = 0; j < k; j++)
{
X2 = points[j + 1].X;
Y2 = points[j + 1].Y;
result = Math.Sqrt((X1 - X2) * (X1 - X2) + (Y1 - Y2) * (Y1 - Y2));
}
}
}
I solved the problem by typing this code k=points.length()
Upvotes: 0
Reputation: 4037
You probably want to go through the array twice.
Point[] points = new Point[100];
for(int i = 0; i < points.Length; i++)
for (int j = points.Length - 1; j >= i; j--)
{
float distance = 0;
if(i != j)
distance = CalculateDistance(points[i], points[j]);
// Do more stuff here
}
Obviously, you could simply run two for loops of equal lengths, but this will give you the same result twice. When i
and j
have the same value flipped (i = 10
, j = 15
and later i = 15
and j = 10
), you do the same calculation to get the same result. To prevent that I have my second loop only run about half the values to not redo calculations.
The CalculateDistance method does exactly the same as the code you have written before, in my case the following:
private static float CalculateDistance(Point point1, Point point2)
{
float X1 = point1.X;
float X2 = point1.Y;
float Y1 = point2.X;
float Y2 = point2.Y;
return (float)Math.Sqrt((X1 - X2) * (X1 - X2) + (Y1 - Y2) * (Y1 - Y2));
}
This way I can reuse and reorder my calculations at any time, because I only have to move a single line. Note that you can always just use the floats as parameters instead of locals, but I felt like this way would make it more readable here in this example.
I also skipped the calculations when the distance was equal, because the same values were compared.
Upvotes: 0
Reputation: 46
You have to use 2 loops. The first loop assign values to X1 and the second loop assign values to X2.
This allows to calculate the Euclidean Distance between two points that aren't contiguous in the array.
Upvotes: 1
Reputation: 134
You have to use 2 for loops to achieve that.
Also you would want to persist the euclidean distances between these points somewhere.
Upvotes: 0