因此,我有一个名为ProbabilisticEnumerator的类,它接受元素映射和基于整数的权重。请参见以下示例:
var myProbabilityTable = new Dictionary<char, uint> {
{ 'A', 1 }, // 14.29%
{ 'B', 2 }, // 28.57%
{ 'C', 4 }, // 57.14%
};
我正在尝试找出一种有效的方法来反转此值,以便可以传递基于浮点数的值(对某些人来说可能更自然)。这是我的意思的示例:
var myProbabilityTable = new Dictionary<char, float> {
{ 'A', 0.1429f }, // 1
{ 'B', 0.2857f }, // 2
{ 'C', 0.5714f }, // 4
};
到目前为止,我能想到的最好的方法是至少需要两次通过。第一个获得总重量,第二个获得新字典。有没有更好的方法可以做到这一点?我是否错过了可能导致事情“崩溃”的边缘情况?
我的尝试:
class Program {
static void Main(string[] args) {
var floatWeights= new Dictionary<string, float> {
{ "A", 25.0f },
{ "B", 60.0f },
{ "C", 15.0f },
};
var integerWeights = ConvertFloatWeightsToInteger(floatWeights);
foreach(var item in integerWeights) {
Console.WriteLine(item);
}
}
static Dictionary<T, int> ConvertFloatWeightsToInteger<T>(Dictionary<T, float> elementWeights) {
var totalWeight = 0f;
foreach (var weight in elementWeights.Values) {
if (float.IsNegative(weight) || float.IsSubnormal(weight)) {
throw new ArgumentOutOfRangeException(actualValue: weight, message: "weight must be a positive normal floating-point number", paramName: nameof(weight));
}
totalWeight += weight;
}
return elementWeights.ToDictionary(
keySelector: k => k.Key,
elementSelector: e => ((int)((e.Value / totalWeight) * 1000000000))
);
}
}