Advertisement
plamen27

Closest 2 points

Oct 12th, 2016
474
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. class Point
  8. {
  9. public double X { get; set; }
  10. public double Y { get; set; }
  11. }
  12.  
  13. class ClosestTwoPoints
  14. {
  15. static void Main(string[] args)
  16. {
  17. Point[] points = ReadPoints(); //• Create an array Point[] points that will keep all points.
  18. Point[] closest2Points = FindClosestTwoPoints(points);
  19. Console.WriteLine("{0:F3}", CalculateDistance(closest2Points[0], closest2Points[1]));
  20. Printpoint(closest2Points[0]);
  21. Printpoint(closest2Points[1]);
  22. }
  23.  
  24. private static void Printpoint(Point point)
  25. {
  26. Console.WriteLine("({0}, {1})", point.X, point.Y);
  27. }
  28.  
  29. private static Point[] FindClosestTwoPoints(Point[] points)
  30. {
  31. double minDistance = double.MaxValue;
  32. Point[] closestTwoPoints = null;
  33. for (int i1 = 0; i1 < points.Length; i1++)
  34. {
  35. for (int i2 = i1+1; i2 < points.Length; i2++)
  36. {
  37. double distance = CalculateDistance(points[i1], points[i2]);
  38. if (distance<minDistance)
  39. {
  40. minDistance = distance;
  41. closestTwoPoints = new Point[] { points[i1], points[i2] };
  42. }
  43. }
  44. }
  45. return closestTwoPoints;
  46. }
  47. private static double CalculateDistance(Point point1, Point point2)
  48. {
  49. double sideA = point1.X - point2.X;
  50. double sideB = point1.Y - point2.Y;
  51. double distan = Math.Sqrt(sideA * sideA + sideB * sideB);
  52. return distan;
  53. }
  54.  
  55. private static Point[] ReadPoints()
  56. {
  57. int n = int.Parse(Console.ReadLine());
  58. Point[] points = new Point[n];
  59. for (int i = 0; i < n; i++)
  60. {
  61. points[i] = ReadPoint();
  62. }
  63. return points;
  64. }
  65.  
  66. private static Point ReadPoint()
  67. {
  68. double[] array = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();
  69. Point p = new Point() { X = array[0], Y = array[1] };
  70. return p;
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement