Utility static helper that picks a random key from a Dictionary<T, float> using weights. It sums weights, multiplies a random double by the total, then walks entries subtracting weights until value <= 0 and returns that key.
using System;
using System.Collections.Generic;
namespace BrickJam;
public static class WeightedList
{
public static T RandomKey<T>( Dictionary<T, float> weightedDictionary )
{
var totalWeight = 0f;
foreach ( var weight in weightedDictionary.Values )
totalWeight += weight;
var randomValue = (float)(MansionGame.Random.NextDouble() * totalWeight);
foreach ( var entry in weightedDictionary )
{
randomValue -= entry.Value;
if ( randomValue <= 0 )
return entry.Key;
}
return default;
}
}