package answer_service import ( "evening_detective_server/internal/services/game_model" "sort" "evening_detective_server/internal/modules/storytelling" ) type TeamResult struct { Team *game_model.Team Answers []AnswerScore TotalScore int Place int } type GameResults struct { Questions []*storytelling.Question Teams []TeamResult } // rankTeams. func buildTeamResults( questions []*storytelling.Question, teams []*game_model.Team, answerByTeamAndCode map[int]map[string]AnswerScore, ) []TeamResult { res := make([]TeamResult, 0, len(teams)) for _, team := range teams { byCode := answerByTeamAndCode[team.ID] answers := make([]AnswerScore, 0, len(questions)) total := 0 for _, question := range questions { answer, ok := byCode[question.Code] if !ok { answers = append(answers, AnswerScore{QuestionCode: question.Code}) continue } answers = append(answers, answer) if answer.Score != nil { total += *answer.Score } } res = append(res, TeamResult{ Team: team, Answers: answers, TotalScore: total, }) } return res } func rankTeams(rows []TeamResult) []TeamResult { sorted := make([]TeamResult, len(rows)) copy(sorted, rows) sort.SliceStable(sorted, func(i, j int) bool { a, b := sorted[i], sorted[j] if a.TotalScore != b.TotalScore { return a.TotalScore > b.TotalScore } if a.Team.ActionsCount != b.Team.ActionsCount { return a.Team.ActionsCount < b.Team.ActionsCount } return a.Team.ID < b.Team.ID }) place := 0 for i := range sorted { row := sorted[i] if i == 0 || row.TotalScore != sorted[i-1].TotalScore || row.Team.ActionsCount != sorted[i-1].Team.ActionsCount { place = i + 1 } sorted[i].Place = place } return sorted }