From 8d1ddb46c45a37538b50d12baa58f7bf0d488027 Mon Sep 17 00:00:00 2001 From: pjmw9izve <2308014474@qq.com> Date: Sun, 6 Oct 2024 13:09:45 +0800 Subject: [PATCH] ADD file via upload --- randomSelect.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 randomSelect.js diff --git a/randomSelect.js b/randomSelect.js new file mode 100644 index 0000000..ffda649 --- /dev/null +++ b/randomSelect.js @@ -0,0 +1,45 @@ +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 };