我试图做一个模拟器基于百分比,并由一个整体改变...什么是最好的方式来做到这一点?根据另一个百分比模拟一个计算的百分比
我们想模拟,例如,一个秋千。 20%来计算某些事情是由于整个击球手和投手的结果,并确定他是否击球。所以,如果他打的球,为他做了一个本垒打,一个犯规球,命中...等
感谢
我试图做一个模拟器基于百分比,并由一个整体改变...什么是最好的方式来做到这一点?根据另一个百分比模拟一个计算的百分比
我们想模拟,例如,一个秋千。 20%来计算某些事情是由于整个击球手和投手的结果,并确定他是否击球。所以,如果他打的球,为他做了一个本垒打,一个犯规球,命中...等
感谢
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);
}
我已经尝试过这一点,对于这个例子,如果我比较MLB,本垒打来了太多时间。比如说,有5倍到10倍的时间。如果它只有失败或成功,我该怎么办?让我们说:这是一个犯规球,本垒打,抓球等吗? – 2010-11-01 19:27:53
@Simon我认为你将不得不更清楚你在找什么。 – McKay 2010-11-01 19:34:33
@McKay:抱歉,我试过了,但我平时说法语,很难解释这个难题......我试过了,但看起来我失败了...... – 2010-11-01 19:37:06
“有很多MOT唯一的一个随机“?!?? – Stephen 2010-11-01 19:23:39
问题不清楚 – Adam 2010-11-01 19:24:56
我不知道该怎么解析“有很多mot只是一个随机......” – 2010-11-01 19:26:32