算法思想:对象权重 / 所有对象权重总和即每个对象相对应的概率
public static void main(String[] args) throws IOException {//初始化每个人的权重//1.从文件中导入数据到集合BufferedReader br = new BufferedReader(new FileReader("D:\\zzz.txt"));//创建学生类集合ArrayList<Student> list = new ArrayList<>();//循环导入String str;while ((str = br.readLine()) != null) {//依次将字符串的内容录入到Student集合中Student stu = new Student();String[] arr = str.split("-");stu.setName(arr[0]);stu.setSex(arr[1]);stu.setAge(Integer.parseInt(arr[2]));stu.setWeight(Double.parseDouble(arr[3]));list.add(stu);}br.close();System.out.println(list);//2.计算学生的抽中概率//每个人的权重除以所有人的权重总和即每个人的概率//定义权重总和double weight = 0;for (Student student : list) {weight += student.getWeight();}System.out.println(weight);//3.定义数组存放每个人的概率double[] arr = new double[list.size()];arr[0] = list.get(0).getWeight() / weight;for (int i = 1; i < list.size(); i++) {arr[i] = arr[i - 1] + list.get(i).getWeight() / weight;}for (double v : arr) {System.out.print(v + " ");}System.out.println();//4.开始抽签,生成0-1之间的随机数,在哪个范围就是哪个人double random = Math.random();System.out.println(random);//5.查找在哪个范围内,用Arrays工具类的二分查找快速遍历//该类的二分查找细节:若在查找范围中找到对应数据则返回对应数据下标,// 若在该插入位置中没有对应数据则该位置 负号下标 - 1//如:随机数0.4041886576958883此时应返回在[0.4-0.5)范围内的同学的下标,即4,而打印结果为-5,符合上面第二种情况,按照该规则计算数组下标即可// -下标 -1 = -5 => 下标 = 4int i = Arrays.binarySearch(arr, random);int index = -i -1;//6.打印抽到的同学,抽到的同学权重减半,减半后存入文件double halfWeight = list.get(index).getWeight() / 2;list.get(index).setWeight(halfWeight);System.out.println(list.get(index).getName());//7.依次将集合内容存回文件BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\zzz.txt"));for (Student student : list) {bw.write(student.toString());bw.newLine();}bw.close();}