从三维中找出距离最接近的点对,有不足之处还请指正
using System;
using System.Collections.Generic;using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 最接近点问题
{
class Program
{
/**
*通过计算他们之间的距离形成一个距离数组选出最小的一个
*1->2,3.4,5..n
*2->3,4,5..n
*3->4,5,6..n
*..
*n-1->n
*/
static void Main(string[] args)
{
while(true)
{
Init();
}
Console.ReadKey();
}
public static void Init()
{
Console.WriteLine("输入点对数:");
int number = int.Parse(Console.ReadLine());
if(number<=1)
{
Console.WriteLine("输入错误");
}
else
{
List<Point> pointsList = new List<Point>();
Random ran = new Random();
List<Distence> pointsDis = new List<Distence>();
Console.WriteLine("随机生成的点:");
for (int i = 0; i < number; i++)
{
double x = Convert.ToDouble((ran.Next(0, 20) + ran.NextDouble()).ToString("0.00"));
double y = Convert.ToDouble((ran.Next(0, 20) + ran.NextDouble()).ToString("0.00"));
double z = Convert.ToDouble((ran.Next(0, 20) + ran.NextDouble()).ToString("0.00"));
pointsList.Add(new Point(i, x, y, z));//随机数初始化
pointsList[i].show();
Console.WriteLine("");
}
for (int i = 0; i < number; i++)
{
for (int j = i + 1; j < number; j++)
{
double dis = pointsList[i].getDistence(pointsList[i], pointsList[j]);//返回这两个点的距离
pointsDis.Add(new Distence(pointsList[i].Id, pointsList[j].Id, dis));//排成list数组
}
}
//按照距离排序
for (int i = 0; i < pointsDis.Count-1; i++)
{
int j=i+1;
Distence p1;
if (pointsDis[i].ShortDis > pointsDis[j].ShortDis)
{
p1 = pointsDis[i];//把最小的排在第一位
pointsDis[i] = pointsDis[j];
pointsDis[j] = p1;
}
}
Console.WriteLine("最短的距离为:点");
pointsList[pointsDis[0].id].show();
pointsList[pointsDis[0].id2].show();
Console.WriteLine("最短距离为:" + pointsDis[0].ShortDis);
}
}
class Distence
{
int ID1;
int ID2;
double shortDis;
public Distence(int a,int b,double dis)
{
this.ID1 = a;
this.ID2 = b;
this.shortDis = dis;
}
public double ShortDis
{
get
{
return shortDis;
}
}
public int id
{
get
{
return ID1;
}
}
public int id2
{
get
{
return ID2;
}
}
}
class Point
{
int ID;
double x;
double y;
double z;
public int Id
{
get
{
return ID;
}
}
public void show()
{
Console.WriteLine("id:"+(this.ID+1)+"<" + this.x + "," + this.y + "," + this.z + ">");
}
public Point(int id, double x, double y, double z)//构造函数
{
this.ID = id;
this.x = x;
this.y = y;
this.z = z;
}
public double getDistence(Point a, Point b)//获取空间中两个点的距离
{
double distence = 0;
distence = Math.Sqrt(Math.Pow(2, (a.x - b.x)) + Math.Pow(2, (a.y - b.y)) + Math.Pow(2, (a.z - b.z)));
return distence;
}
}
}
}