C# 从 4 max/min 个选择中找到 2 个最强的值

C# Find 2 strongest values from 4 max/min selections

所有值的范围从 -100.0f 到 100.0f

public float happysad = 0.0f;
public float passiveagressive = 0.0f;
public float friendenemy = 0.0f;
public float weakstrong = 0.0f;

void GetStrongestTwo() {
    /* Work out the 2 most extreme values
    if (happysad > 0){
            sad is the strongest
    }
    if (happysad < 0){
            sad is the strongest
    }
    Need to do this for all then work out the two that have the largest (either positive or negative value)
    */ 
}

我试过常量 if 语句,但根据我对 max 和 min 的理解,应该有更简单的方法。我的尝试产生了 24 个 if 语句。另一种方法是将值分隔为以下值。

public float happy = 0.0f;
public float sad = 0.0f;
public float passive = 0.0f;
public float agressive = 0.0f;
public float friend = 0.0f;
public float enemy = 0.0f;
public float weak = 0.0f;
public float strong = 0.0f;

我的问题是应对这一挑战的最佳方法是什么?如果存在一种编码方法并且我只需要进行更多研究,我会很感激向正确的方向推进,或者如果第二种解决方案更可行,那么我稍后会在我的代码中对其进行补偿。由于这些值是相反的,我宁愿每次发生影响情感元素的事件时都必须添加或删除 1.0f 的值。

与其使用那么多变量和大量 if,不如创建一个带有名称和值的简单 class,例如:

public class GameInfo
{
  public string name;
  public float value;
  public GameInfo(string name, float value)
  {
    this.name = name;
    this.value = value;
  }
}

现在,您可以轻松地得到一个包含这些值的 sorted 列表。像这样:

    List<GameInfo> info = new List<GameInfo>();

    // please add the other info you wish
    info.Add(new GameInfo("happy", 5.0f));
    info.Add(new GameInfo("sad", 15.0f));
    info.Add(new GameInfo("passive", 4.0f));
    info.Add(new GameInfo("agressive", 35.0f));
    // ...

    // sort the list (I used linq but you could use other methods)
    List<GameInfo> sortedInfo = info.OrderByDescending(o => o.value).ToList();

    foreach (GameInfo i in sortedInfo)
    {
        Console.WriteLine(i.name + ", " + i.value);
    }

就是这样。

"strongest",您的意思是您正在尝试查找具有最高幅度的值吗?您只需要变量的值或名称吗?

如果你只需要这些值,你可以这样做:

float happysad = -10.0f;
float passiveaggressive = 5.0f;
float friendenemy = 2.0f;
float weakstrong = 7.0f;

var twoStrongest = 
    new [] {happysad, passiveaggressive, friendenemy, weakstrong}
        .Select(stat => new {Value = stat, Magnitude = Math.Abs(stat)})
        .OrderByDescending(statWithMagnitude => statWithMagnitude.Magnitude)
        .Select(statWithMagnitude => statWithMagnitude.Value)
        .Take(2).ToList();

上面的内容:将每个浮点数映射到一个临时对象,该对象具有每个统计量的大小,按大小对其进行排序,然后将其转换回原始浮点数,并取前两个值。

另一方面,如果要查找名称,可以将 name/stat 映射存储在字典中:

var stats = new Dictionary<string, float> {
    {"happysad",  -10.0f},
    {"passiveaggressive",  -6.0f},
    {"friendenemy",  8.0f},
    {"weakstrong",  3.0f}
};

var twoStrongest = stats
    .Select(entry => new {Entry = entry, Magnitude = Math.Abs(entry.Value)})
    .OrderByDescending(statWithMagnitude => statWithMagnitude.Magnitude)
    .Select(statWithMagnitude => statWithMagnitude.Entry)
    .Take(2).ToList();

上方 returns 包含名称和原始值的 key/value 对列表。