-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: random 包新增 Dice 掷骰子和 Probability 概率函数
- Loading branch information
1 parent
ace17a6
commit d9d0392
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | ||
} |