[英]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,而不是创建具有名称和值的简单类,例如:
public class GameInfo
{
public string name;
public float value;
public GameInfo(string name, float value)
{
this.name = name;
this.value = value;
}
}
现在,您可以轻松拥有包含这些值的排序列表。 像这样:
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);
}
就是这样。
所谓“最强”,是指您要查找具有最大幅度的值吗? 您是否只需要值或变量名?
如果只需要这些值,则可以执行以下操作:
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();
上面的操作:将每个float映射到具有每个stat大小的临时对象,按大小对其进行排序,然后将其转换回原始float,并获取前两个值。
另一方面,如果要查找名称,可以将名称/状态映射存储在字典中:
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();
上面返回包含名称和原始值的键/值对的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.