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.

102 lines
2.1 KiB

package logic
import (
"main/dao/mysql"
"main/models"
"main/pkg/snowflake"
"main/utils"
"math/rand"
)
func GetAllStudentInfoLogic() (back *[]models.User, err error) {
return mysql.GetAllStudentInfo()
}
func GetOneRandomStudentInfoLogic() (info models.User, err error) {
back, err := mysql.GetOneRandomStudentInfo()
if err != nil {
return
}
info = *back
return
}
func GetOneStudentInfoAccordScoreLogic() (info models.User, err error) {
back, err := GetAllStudentInfoLogic()
if err != nil {
return
}
seed := snowflake.GenID()
info = WeightedRandomSelect(*back, seed)
return
}
func GetNStudentInfoAccordScoreLogic(p *models.ParamNum) (info []models.User, err error) {
back, err := GetAllStudentInfoLogic()
if err != nil {
return
}
if p.Num > len(*back) {
err = utils.ErrorBeyondNum
return
}
seed := snowflake.GenID()
for i := 0; i < p.Num; i++ {
getInfo := WeightedRandomSelect(*back, seed)
info = append(info, getInfo)
removeUser(*back, getInfo)
}
return
}
func GetTargetStudentInfoLogic(p *models.ParamUser) (info models.User, err error) {
back, err := mysql.GetTargetStudentInfo(p.User_id)
if err != nil {
return
}
info = *back
return
}
func ChangeStuScoreLogic(p *models.ParamUser) (user *models.UserScore, err error) {
user = new(models.UserScore)
user.User_id = p.User_id
user.User_score = p.User_score
err = mysql.ChangeStuScore(user)
return
}
func WeightedRandomSelect(users []models.User, seed int64) models.User {
totalWeight := 0.0
weights := make([]float64, len(users))
for i, user := range users {
if user.User_score == 0 {
weights[i] = 3
} else if user.User_score > 0 {
weights[i] = 1.0 / float64(user.User_score)
} else {
weights[i] = 0 - float64(user.User_score) + 3
}
totalWeight += weights[i]
}
rand.Seed(seed)
randomWeight := rand.Float64() * totalWeight
for i, user := range users {
if randomWeight < weights[i] {
return user
}
randomWeight -= weights[i]
}
return users[0]
}
func removeUser(users []models.User, user models.User) []models.User {
for i, u := range users {
if u.User_id == user.User_id {
return append(users[:i], users[i+1:]...)
}
}
return users
}