The following code calculate the nearest distance in two points.
The part if(j==0) is tested redundantly for UsedServices.Count-1 time,
is there any way not to introduce this redudancy?
Of course we can separate the case out from for loop, I am just thinking is there a more elegant way to achieve this.
double[] nearestDistant=new double[UnUsedServices.Count];
for (int i=0;i<UnUsedServices.Count;i++)
{
for (int j=0;j<UsedServices.Count;j++)
{
double distance=GetDistance(UnUsedServices[i].coords,
UsedServices[j].coords);
if (j==0) //Used once and redundant for UsedServices.Count-1 time!
{
nearestDistant[i] = distance;
}
else
{
nearestDistant[i] = Math.Min(nearestDistant[i], distance);
}
}
}
You could initialize
nearestDistant[i]toDouble.MaxValuebefore the inner loop and then you can remove theif.The side effect of this is when
UsedServices.Count == 0thenearestDistant[i]would be set toDouble.MaxValue. If that’s ok with you.