-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrandom.c
50 lines (45 loc) · 1.13 KB
/
random.c
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
#include "random.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
void
random_seed(unsigned int const seed)
{
srand(seed);
}
int
rand_range(int const min, int const max)
{
unsigned mn = min;
unsigned mx = max;
/* NOLINTNEXTLINE(cert-msc30-c, cert-msc50-cpp) */
return (int)(mn + (rand() / (RAND_MAX / (mx - mn + 1) + 1)));
}
void
rand_shuffle(size_t const elem_size, void *const elems, size_t const n,
void *const tmp)
{
if (n <= 1)
{
return;
}
uint8_t *elem_view = elems;
size_t const step = elem_size * sizeof(uint8_t);
for (size_t i = 0; i < n - 1; ++i)
{
/* NOLINTNEXTLINE(cert-msc30-c, cert-msc50-cpp) */
size_t const rnd = (size_t)rand();
size_t const j = i + (rnd / (RAND_MAX / (n - i) + 1));
memcpy(tmp, elem_view + (j * step), elem_size);
memcpy(elem_view + (j * step), elem_view + (i * step), elem_size);
memcpy(elem_view + (i * step), tmp, elem_size);
}
}
void
iota(int *const array, size_t n, unsigned start_val)
{
for (size_t i = 0; n--; ++i, ++start_val)
{
array[i] = (int)start_val;
}
}