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(10,99) will most probably (%99) return 1
since 99 is the second parameter.
* chooseWithChance(99,1) will most probably (%99) return 0
since 99 is the first parameter * 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];
}
int random = new Random(DateTime.Now.Millisecond)double randomDouble = random.NextNextDouble(sumOfChances); * sumOfChances;
while ((randomsumOfChances -=args[argCount-1])> 0randomDouble)
{
{
argCount--;
sumOfChances -= args[argCount -1];
argCount--;
}
return argCount-1;
}
string[] fruits = new string[] { "apple", "orange", "lemon" };
int choosenOne = chooseWithChance(498,21,1);
Console.WriteLine(fruits[choosenOne]);
if you give weight as (1,1,98) itThe above code will most probably (%98) return 20 which is index for 'lemon''apple' for yourthe given array.
Also, this code tests the method provided above:
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);
It gives an output something like that:
Start...
Head count:52
Tails count:48