我有一个班级泵
public class Pump
{
public string Name { get; set; }
public int PSI_min { get; set; }
public int PSI_max { get; set; }
public int Horsepower_min { get; set; }
public Bitmap Graph { get; set; }
public int RPM { get; set; }
public Pump (string name, int psi_min, int psi_max, int horsepower_min)
{
Name = name;
PSI_min = psi_min;
PSI_max = psi_max;
Horsepower_min = horsepower_min;
}
}
我可以根据用户输入(PSI,HP和RPM)找到适合的泵
public void Calculate()
{
for (int i=0; i<9; i++)
{
Pump pump = pumps[i];
if (pump.PSI_min <= givenPSI && pump.PSI_max >= givenPSI && pump.Horsepower_min <= givenHorsepower && pump.RPM == givenRPM)
{
pumpsThatFit.Add(pump);
}
}
现在,如果没有完全匹配的泵(PSI太高,HP太低等等),我试图找到一种让程序获得最近可用泵的方法。但我无法想办法。有什么想法吗?
答案 0 :(得分:0)
一种方法是计算泵和用户定义的泵之间的euclidian distance,然后选择最接近的泵。
计算两个向量之间的距离是通过得到第n个元素的向量差的平方和的平方根来完成的。
A := (A[0], A[1], ..., A[n])
B := (B[0], B[1], ..., B[n])
distance = sqrt( (B[0]-A[0])^2 + (B[1]-A[1])^2 + ... + (B[n]-A[n])^2)
您的Pumps也可以这样做,因为它们在技术上属于属性载体。
double Dist(Pump a, Pump b)
{
int PSIMinDiff = b.PSI_min - a.PSI_min;
int PSIMaxDiff = b.PSI_max - a.PSI_max;
int HorsepowerMinDiff = b.Horsepower_min - a.Horsepower_min;
int RPMDiff = b.RPM - a.RPM;
return Math.Sqrt(
(PSIMinDiff * PSIMinDiff) +
(PSIMaxDiff * PSIMaxDiff) +
(HorsepowerMinDiff * HorsepowerMinDiff) +
(RPMDiff * RPMDiff));
}
//Pump[] pumps - all pumps
//Pump userPump - the pump defined by the user
List<Pump> closestPumps = new List<Pump>();
//Get the lowest distance
double minDist = Double.MaxValue;
foreach(Pump p in pumps)
{
double distance= Dist(p, userPump);
if(distance < minDist) minDist = distance;
}
//Select pumps which are the closest to the one that the user defined
foreach(Pump p in pumps)
{
if(Dist(p, userPump) == minDist)
closestPumps.Add(p);
}
请注意,尽管此方法易于实现和使用,但其中一个最大的缺点是它没有加权,虽然结果在数学上是正确的,但它们可能与用户想要看到的不同。