Java Weighted random number implementation

Source: Internet
Author: User


Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.Random;

public class Test1 {

String can be of any type or can be custom type
Static map<string, integer> Keychancemap = new hashmap<string, integer> ();
static {
Keychancemap.put ("Occurrence ratio of 10", 10);
Keychancemap.put ("Occurrence ratio of 40", 4);
Keychancemap.put ("Occurrence ratio of 20", 2);
Keychancemap.put ("Occurrence ratio of 10", 1);
Keychancemap.put ("Occurrence ratio of 30", 3);
}

public static void Main (string[] args) {
map<string, integer> count = new hashmap<string, integer> ();
for (int i = 0; i < 100000; i++) {

String item = chanceselect (KEYCHANCEMAP);

if (Count.containskey (item)) {
Count.put (item, Count.get (item) + 1);
} else {
Count.put (item, 1);
}
}

For (String Id:count.keySet ()) {
System.out.println (id + "\ t appears" + Count.get (ID) + "Times");
}
}

public static String Chanceselect (map<string, integer> keychancemap) {
if (Keychancemap = = NULL | | keychancemap.size () = = 0)
return null;

Integer sum = 0;
For (Integer value:keyChanceMap.values ()) {
sum + = value;
}
Starting from 1
Integer rand = new Random (). Nextint (sum) + 1;

For (map.entry<string, integer> entry:keyChanceMap.entrySet ()) {
Rand =rand-entry.getvalue ();
Selected
if (Rand <= 0) {
String item = Entry.getkey ();
return item;
}
}

return null;
}
}

Java Weighted random number implementation

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.