package main
import (
"fmt"
"math/rand"
"sort"
)
// 赛马
//@题目:有25匹马,5个赛道,选出跑的最快的前几匹。
//@思路:先将25匹马,分成5组,组内排序,倒序。 如[5, 4, 3, 2, 1]
// 将5组马,放到5个赛道中,组内跑的最快的在队首。
// 每个赛道跑的最快的进行比赛,就可选出跑的最快的那匹马。
// 将跑的最快的马剔除跑道,那个队伍第二快的和其他几个队伍第一快的比赛。选出第二...
func main() {
// 创建比赛
horseRace := NewHorseRace(25, 5)
fmt.Printf("%+v", horseRace)
// 按赛道分组,并第一次比赛
var playground Playground
for i := 0; i < len(horseRace.Horses); i += horseRace.Tracks {
r := Race{
Horses: horseRace.Horses[i : i+horseRace.Tracks],
}
r.Match()
playground.Races = append(playground.Races, r)
}
fmt.Println(playground)
// 第一次比赛
for i := 0; i < 25; i++ {
fmt.Println(i+1, ":", playground.GetNo1())
}
}
type HorseRace struct {
Horses []int // 马
Tracks int // 赛道数
}
// 赛道
type Race struct {
Horses []int // 待比赛的马
}
// 比赛
func (this *Race) Match() {
sort.Sort(sort.Reverse(sort.IntSlice(this.Horses)))
}
// 获得本赛道跑的最快的那匹马
func (this *Race) GetFastest() int {
if len(this.Horses) == 0 {
return -1
}
this.Match()
fastest := this.Horses[0]
this.Horses = this.Horses[1:]
return fastest
}
// 操场
type Playground struct {
Races []Race // 赛道
}
// 获得操场上的第一名,并从操场上移除
func (this *Playground) GetNo1() int {
var newRace Race
// 将每组跑的最快的放在赛道上比赛
for _, r := range this.Races {
newRace.Horses = append(newRace.Horses, r.Horses[0])
}
h := newRace.GetFastest()
// 将最快的马h从操场上移除
for i := 0; i < len(this.Races); i++ {
r := &this.Races[i]
if h == r.Horses[0] {
r.Horses = r.Horses[1:]
// 如果某个赛道没有马了,清除这个赛道
if len(r.Horses) == 0 {
this.Races = append(this.Races[:i], this.Races[i+1:]...)
}
break
}
}
return h
}
// 新建一场赛马比赛
// @num 马的数量
// @tracks 赛道数
func NewHorseRace(num, tracks int) HorseRace {
var horses []int
for i := 0; i < num; i++ {
horses = append(horses, rand.Intn(25))
}
horserace := HorseRace{
Horses: horses,
Tracks: tracks,
}
return horserace
}
赛马比赛:25匹马,5个赛道,选出跑的快的前几匹
最新推荐文章于 2021-04-18 16:01:27 发布