赛马比赛:25匹马,5个赛道,选出跑的快的前几匹

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
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值