Home   Cover Cover Cover Cover
 

Minimum distance between points

/csbook/solutions/18/A03.cs
using System;

class MinimumDistance {
  
  // Given a set of points in 2D space this program computes the two
  // closest points.
  static void Main(string[] arg) {
    double[,] p = {{2.5,3.0}, {3.7,0.1}, {5.2,3.2},  // points
                   {4.9,1.4}, {3.5,2.7}, {2.6,4.7}};
    double min = Double.MaxValue;                    // minimum distance
    int mini = 0, minj = 0;                          // indexes of the points with min.distance
    for (int i = 0; i < p.GetLength(0); i++) {       // first point
      for (int j = i+1; j < p.GetLength(0); j++) {   // second point
        double dist = Math.Sqrt(Math.Pow(p[i,0]-p[j,0], 2) + Math.Pow(p[i,1]-p[j,1], 2));
        if (dist < min) {
          min = dist; mini = i; minj = j;
        }
      }
    }
    Console.WriteLine("Closest points: ({0},{1}) und ({2},{3})", 
      p[mini,0], p[mini,1], p[minj,0], p[minj,1]);
  }
}