带权重的随机算法
假设有10名学生,其中5个男生,5个女生。
要求点到男生的概率为70%,女生的概率为30%。
给男生和女生设置权重,其中男生权重为7,女生权重为3。
public class Test02_case2 {
public static void main(String[] args) throws IOException {
//把文件中的学生全部读取出来放到集合中
ArrayList<String> infoList = new ArrayList<>();
//使用缓冲流读,因为可以一次读取一行
BufferedReader br = new BufferedReader(new FileReader("name_10.txt"));
String info;
while ((info = br.readLine()) != null) {
infoList.add(info);
}
ArrayList<Student> studentList = new ArrayList<>();
for (String s : infoList) {
String[] ss = s.split("-");
Student student = new Student(ss[0], ss[1], Integer.parseInt(ss[2]),Double.parseDouble(ss[3]));
studentList.add(student);
}
double sum = 0;
for (Student student : studentList) {
sum += student.getWeight();
}
double p1 = 5 * 7 / sum;
double p2 = 5 * 3 / sum;
double r = Math.random();
int boyCount = 0;
int girlCount = 0;
for (int i = 0; i < 1000000; i++) {
if (r <= 0.3) {
girlCount++;
} else {
boyCount++;
}
}
//统计概率
double p3 = (double) boyCount / 1000000;
double p4 = (double) girlCount / 1000000;
System.out.println(p1);
System.out.println(p2);
}
}
public class Test05 {
public static void main(String[] args) throws IOException {
//把文件中的学生全部读取出来放到集合中
ArrayList<String> infoList = new ArrayList<>();
//使用缓冲流读,因为可以一次读取一行
BufferedReader br = new BufferedReader(new FileReader("name_10_5.txt"));
String info;
while ((info = br.readLine()) != null) {
infoList.add(info);
}
//把属性封装到对象中,并把所有对象放到集合中去
ArrayList<Student> studentList = new ArrayList<>();
for (String s : infoList) {
String[] ss = s.split("-");
Student student = new Student(ss[0], ss[1], Integer.parseInt(ss[2]), Double.parseDouble(ss[3]));
studentList.add(student);
}
//计算权重总和
double sum = 0;
for (Student student : studentList) {
sum += student.getWeight();
}
//概率
double[] ww = new double[infoList.size()];
for (int i = 0; i < ww.length; i++) {
ww[i] = studentList.get(i).getWeight() / sum;
}
double[] proRange = new double[ww.length];
for (int i = 0; i < proRange.length; i++) {
if (i == 0) {
proRange[i] = ww[i];
} else {
proRange[i] = proRange[i - 1] + ww[i];
}
}
//随机点名
double r = Math.random();
System.out.println(r);
int i = Arrays.binarySearch(proRange, r);
int index = -(i + 1);
Student student = studentList.get(index);
System.out.println(student);
//将点到的学生权重/2
student.setWeight(student.getWeight() / 2);
//
System.out.println(student);
//将减半后的权重重新写回
BufferedWriter bw = new BufferedWriter(new FileWriter("name_10_5.txt"));
for (Student student1 : studentList) {
bw.write(student1.getName() + "-" + student1.getGender() + "-" + student1.getAge() + "-" + student1.getWeight());
bw.newLine();
}
bw.close();
}
}