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{2, 3, 4, 4, 5, 8, 8, 9, 1, 10,1}
    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)
    }
}

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

    return
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
by JeffreyBool blog :point_right: link
JeffreyBool
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!