You are currently viewing the GMLscripts.com static mirror. Forum access and script submissions are not available through this mirror.

Invert GMLscripts.com

random_weighted

This function randomly selects an index based on its probability relative to the probabilities of the other given indices. For instance, if the supplied probabilities are 1, 2, and 3, giving a chance ratio of n/6, where 6 is the sum of the probabilities, the first index will be returned 1/6 of the time, the second index will be returned 2/6 of the time, and the third index will be returned 3/6 of the time.

Click display to restart with new weights.Download
random_weighted(p0 [, p1, ..., pN])
Returns a randomly selected index based on their given relative probabilities.
COPY/// @func   random_weighted(p0 [, p1, ..., pN])
///
/// @desc   Returns a randomly selected index based on their given relative
///         probabilities. Any number of index probabilities can be supplied,
///         expressed by any positive numerical value including percentages.
///
///         eg. random_weighted(1,2,3) == 0: 1/6 of the time
///                                    or 1: 1/3 of the time
///                                    or 2: 1/2 of the time
///
/// @param  {real}      p0          first index probability
/// @param  {real}      p1...pN     additional probabilities
///
/// @return {real}      index of the selected probability
///
/// GMLscripts.com/license

function random_weighted() 
{
    var sum = 0;
    for (var i=0; i<argument_count; i++) {
        sum += argument[i];
    }
    var rnd = random(sum);
    for (var i=0; i<argument_count; i++) {
        if (rnd < argument[i]) return i;
        rnd -= argument[i];
    }
}

Contributors: xot

GitHub: View · Commits · Blame · Raw