Added float-based weighted random selection function.

git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@3851 542714f4-19e9-0310-aa3c-eee0fc999fb1
This commit is contained in:
Mike Thomas
2006-02-14 21:46:53 +00:00
parent ccce88790a
commit 402de06e07
+41 -1
View File
@@ -76,7 +76,7 @@ public class RandomUtil
* Pick a random index from the array, weighted by the value of the
* corresponding array element.
*
* @param weights an array of positive integers.
* @param weights an array of non-negative integers.
* @return an index into the array, or -1 if the sum of the weights
* is less than 1.
*
@@ -105,6 +105,46 @@ public class RandomUtil
return 0;
}
/**
* Pick a random index from the array, weighted by the value of the
* corresponding array element.
*
* @param weights an array of non-negative floats.
* @return an index into the array, or -1 if the sum of the weights
* is less than or equal to 0.0 or any individual element is negative.
*
* For example, passing in {0.2, 0.0, 0.6, 0.8} will return
* <table><tr><td>0</td><td>1/8th of the time</td></tr>
* <tr><td>1</td><td>never</td></tr>
* <tr><td>2</td><td>3/8th of the time</td></tr>
* <tr><td>3</td><td>half of the time</td></tr></table>
*/
public static int getWeightedIndex (float[] weights)
{
float sum = 0.0f;
for (int ii = 0; ii < weights.length; ii++) {
if (weights[ii] < 0.0f) {
return -1;
}
sum += weights[ii];
}
if (sum <= 0.0) {
return -1;
}
float pick = getFloat(sum);
for (int ii=0, nn=weights.length; ii < nn; ii++) {
pick -= weights[ii];
if (pick < 0.0) {
return ii;
}
}
// Impossible!
Log.logStackTrace(new Throwable());
return 0;
}
/**
* Picks a random object from the supplied array of values. Even
* weight is given to all elements of the array.