找到最近的选项

本文关键字:选项 最近 | 更新日期: 2023-09-27 17:52:17

我有一个class Pump

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太低等),我正试图找到一种方法让程序获得最接近的可用泵。但我想不出什么办法。什么好主意吗?

找到最近的选项

一种方法是计算您的泵与用户定义的泵之间的欧几里德距离,然后选择最接近的泵。

计算两个向量之间的距离是通过取两个向量每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)

泵也可以这样做,因为它们在技术上是属性向量。

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);
}

请注意,虽然这种方法很容易实现和使用,但它最大的缺点之一是它没有加权,虽然结果在数学上是正确的,但它们可能与用户想要看到的结果不同。