From 402de06e077012fb5385fa817a2eceb1d1a13b63 Mon Sep 17 00:00:00 2001 From: Mike Thomas Date: Tue, 14 Feb 2006 21:46:53 +0000 Subject: [PATCH] Added float-based weighted random selection function. git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@3851 542714f4-19e9-0310-aa3c-eee0fc999fb1 --- src/java/com/threerings/util/RandomUtil.java | 42 +++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/src/java/com/threerings/util/RandomUtil.java b/src/java/com/threerings/util/RandomUtil.java index 68dab06fc..6fbe59956 100644 --- a/src/java/com/threerings/util/RandomUtil.java +++ b/src/java/com/threerings/util/RandomUtil.java @@ -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 + * + * + * + *
01/8th of the time
1never
23/8th of the time
3half of the time
+ */ + 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.