miércoles, 2 de julio de 2014

Selección aleatoria con pesos

Tenemos el siguiente problema: Tenemos un conjunto y hemos de seleccionar aleatoriamente (función de probabilidad uniforme) un elemento de dicho conjunto, lo que ocurre es que cada elemento tiene un peso que lo hace más elegible es decir, tiene más papeletas.

La solución la tenemos en https://stackoverflow.com/questions/6737283/weighted-randomness-in-java

Item[] items = ...;

// Compute the total weight of all items together
double totalWeight = 0.0d;
for (Item i : items)
{
    totalWeight += i.getWeight();
}
// Now choose a random item
int randomIndex = -1;
double random = Math.random() * totalWeight;
for (int i = 0; i < items.length; ++i)
{
    random -= items[i].getWeight();
    if (random <= 0.0d)
    {
        randomIndex = i;
        break;
    }
}
Item myRandomItem = items[randomIndex];
Si vamos a usar reiteradamente Math.random(), es más eficiente usar el objeto Random y llamar a nextDouble(), pues Math.random() usa internamente Random.nextDouble();

Más sobre esto en:
http://www.aprenderaprogramar.es/...
https://stackoverflow.com/questions/738629/math-random-versus-random-nextintint