The following requirements:
20% probability to execute method A,
1% probability to execute method B,
29% probability to execute method C,
50% probability to execute method D
If you use statements such as if random numbers to judge, it may be very messy. I wrote a random distributor to standardize this operation. The code after using this distributor is as follows:
The code copy is as follows:
//Create a distributor
RandomDispatcher randomDispatcher = new RandomDispatcher();
//Set the probability of each event, note that the sum of the probability does not necessarily mean that the sum of the probability is 100
randomDispatcher.put(20, 1);
randomDispatcher.put(1, 2);
randomDispatcher.put(29, 3);
randomDispatcher.put(50, 4);
//random
int retIndex = randomDispatcher.random();
//Execute different methods according to random results
switch (retIndex) {
case 1:
System.out.println("do method A");
break;
case 2:
System.out.println("do method B");
break;
case 3:
System.out.println("do method C");
break;
case 4:
System.out.println("do method D");
break;
default:
break;
}