列举多个例子生动形象的详细说明java中有概率的随机点名思路并给出代码及其注释
在Java中实现概率的随机点名,可以使用Random类来生成随机数,并结合概率的设定来决定点名的结果。下面是一个示例代码及其注释:
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
public class RandomRollCall {
public static void main(String[] args) {
// 创建一个Map来存储学生姓名和对应的概率
Map<String, Double> students = new TreeMap<>();
students.put("Alice", 0.2);
students.put("Bob", 0.3);
students.put("Charlie", 0.5);
// 计算每个学生的累积概率
double cumulativeProbability = 0.0;
for (String student : students.keySet()) {
cumulativeProbability += students.get(student);
students.put(student, cumulativeProbability);
}
// 生成一个随机数
Random random = new Random();
double randomNumber = random.nextDouble();
// 根据随机数的大小来确定点名结果
for (String student : students.keySet()) {
if (randomNumber <= students.get(student)) {
System.out.println(student + " is selected.");
break;
}
}
}
}
在上述代码中,首先创建了一个Map来存储学生姓名和对应的概率。然后,通过循环计算每个学生的累积概率,将其更新到Map中。接着,生成一个随机数,并根据随机数的大小确定点名结果。最后,输出被点到名的学生姓名。
注释部分详细解释了代码的逻辑。在示例中,Alice被设置为0.2的概率,Bob被设置为0.3的概率,Charlie被设置为0.5的概率。每个学生的累积概率分别为0.2、0.5和1.0。生成的随机数在0到1之间,根据这个随机数的大小来决定点名的结果
原文地址: https://www.cveoy.top/t/topic/i0tj 著作权归作者所有。请勿转载和采集!