欢迎来到cool的博客
7

Music box

Click to Start

点击头像播放音乐
新博客链接

golang 根据分数计算排名,同分数排名相同

package main

import (
    "fmt"
    "sort"
)

type userInfo struct {
    Uid   int64 //uid
    Score int64 //分数
    Rank  int   //排名
}

type Score []userInfo

func (s Score) Len() int      { return len(s) }
func (s Score) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s Score) Less(i, j int) bool { return s[i].Score > s[j].Score } // 从大到小排序

func main()  {
    users := []userInfo{}
    scores := []int64{0, 2, 2, 3, 0, 0, 0, 0, 0, 0,0}
    fmt.Println(scores)
    for i := 1; i <= 10; i++ {
        users = append(users, userInfo{
            Uid:   int64(i),
            Score: scores[i],
        })
    }

    sort.Sort(Score(users))
    fmt.Printf("%+v \n",users)

    res := ReckonRank(users)
    for _,v := range res {
        fmt.Printf("user %+v \n",v)
    }

    fmt.Println(4294967295 == 0xffffffff)
}

func ReckonRank(users []userInfo) (usersInfo []userInfo) {
    index := 0          //排名
    var lastScore int64 //上一次分数
    usersInfo = make([]userInfo, 0)
    for _, user := range users {
        if user.Score != lastScore || (user.Score == 0 && index == 0) {
            index ++
            lastScore = user.Score
        }
        usersInfo = append(usersInfo, userInfo{
            Uid:   user.Uid,
            Score: user.Score,
            Rank:  index,
        })
    }

    return
}

返回列表