From 4d8d0f37887e42b9db7fd772ffe59fb034e24b2c Mon Sep 17 00:00:00 2001 From: ray Date: Fri, 29 Jun 2007 00:32:12 +0000 Subject: [PATCH] From Charlie Groves: - Added a version of getWeightedIndex() that takes a float[] the Random to use for picking. git-svn-id: https://samskivert.googlecode.com/svn/trunk@2119 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- src/java/com/samskivert/util/RandomUtil.java | 35 ++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/src/java/com/samskivert/util/RandomUtil.java b/src/java/com/samskivert/util/RandomUtil.java index 4ca99698..9765b809 100644 --- a/src/java/com/samskivert/util/RandomUtil.java +++ b/src/java/com/samskivert/util/RandomUtil.java @@ -69,9 +69,21 @@ public class RandomUtil */ public static float getFloat (float high) { - return rand.nextFloat() * high; + return getFloat(high, rand); } + /** + * Returns a pseudorandom, uniformly distributed float value between + * 0.0 (inclusive) and the specified value (exclusive). + * + * @param high the high value limiting the random number sought. + * @param r the random number generator to use + */ + public static float getFloat (float high, Random r) + { + return r.nextFloat() * high; + } + /** * Pick a random index from the array, weighted by the value of the * corresponding array element. @@ -120,6 +132,25 @@ public class RandomUtil * 3half of the time */ public static int getWeightedIndex (float[] weights) + { + return getWeightedIndex(weights, rand); + } + + /** + * 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, Random r) { float sum = 0.0f; for (int ii = 0; ii < weights.length; ii++) { @@ -132,7 +163,7 @@ public class RandomUtil if (sum <= 0.0) { return -1; } - float pick = getFloat(sum); + float pick = getFloat(sum, r); for (int ii=0, nn=weights.length; ii < nn; ii++) { pick -= weights[ii]; if (pick < 0.0) {