Research micro-channel assignment Golang red version of the algorithm

Today, look at the distribution of red envelopes, red envelopes micro-channel allocation algorithm reference circulating a few years ago, and today a version with Golang achieve, and verify the test results.

Random algorithm micro-letter envelopes is how to achieve? https://www.zhihu.com/question/22625187

Red core algorithm

分配:红包里的金额怎么算?为什么出现各个红包金额相差很大?
答:随机,额度在0.01和(剩余平均值*2)之间

Each split red, the amount ranges between 0.01 [2] * average residual, it is a wonderful design.
Such as hair 100, a total of 10 red hair, then the average value of $ 10, the first split out of the red line fluctuated between 0.01 yuan to 20 members, you can not ensure that a person picking up the whole red case, since the maximum residual is 2 times the average.
0.1 yuan such as hair, a total of 10 red hair, each 0.01 yuan, which would not have a random algorithm, direct it evenly.

No bb, show your code!

Design red envelope structure

//reward.go
//红包
type Reward struct {
    Count          int   //个数
    Money          int   //总金额(分)
    RemainCount    int   //剩余个数
    RemainMoney    int   //剩余金额(分)
    BestMoney int   //手气最佳金额
    BestMoneyIndex int   //手气最佳序号
    MoneyList      []int //拆分列表
}
  • I am here to do with the amount calculated int integer, floating-point precision to avoid problems when displayed in addition to 100, the unit is the yuan.

The core algorithm randomly assigned red envelopes

//reward.go
// 抢红包
func GrabReward(reward *Reward) int {
    if reward.RemainCount <= 0 {
        panic("RemainCount <= 0")
    }
    //最后一个
    if reward.RemainCount - 1 == 0 {
        money := reward.RemainMoney
        reward.RemainCount = 0
        reward.RemainMoney = 0
        return money
    }`
    //是否可以直接0.01
    if (reward.RemainMoney / reward.RemainCount) == 1 {
        money := 1
        reward.RemainMoney -= money
        reward.RemainCount--
        return money
    }

    //红包算法参考 https://www.zhihu.com/question/22625187
    //最大可领金额 = 剩余金额的平均值x2 = (剩余金额 / 剩余数量) * 2
    //领取金额范围 = 0.01 ~ 最大可领金额
    maxMoney := int(reward.RemainMoney / reward.RemainCount) * 2
    rand.Seed(time.Now().UnixNano())
    money := rand.Intn(maxMoney)
    for money == 0 {
        //防止零
        money = rand.Intn(maxMoney)
    }
    reward.RemainMoney -= money
    //防止剩余金额负数
    if reward.RemainMoney < 0 {
        money += reward.RemainMoney
        reward.RemainMoney = 0
        reward.RemainCount = 0
    } else {
        reward.RemainCount--
    }
    return money
}

After the allocation algorithm is complete, verify, verification unit testing approach

//reward_test.go
func TestGrabReward2(t *testing.T) {
    chanReward := make(chan Reward)
    rand.Seed(time.Now().UnixNano())
    go func(){
        //随机生成1000个红包
        for i:=0; i < 1000; i++  {
            //随机红包个数 1~50
            count := rand.Intn(50) + 1
            //随机红包总金额 1~100元
            money := rand.Intn(10000) + 100

            avg := money / count
            for avg == 0 {
                //保证金额足够分配
                count = rand.Intn(50) + 1
                money = rand.Intn(10000) + 100
                avg = money / count
            }
            reward := Reward{Count: count, Money: money,
                RemainCount: count, RemainMoney: money}

            chanReward <- reward
        }
        close(chanReward)
    }()

    //打印拆包列表,带手气最佳
    for reward := range chanReward {
        for i := 0; reward.RemainCount > 0; i++ {
            money := GrabReward(&reward)
            if money > reward.BestMoney {
                reward.BestMoneyIndex, reward.BestMoney = i, money
            }
            reward.MoneyList = append(reward.MoneyList, money)
        }
        t.Logf("总个数:%d, 总金额:%.2f", reward.Count, float32(reward.Money)/100)
        for i := range reward.MoneyList {
            money := reward.MoneyList[i]
            isBest := ""
            if reward.BestMoneyIndex == i {
                isBest = " ** 手气最佳"
            }
            t.Logf("money_%d : (%.2f)%s\n", i+1, float32(money)/100, isBest)
        }
        t.Log("-------")
    }

}

operation result

    reward_test.go:106: 总个数:7, 总金额:86.59
    reward_test.go:113: money_1 : (16.29)
    reward_test.go:113: money_2 : (4.93)
    reward_test.go:113: money_3 : (22.89) ** 手气最佳
    reward_test.go:113: money_4 : (3.17)
    reward_test.go:113: money_5 : (20.51)
    reward_test.go:113: money_6 : (0.12)
    reward_test.go:113: money_7 : (18.68)
    reward_test.go:115: -------
    reward_test.go:106: 总个数:10, 总金额:53.79
    reward_test.go:113: money_1 : (3.56)
    reward_test.go:113: money_2 : (6.39)
    reward_test.go:113: money_3 : (0.36)
    reward_test.go:113: money_4 : (2.60)
    reward_test.go:113: money_5 : (10.11)
    reward_test.go:113: money_6 : (5.76)
    reward_test.go:113: money_7 : (2.84)
    reward_test.go:113: money_8 : (14.04) ** 手气最佳
    reward_test.go:113: money_9 : (1.95)
    reward_test.go:113: money_10 : (6.18)
    reward_test.go:115: -------

Performance Testing

//性能测试
func BenchmarkGrabReward(b *testing.B) {
    chanReward := make(chan *Reward, b.N)
    rand.Seed(time.Now().UnixNano())
    go func(){
        //随机生成红包
        for i:=0; i < b.N; i++  {
            //随机红包个数 1~50
            count := rand.Intn(50) + 1
            //随机红包总金额 1~100元
            money := rand.Intn(10000) + 100

            avg := money / count
            for avg == 0 {
                //保证金额足够分配
                count = rand.Intn(50) + 1
                money = rand.Intn(10000) + 100
                avg = money / count
            }
            reward := Reward{Count: count, Money: money,
                RemainCount: count, RemainMoney: money}

            chanReward <- &reward
        }
        close(chanReward)
    }()

    //打印拆包列表,带手气最佳
    for reward := range chanReward {
        for i := 0; reward.RemainCount > 0; i++ {
            money := GrabReward(reward)
            if money > reward.BestMoney {
                reward.BestMoneyIndex, reward.BestMoney = i, money
            }
            reward.MoneyList = append(reward.MoneyList, money)
        }
        _ = fmt.Sprintf("总个数:%d, 总金额:%.2f", reward.Count, float32(reward.Money)/100)
        for i := range reward.MoneyList {
            money := reward.MoneyList[i]
            isBest := ""
            if reward.BestMoneyIndex == i {
                isBest = " ** 手气最佳"
            }
            _ = fmt.Sprintf("money_%d : (%.2f)%s\n", i+1, float32(money)/100, isBest)
        }
    }
}

Performance Test Results

BenchmarkGrabReward-8           4461        244842 ns/op
//4核8线的CPU运运行4461次,平均每次244842纳秒=0.244842毫秒

Performance can be said to be very good, because this test is a pure in-memory computing, there is no network IO, no storage disk write purely for verification algorithm, so performance is very high.
carry out!

Guess you like

Origin www.cnblogs.com/imbin/p/12320661.html