golang 結構體自定義排序 + 按照分數算排名同分數排名一樣

kenuo發表於2019-02-14

直接上程式碼

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
}

by JeffreyBool blog :point_right: link

相關文章