Return random `list` item by its `weight`
Unity3D 2014. 11. 5. 20:43http://programmers.stackexchange.com/questions/150616/return-random-list-item-by-its-weight
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 99 is the second parameter.
* chooseWithChance(99,1) will most probably (%99) return 0 since 99 is the first parameter.
*/
int argCount = args.Length;
int sumOfChances = 0;
for (int i = 0; i < argCount; i++) {
sumOfChances += args[i];
}
int random = new Random(DateTime.Now.Millisecond).Next(sumOfChances);
while ((random -=args[argCount-1])> 0)
{
argCount--;
sumOfChances -= args[argCount -1];
}
return argCount-1;
}
string[] fruits = new string[] { "apple", "orange", "lemon" };
int choosenOne = chooseWithChance(4,2,1);
Console.WriteLine(fruits[choosenOne]);
'Unity3D' 카테고리의 다른 글
유니티의 iOS 빌드는 왜 다른가? (0) | 2014.11.25 |
---|---|
Excel to json converter (0) | 2014.11.25 |
unity3d Magnetic move particles (0) | 2014.11.05 |
Texture size and performance (0) | 2014.10.02 |
Execution Order of Event Functions (0) | 2014.07.25 |