This class uses the integerweightrandom class mentioned earlier;
Example:
Given that "A" has a weight of 100 and "B" has a weight of 50, the probability of "a" is greater when getnextstring () is used;
Package Org. xiazdong. util;/* specify a string set, set the weight of each string, and return a random string */public class stringrandom {private string [] datas; private integerweightrandom random = new integerweightrandom (); public stringrandom (string [] datas) {This. datas = datas;} public void setstringweight (INT weight, int idx) {If (datas. length> idx) random. addweightnumber (weight, idx);} Public String getnextstring () {int idx = random. getnextint (); Return datas [idx] ;}}
Test class:
package test.org.xiazdong.util;import org.junit.Test;import org.xiazdong.util.StringRandom;import junit.framework.TestCase;public class StringRandomTest extends TestCase {@Testpublic void testGetNextString() {StringRandom random = new StringRandom(new String[] { "a", "b", "c" });random.setStringWeight(10, 0);random.setStringWeight(20, 1);random.setStringWeight(30, 2);for (int i = 0; i < 10; i++)System.out.println(random.getNextString());}}