package weight import ( "sort" ) // Weight 权重 type Weight struct { // 权重值 Value float64 // 权重名称 Name string } // WeightList 权重列表 type WeightList []Weight // Len 长度 func (w WeightList) Len() int { return len(w) } // Less 小于 func (w WeightList) Less(i, j int) bool { return w[i].Value < w[j].Value } // Swap 交换 func (w WeightList) Swap(i, j int) { w[i], w[j] = w[j], w[i] } // Sort 排序 func (w WeightList) Sort() { sort.Sort(w) } // WeightModel 权重模型 type WeightModel struct { // 权重列表 Weights WeightList // 权重总和 Total float64 } // NewWeightModel 创建权重模型 func NewWeightModel() *WeightModel { return &WeightModel{ Weights: make(WeightList, 0), } } // Add 添加权重 func (w *WeightModel) Add(name string, value float64) { w.Weights = append(w.Weights, Weight{ Name: name, Value: value, }) w.Total += value } // Get 获取权重 func (w *WeightModel) Get(name string) float64 { for _, weight := range w.Weights { if weight.Name == name { return weight.Value } } return 0 } // GetWeight 获取权重 func (w *WeightModel) GetWeight(name string) float64 { for _, weight := range w.Weights { if weight.Name == name { return weight.Value / w.Total } } return 0 } // GetWeightList 获取权重列表 func (w *WeightModel) GetWeightList() WeightList { w.Weights.Sort() return w.Weights } // GetWeightListByValue 获取权重列表 func (w *WeightModel) GetWeightListByValue() WeightList { w.Weights.Sort() return w.Weights } // GetWeightListByValueDesc 获取权重列表 func (w *WeightModel) GetWeightListByValueDesc() WeightList { w.Weights.Sort() return w.Weights } // GetWeightListByName 获取权重列表 func (w *WeightModel) GetWeightListByName() WeightList { w.Weights.Sort() return w.Weights } // GetWeightListByNameDesc 获取权重列表 func (w *WeightModel) GetWeightListByNameDesc() WeightList { w.Weights.Sort() return w.Weights } // GetWeightListByWeight 获取权重列表 func (w *WeightModel) GetWeightListByWeight() WeightList { w.Weights.Sort() return w.Weights } // GetWeightListByWeightDesc 获取权重列表 func (w *WeightModel) GetWeightListByWeightDesc() WeightList { w.Weights.Sort() return w.Weights }