/*
* Pick a weighted item from a list of weighted numbers
* Args:
* const int items[]: The item array to pick from. The element value holds the weighted number
* const int len: the length ofthe array
*
* NOTE: arrays decay into pointers when passed into functions, so array length can't be calculated in the function.
* calculate the length outside the function and pass it in as an argument.
*/
int PickWeightedItem(const int items[], const int len)
{
int sum = 0;
int i = 0;
for(i = 0; i < len; i++)
{
sum += items[i];
}
srand(time(NULL));
int r = rand() % sum;
for(i = 0; i < len; i++)
{
if(r < items[i])
{
break;
}
r -= items[i];
}
return i;
}
[go to home page]