开发者

Simulate a computed percentage based on another percentage

I'm trying to make a simulator base on percent and being changed by an overall ... what is the best way to do it?

We want to simulate, for example, a swing. 20% to calculate something as a result of the list overall hitter and pitcher and determine whether or not he hits the ball. So if he hits th开发者_如何学JAVAe ball, is he made a home run, a foul ball, a hit ... etc.

Thanks


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.");    
}

usage:

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜