Update randomSelect.js

main
luoyonghuang 2 months ago
parent 873b9a982d
commit fcc3bda958

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

Loading…
Cancel
Save