Skip to content

Commit

Permalink
feat: random 包新增 Dice 掷骰子和 Probability 概率函数
Browse files Browse the repository at this point in the history
  • Loading branch information
kercylan98 committed Aug 2, 2023
1 parent ace17a6 commit d9d0392
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
16 changes: 16 additions & 0 deletions utils/random/dice.go
Original file line number Diff line number Diff line change
@@ -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)
}
36 changes: 36 additions & 0 deletions utils/random/probability.go
Original file line number Diff line number Diff line change
@@ -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")
}

0 comments on commit d9d0392

Please sign in to comment.