From 9cd286fd92acfbdbdfb85c5af08a8843c05473ea Mon Sep 17 00:00:00 2001 From: ayflying Date: Thu, 13 Mar 2025 14:28:26 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=9D=83=E9=87=8D=E9=9A=8F?= =?UTF-8?q?=E6=9C=BA=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/random.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 tools/random.go diff --git a/tools/random.go b/tools/random.go new file mode 100644 index 0000000..d9803ba --- /dev/null +++ b/tools/random.go @@ -0,0 +1,45 @@ +package tools + +import ( + "math/rand" + "time" +) + +// RandomAll 按权重随机选取 N 个不重复的元素 +func (m *tools) RandomAll(data map[int]int, n int) []int { + if n > len(data) { + return nil + } + rand.Seed(time.Now().UnixNano()) + // 复制权重映射,避免修改原始数据 + remainingWeights := make(map[int]int) + for k, v := range data { + remainingWeights[k] = v + } + result := make([]int, 0, n) + + for i := 0; i < n; i++ { + totalWeight := 0 + // 计算剩余元素的总权重 + for _, weight := range remainingWeights { + totalWeight += weight + } + if totalWeight == 0 { + break + } + // 生成一个 0 到总权重之间的随机数 + randomNum := rand.Intn(totalWeight) + currentWeight := 0 + for key, weight := range remainingWeights { + currentWeight += weight + if randomNum < currentWeight { + // 将选中的元素添加到结果切片中 + result = append(result, key) + // 从剩余权重映射中移除选中的元素 + delete(remainingWeights, key) + break + } + } + } + return result +}