wp-go/helper/number/number.go

97 lines
1.4 KiB
Go
Raw Permalink Normal View History

2023-02-01 15:52:09 +00:00
// Package number
// 使用随机数时需要先 调用 rand.seed()函数
2023-01-21 11:31:23 +00:00
package number
import (
"fmt"
"math/rand"
)
type IntNumber interface {
~int | ~int64 | ~int32 | ~int8 | ~int16 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}
2023-01-27 15:48:48 +00:00
type Number interface {
IntNumber | ~float64 | ~float32
}
2023-01-21 11:31:23 +00:00
func Range[T IntNumber](start, end, step T) []T {
if step == 0 {
panic("step can't be 0")
}
l := int((end-start+1)/step + 1)
if l < 0 {
l = 0 - l
}
r := make([]T, 0, l)
for i := start; ; {
r = append(r, i)
i = i + step
if (step > 0 && i > end) || (step < 0 && i < end) {
break
}
}
return r
}
2023-01-27 15:48:48 +00:00
// Rand 都为闭区间 [start,end]
2023-01-21 11:31:23 +00:00
func Rand[T IntNumber](start, end T) T {
end++
return T(rand.Int63n(int64(end-start))) + start
}
2023-01-27 15:48:48 +00:00
func Min[T Number](a ...T) T {
2023-01-21 11:31:23 +00:00
min := a[0]
for _, t := range a {
if min > t {
min = t
}
}
return min
}
2023-01-27 15:48:48 +00:00
func Max[T Number](a ...T) T {
2023-01-21 11:31:23 +00:00
max := a[0]
for _, t := range a {
if max < t {
max = t
}
}
return max
}
2023-01-27 15:48:48 +00:00
func Sum[T Number](a ...T) T {
2023-01-21 11:31:23 +00:00
s := T(0)
for _, t := range a {
s += t
}
return s
}
2023-01-27 15:48:48 +00:00
func Add[T Number](i, j T) T {
return i + j
}
2023-01-28 13:38:34 +00:00
func Sub[T Number](i, j T) T {
return i - j
}
2023-01-27 15:48:48 +00:00
func ToString[T Number](n T) string {
2023-01-21 11:31:23 +00:00
return fmt.Sprintf("%v", n)
}
2023-01-27 15:48:48 +00:00
func Abs[T Number](n T) T {
if n >= 0 {
return n
}
return -n
}
2023-01-28 13:38:34 +00:00
func Mul[T Number](i, j T) T {
return i * j
}
func Divide[T Number](i, j T) T {
return i / j
}