根据另一个百分比模拟计算的百分比

时间:2010-11-01 19:21:05

标签: c# random

我正在努力建立一个基于百分比的模拟器,并通过整体改变......最好的方法是什么?

我们想要模拟,例如,挥杆。 20%由于列表整体击球手和投手而计算出某些东西并确定他是否击球。因此,如果他击球,他是一个本垒打,一个犯规球,一个打击......等等。

由于

1 个答案:

答案 0 :(得分:2)

private static Random rand = new Random();

public static T ChooseRandomOutcome<T>(Dictionary<T,int> relativeWeights)
{
    Random rand = new Random();

    var total = relativeWeights.Values.Sum();
    var randomValue = rand.Next(total);
    var runningSum = 0;
    foreach (var pair in relativeWeights)
    {
        if (randomValue < pair.Value)
        {
            return pair.Key;
        }
        runningSum += pair.Value;
    }
    throw new Exception("This should never happen.");    
}

用法:

public Enum PitchOutcome
{
    Ball,
    Strike,
    Hit
}

public Enum HitOutcome
{
    PopFly,
    HomeRun,
    Single,
}

var weights = new Dictionary<PitchOutcome, int>();
weights.Add(PitchOutcome.Ball, 40);
weights.Add(PitchOutcome.Strike, 30);
weights.Add(PitchOutcome.Hit, 30);
PitchOutcome randomOutcome = ChooseRandomOutcome(weights);
// it should be a Hit 30% of the time.

if (randomOutcome == PitchOutcome.Hit)
{

    var hitWeights = new Dictionary<HitOutcome, int>();
    hitWeights.Add(HitOutcome.PopFly, 50);
    hitWeights.Add(HitOutcome.HomeRun, 5);
    hitWeights.Add(HitOutcome.Single, 45);
    HitOutcome hitResult = ChooseRandomOutcome(hitWeights);
}