-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslices.go
87 lines (75 loc) · 1.61 KB
/
slices.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
83
84
85
86
87
package aoc
import (
"slices"
"golang.org/x/exp/constraints"
)
func SliceCopy[T any](in []T) []T {
res := make([]T, len(in))
copy(res, in)
return res
}
// DeleteSliceIndex deletes a given index.
func DeleteSliceIndex[T any](in []T, index int, deepCopy bool) []T {
if deepCopy {
in = SliceCopy(in)
}
return append(in[:index], in[index+1:]...)
}
// DeleteSliceIndices deletes a list of indices.
func DeleteSliceIndices[T any](in []T, indices []int, deepCopy bool) []T {
if len(in) == 0 {
return nil
}
if deepCopy {
in = SliceCopy(in)
}
set := SliceToSet(indices)
i := 0
return slices.DeleteFunc(in, func(t T) bool {
defer func() {
i++
}()
return set[i]
})
}
func IsSliceSorted[T constraints.Ordered](in []T, comp func(a T, b T) bool) bool {
if len(in) <= 1 {
return true
}
prev := in[0]
for i := 1; i < len(in); i++ {
cur := in[i]
if !comp(prev, cur) {
return false
}
prev = cur
}
return true
}
func IsSliceMonotonicallyIncreasing[T constraints.Ordered](in []T) bool {
return IsSliceSorted(in, func(a T, b T) bool {
return b >= a
})
}
func IsSliceMonotonicallyDecreasing[T constraints.Ordered](in []T) bool {
return IsSliceSorted(in, func(a T, b T) bool {
return b <= a
})
}
func IsSliceStrictlyIncreasing[T constraints.Ordered](in []T) bool {
return IsSliceSorted(in, func(a T, b T) bool {
return b > a
})
}
func IsSliceStrictlyDecreasing[T constraints.Ordered](in []T) bool {
return IsSliceSorted(in, func(a T, b T) bool {
return b < a
})
}
func SliceCount[T comparable](in []T) map[T]int {
res := make(map[T]int)
for _, v := range in {
res[v]++
}
return res
}