You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.6 KiB

2 months ago
const pool = require('../db');
async function selectStudent(req, res) {
try {
const connection = await pool.getConnection();
// 从数据库查询学生
const [students] = await connection.query('SELECT * FROM students');
// 计算权重的总和(使用 softmax 权重计算)
const totalWeight = students.reduce((acc, student) => acc + Math.exp(-student.score), 0);
// 将每个学生的权重归一化
const weightedStudents = students.map(student => ({
student,
weight: Math.exp(-student.score) / totalWeight,
}));
// 生成随机数
const random = Math.random(); // 介于 0 和 1 之间
let sum = 0; // 用于累加权重
let selectedStudent = null;
// 遍历加权后的学生,累加权重,并判断随机数落在哪个学生的区间
for (let i = 0; i < weightedStudents.length; i++) {
sum += weightedStudents[i].weight; // 累加当前学生的权重
if (random <= sum) { // 如果随机数小于或等于当前的累积权重
selectedStudent = weightedStudents[i].student; // 选中该学生
break; // 找到后立即退出循环
}
}
if (selectedStudent) {
res.send({ student: selectedStudent });
} else {
res.status(404).send({ message: '无学生数据' });
}
connection.release();
} catch (error) {
res.status(500).send({ error: '随机选择学生失败' });
}
}
module.exports = { selectStudent };