Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
chooseWithChance.cs - Choose a random member of a set with a given chance of selection.
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(1,99) will most probably (%99) return 1 since index of 99 is 1
* chooseWithChance(99,1) will most probably (%99) return 0 since index of 99 is 0
* chooseWithChance(0,100) will always return 1.
* chooseWithChance(10,10,80) will most probably (%80) return 2 since index of 80 is 2
*/
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;
}
@ramazanpolat

This comment has been minimized.

Copy link
Owner Author

@ramazanpolat ramazanpolat commented Jul 3, 2013

chooseWithChance(1,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(10,10,80) will most probably (%80) return 2 since 80 is the third parameter.

@MiraiTunga

This comment has been minimized.

Copy link

@MiraiTunga MiraiTunga commented Jun 19, 2015

Awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment