package com.example.classroomattendance.service; import com.example.classroomattendance.model.Student; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Random; @Service public class StudentService { private List students = new ArrayList<>(); private Random random = new Random(); public void addStudents(List studentList) { students.addAll(studentList); } public Student pickRandomStudent() { if (students.isEmpty()) { return null; } // 计算所有学生的总权重 double totalWeight = 0; for (Student student : students) { totalWeight += getWeight(student); } // 随机选择权重范围内的值 double randomValue = random.nextDouble() * totalWeight; // 选取符合该随机值的学生 for (Student student : students) { randomValue -= getWeight(student); if (randomValue <= 0) { return student; } } // 防止极端情况下返回最后一个学生 return students.get(students.size() - 1); } // 获取学生的权重,积分越高权重越低 private double getWeight(Student student) { return 1.0 / (student.getPoints() + 1.0); // 防止分母为0 } public void updateStudentPoints(Long id, double points) { for (Student student : students) { if (student.getId().equals(id)) { student.setPoints(student.getPoints() + points); break; } } } public List getAllStudents() { return students; } }