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