From 15792c592835950df7b685286afb624e159224b9 Mon Sep 17 00:00:00 2001 From: Ray Greenwell Date: Wed, 5 Mar 2003 02:50:28 +0000 Subject: [PATCH] added getWeightedIndex(). git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@2298 542714f4-19e9-0310-aa3c-eee0fc999fb1 --- src/java/com/threerings/util/RandomUtil.java | 31 +++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/java/com/threerings/util/RandomUtil.java b/src/java/com/threerings/util/RandomUtil.java index 2114e1c32..b635d229c 100644 --- a/src/java/com/threerings/util/RandomUtil.java +++ b/src/java/com/threerings/util/RandomUtil.java @@ -1,8 +1,10 @@ // -// $Id: RandomUtil.java,v 1.5 2002/04/15 18:18:20 mdb Exp $ +// $Id: RandomUtil.java,v 1.6 2003/03/05 02:50:28 ray Exp $ package com.threerings.util; +import com.samskivert.util.IntListUtil; + import java.util.Random; /** @@ -36,4 +38,31 @@ public class RandomUtil { return rand.nextFloat() * high; } + + /** + * Pick a random index from the array, weighted by the value of the + * corresponding array element. + * + * @param weights an array of positive integers. + * + * For example, passing in {1, 0, 3, 4} will return + * + * + * + *
01/8th of the time
1never
23/8th of the time
3half of the time
+ */ + public static int getWeightedIndex (int[] weights) + { + int pick = getInt(IntListUtil.sum(weights)); + for (int ii=0, nn=weights.length; ii < nn; ii++) { + pick -= weights[ii]; + if (pick < 0) { + return ii; + } + } + + // Impossible! + Log.logStackTrace(new Throwable()); + return 0; + } }