-
Notifications
You must be signed in to change notification settings - Fork 2
/
number.go
82 lines (73 loc) · 1.61 KB
/
number.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package utils
import (
"crypto/rand"
"math/big"
"strconv"
"strings"
"golang.org/x/exp/constraints"
)
// Min returns the minimum of two ordered values x and y.
func Min[T constraints.Ordered](x, y T) T {
if x < y {
return x
}
return y
}
// Max returns the maximum of two ordered values x and y.
func Max[T constraints.Ordered](x, y T) T {
if x > y {
return x
}
return y
}
// MinOf returns the minimum value in the ordered slice s.
// Returns the zero value of T if s is empty.
func MinOf[T constraints.Ordered](s []T) T {
if len(s) == 0 {
var zero T
return zero
}
m := s[0]
for _, v := range s {
if m > v {
m = v
}
}
return m
}
// MaxOf returns the maximum value in the ordered slice s.
// Returns the zero value of T if s is empty.
func MaxOf[T constraints.Ordered](s []T) T {
if len(s) == 0 {
var zero T
return zero
}
m := s[0]
for _, v := range s {
if m < v {
m = v
}
}
return m
}
// RandomInt64 generates a random int64 value between min and max.
func RandomInt64(min, max int64) int64 {
if min > max {
min, max = max, min
}
nBig, _ := rand.Int(rand.Reader, big.NewInt(max-min+1))
return nBig.Int64() + min
}
// RandomFloat64 generates a random float64 value between min and max.
func RandomFloat64(min, max float64) float64 {
if min > max {
min, max = max, min
}
nBig, _ := rand.Int(rand.Reader, big.NewInt(1<<62))
return (float64(nBig.Int64())/float64(1<<62))*(max-min) + min
}
// ParseFloat64 parses a string s as a float64 value.
func ParseFloat64(s string) (float64, error) {
s = strings.ReplaceAll(strings.TrimSpace(s), ",", "")
return strconv.ParseFloat(s, 64)
}