feat: 完成点名功能

backend/dev
Spark 1 month ago
parent 680ca6808f
commit fb4f781e56

@ -84,5 +84,18 @@ public class StudentController {
return Result.success();
}
@Operation(summary = "随机抽取一名学生")
@GetMapping("/rollcall")
public Result<Student> rollCall() {
Student stu = studentService.rollCall();
return Result.success(stu);
}
@Operation(summary = "更新积分")
@PutMapping("/points/{id}/{points}")
public Result updatePoints(@PathVariable Integer id, @PathVariable Double points) {
studentService.updatePoints(id, points);
return Result.success();
}
}

@ -21,8 +21,11 @@ public interface StudentService extends IService<Student> {
void save(StudentDTO studentDTO);
Student rollCall();
void importStudentsByExcel(MultipartFile file);
void exportStudentsToExcel(HttpServletResponse response);
void updatePoints(Integer id, Double points);
}

@ -127,6 +127,43 @@ public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
baseMapper.insert(student);
}
@Override
public Student rollCall() {
List<Student> studentList = this.list();
if (studentList.isEmpty()) {
throw new RuntimeException("学生列表为空");
}
// 找出最高积分,用于计算反向权重
final double maxPoints = studentList.stream()
.mapToDouble(Student::getPoints)
.max()
.orElse(0.0) + 1.0;
// 计算总的反向权重
double totalInverseWeights = studentList.stream()
.mapToDouble(student -> maxPoints - student.getPoints())
.sum();
// 生成一个0到总反向权重之间的随机数
Random random = new Random();
double randomValue = random.nextDouble() * totalInverseWeights;
// 使用累加器方法选择学生
double accumulatedWeight = 0;
for (Student student : studentList) {
// 计算该学生的反向权重
double inverseWeight = maxPoints - student.getPoints();
accumulatedWeight += inverseWeight;
if (accumulatedWeight >= randomValue) {
return student;
}
}
// 以防万一,返回最后一个学生
return studentList.get(studentList.size() - 1);
}
@Override
public void importStudentsByExcel(MultipartFile file) {
@ -232,4 +269,10 @@ public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
}
}
@Override
public void updatePoints(Integer id, Double points) {
Student student = baseMapper.selectById(id);
student.setPoints(student.getPoints() + points);
baseMapper.updateById(student);
}
}
Loading…
Cancel
Save