Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)

Paste

Pasted as C# by Ellerfanteller ( 8 years ago )
public int GetRandomWeightedIndex(int[] weights)
{
    // Get the total sum of all the weights.
    int weightSum = 0f;
    for (int i = 0; i < weights; ++i)
    {
        weightSum += weights[i];
    }
 
    // Step through all the possibilities, one by one, checking to see if each one is selected.
    int index = 0;
    int lastIndex = elementCount - 1;
    while (index < lastIndex)
    {
        // Do a probability check with a likelihood of weights[index] / weightSum.
        if (Random.Range(0, weightSum) < weights[index])
        {
            return index;
        }
 
        // Remove the last item from the sum of total untested weights and try again.
        weightSum -= weights[index++];
    }
 
    // No other item was selected, so return very last index.
    return index;
}

 

Revise this Paste

Your Name: Code Language: