-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_test.go
158 lines (114 loc) · 2.24 KB
/
utils_test.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package parlo_test
import (
"math/rand"
"runtime"
"sync"
"github.com/mahdi-shojaee/parlo/internal/constraints"
)
var MAX_THREADS = 8
const LENGTH = 50_000_000
type Elem uint32
type Elems []Elem
func Initialize[T any](slice []T, create func(n int) T) {
for i := 0; i < len(slice); i++ {
slice[i] = create(i)
}
}
func InitializePar[T any](slice []T, create func(n int) T) {
threads := runtime.GOMAXPROCS(0)
chunkSize := len(slice) / threads
s := slice
var wg sync.WaitGroup
wg.Add(threads)
for i := 0; i < threads; i++ {
endIndex := chunkSize
if i == threads-1 {
endIndex = len(s)
}
go func(s []T, chunkIndex int) {
for i := 0; i < len(s); i++ {
s[i] = create(chunkIndex*chunkSize + i)
}
wg.Done()
}(s[:endIndex], i)
s = s[endIndex:]
}
wg.Wait()
}
func MakeCollection(size int, randomness float32, newElem func(index int) Elem) Elems {
slice := make(Elems, size)
InitializePar(slice, newElem)
numSwaps := int(randomness * float32(size))
for i := 0; i < numSwaps; i++ {
j := rand.Intn(size)
k := rand.Intn(size)
slice[j], slice[k] = slice[k], slice[j]
}
return slice
}
func Split[S ~[]E, E any](slice []E, chunksNo int) []S {
chunks := make([]S, chunksNo)
chunkSize := len(slice) / chunksNo
s := slice
for i := 0; i < chunksNo; i++ {
endIndex := chunkSize
if i == chunksNo-1 {
endIndex = len(s)
}
chunks[i] = s[:endIndex]
s = s[endIndex:]
}
return chunks
}
func Min[S ~[]E, E constraints.Ordered](slice S) E {
var min E
if len(slice) == 0 {
return min
}
min = slice[0]
for _, v := range slice[1:] {
if v < min {
min = v
}
}
return min
}
func MinFunc[S ~[]E, E any](slice S, cmp func(a, b E) int) E {
var min E
if len(slice) == 0 {
return min
}
min = slice[0]
for _, v := range slice[1:] {
if cmp(v, min) < 0 {
min = v
}
}
return min
}
func Max[S ~[]E, E constraints.Ordered](slice S) E {
var max E
if len(slice) == 0 {
return max
}
max = slice[0]
for _, v := range slice[1:] {
if v > max {
max = v
}
}
return max
}
func MaxFunc[S ~[]E, E any](slice S, cmp func(a, b E) int) E {
var max E
if len(slice) == 0 {
return max
}
max = slice[0]
for _, v := range slice[1:] {
if cmp(v, max) > 0 {
max = v
}
}
return max
}