Random acquisition of user-defined strings

Source: Internet
Author: User

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());}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.