From d9d0392db39cff582d1af1e78286d62570bb1979 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Wed, 2 Aug 2023 15:10:32 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20random=20=E5=8C=85=E6=96=B0=E5=A2=9E=20?= =?UTF-8?q?Dice=20=E6=8E=B7=E9=AA=B0=E5=AD=90=E5=92=8C=20Probability=20?= =?UTF-8?q?=E6=A6=82=E7=8E=87=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/random/dice.go | 16 ++++++++++++++++ utils/random/probability.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 utils/random/dice.go create mode 100644 utils/random/probability.go diff --git a/utils/random/dice.go b/utils/random/dice.go new file mode 100644 index 0000000..3d23842 --- /dev/null +++ b/utils/random/dice.go @@ -0,0 +1,16 @@ +package random + +// Dice 掷骰子 +// - 常规掷骰子将返回 1-6 的随机数 +func Dice() int { + return Int(1, 6) +} + +// DiceN 掷骰子 +// - 与 Dice 不同的是,将返回 1-N 的随机数 +func DiceN(n int) int { + if n <= 1 { + return 1 + } + return Int(1, n) +} diff --git a/utils/random/probability.go b/utils/random/probability.go new file mode 100644 index 0000000..a9763ab --- /dev/null +++ b/utils/random/probability.go @@ -0,0 +1,36 @@ +package random + +// Probability 输入一个概率,返回是否命中 +// - 当 full 不为空时,将以 full 为基数,p 为分子,计算命中概率 +func Probability(p int, full ...int) bool { + var f = 100 + if len(full) > 0 { + f = full[0] + if f <= 0 { + f = 100 + } else if p > f { + return true + } + } + r := Int(1, f) + return r <= p +} + +// ProbabilityChooseOne 输入一组概率,返回命中的索引 +func ProbabilityChooseOne(ps ...int) int { + var f int + for _, p := range ps { + f += p + } + if f <= 0 { + panic("total probability less than or equal to 0") + } + r := Int(1, f) + for i, p := range ps { + if r <= p { + return i + } + r -= p + } + panic("probability choose one error") +}