← 中文资源

简体中文版本

用 sort.Search 校验单调性并匹配阶梯阈值

先用 sort.SliceIsSorted 验证阶梯表的升序单调不变量,再用 sort.Search 二分查找用量所属档位,显式处理边界与越界。

阅读英文原文

实现说明

活动部件是函数 lookupTier、main。 重复被限制在 for _, usage := range []int{0, 100, 101, 1500, 2500} 里——其余代码按顺序各跑一遍。

使用要点

  • 省略安装准备工作:示例用到的全部 API 全部随平台提供。
  • 每一步打印都带着自己的标签:usage=。
  • main 按顺序串起 lookupTier;运行文件就会把这个流程跑一遍。

常见问题

运行「用 sort.Search 校验单调性并匹配阶梯阈值」会打印什么?

运行文件本身,usage= 这些前缀各对应一段演示逻辑。

签名一览:func lookupTier(tiers []Tier, units int) (Tier, bool)

核心语句

for _, usage := range []int{0, 100, 101, 1500, 2500} {
	tier, ok := lookupTier(tiers, usage)
	if !ok {
		fmt.Printf("usage=%d -> enterprise quote (above %d)\n", usage, tiers[len(tiers)-1].MaxUnits)
		continue
	}
	fmt.Printf("usage=%d -> cap=%d unit_price=%d\n", usage, tier.MaxUnits, tier.Price)
}
return Tier{}, false
panic("tier thresholds must be sorted ascending")

代码示例

package main

import (
	"fmt"
	"sort"
)

type Tier struct {
	MaxUnits int
	Price    int
}

func lookupTier(tiers []Tier, units int) (Tier, bool) {
	if !sort.SliceIsSorted(tiers, func(i, j int) bool {
		return tiers[i].MaxUnits < tiers[j].MaxUnits
	}) {
		panic("tier thresholds must be sorted ascending")
	}
	idx := sort.Search(len(tiers), func(i int) bool {
		return tiers[i].MaxUnits >= units
	})
	if idx == len(tiers) {
		return Tier{}, false
	}
	return tiers[idx], true
}

func main() {
	tiers := []Tier{
		{MaxUnits: 100, Price: 10},
		{MaxUnits: 500, Price: 8},
		{MaxUnits: 2000, Price: 5},
	}
	for _, usage := range []int{0, 100, 101, 1500, 2500} {
		tier, ok := lookupTier(tiers, usage)
		if !ok {
			fmt.Printf("usage=%d -> enterprise quote (above %d)\n", usage, tiers[len(tiers)-1].MaxUnits)
			continue
		}
		fmt.Printf("usage=%d -> cap=%d unit_price=%d\n", usage, tier.MaxUnits, tier.Price)
	}
}