added getWeightedIndex().
git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@2298 542714f4-19e9-0310-aa3c-eee0fc999fb1
This commit is contained in:
@@ -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;
|
package com.threerings.util;
|
||||||
|
|
||||||
|
import com.samskivert.util.IntListUtil;
|
||||||
|
|
||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -36,4 +38,31 @@ public class RandomUtil
|
|||||||
{
|
{
|
||||||
return rand.nextFloat() * high;
|
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
|
||||||
|
* <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 (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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user