Dieser Kern tut genau das, wonach Sie fragen.
public static Random random = new Random(DateTime.Now.Millisecond);
public int chooseWithChance(params int[] args)
{
/*
* This method takes number of chances and randomly chooses
* one of them considering their chance to be choosen.
* e.g.
* chooseWithChance(0,99) will most probably (%99) return 1
* chooseWithChance(99,1) will most probably (%99) return 0
* chooseWithChance(0,100) will always return 1.
* chooseWithChance(100,0) will always return 0.
* chooseWithChance(67,0) will always return 0.
*/
int argCount = args.Length;
int sumOfChances = 0;
for (int i = 0; i < argCount; i++) {
sumOfChances += args[i];
}
double randomDouble = random.NextDouble() * sumOfChances;
while (sumOfChances > randomDouble)
{
sumOfChances -= args[argCount -1];
argCount--;
}
return argCount-1;
}
du kannst es so benutzen:
string[] fruits = new string[] { "apple", "orange", "lemon" };
int choosenOne = chooseWithChance(98,1,1);
Console.WriteLine(fruits[choosenOne]);
Der obige Code wird höchstwahrscheinlich (% 98) 0 zurückgeben, was der Index für 'apple' für das angegebene Array ist.
Außerdem testet dieser Code die oben bereitgestellte Methode:
Console.WriteLine("Start...");
int flipCount = 100;
int headCount = 0;
int tailsCount = 0;
for (int i=0; i< flipCount; i++) {
if (chooseWithChance(50,50) == 0)
headCount++;
else
tailsCount++;
}
Console.WriteLine("Head count:"+ headCount);
Console.WriteLine("Tails count:"+ tailsCount);
Es gibt eine Ausgabe in etwa so:
Start...
Head count:52
Tails count:48