-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice.go
76 lines (60 loc) · 1.29 KB
/
slice.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
package slice
import (
"errors"
"wangzugames.com/kumay/gameServer2/util/mathUtil"
)
//IsSliceEqual check if 2 slices are equal
func IsSliceEqual(a, b []byte) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
//RandomIntSlice returns new slice after random
func RandomIntSlice(src []int) ([]int, error) {
slen := len(src)
dst := make([]int, slen)
if slen == 0 {
return nil, errors.New("source slice len==0")
} else if slen == 1 {
copy(dst, src)
return dst, nil
}
//fill -1
for i := 0; i < slen; i++ {
dst[i] = -1
}
for i := 0; i < slen; i++ {
pos := mathUtil.RandomInt(0, len(src)-1)
dst[i] = src[pos]
src = append(src[:pos], src[pos+1:]...)
}
return dst, nil
}
func Contain(obj interface{}, target interface{}) (bool, error) {
targetValue := reflect.ValueOf(target)
switch reflect.TypeOf(target).Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < targetValue.Len(); i++ {
if targetValue.Index(i).Interface() == obj {
return true, nil
}
}
case reflect.Map:
if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
return true, nil
}
}
return false, errors.New("not in array")
}