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.");
}
utilisation:
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);
}
« Il y a un mot beaucoup le seul un hasard "?! ?? – Stephen
question n'est pas claire – Adam
Je ne sais pas comment analyser "Il ya beaucoup de mot le seul un hasard ..." –