Skip to content

Instantly share code, notes, and snippets.

@ramazanpolat
Last active December 9, 2017 21:40
Show Gist options
  • Save ramazanpolat/5923486 to your computer and use it in GitHub Desktop.
Save ramazanpolat/5923486 to your computer and use it in GitHub Desktop.
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;
}
@MiraiTunga
Copy link

Awesome!

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