aboutsummaryrefslogtreecommitdiff
path: root/src/utils/utilities.c
blob: 717dce01c6a233d762f02d62b6d9a56141373368 (plain)
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
#include "utils/utilities.h"
#include <string.h>
#include <time.h>

bool monotonic(int a, int b, int c);

// TODO: Handle the case when they are not equal (greater or smaller)
int cmpstr_tillchar(const char *a, const char *b, char a_until, char b_until)
{
    while (*a != 0 && *b != 0 && *a != a_until && *b != b_until)
    {
        if (*a != *b)
            return -1;
        a++;
        b++;
    }
    return 0;
}

static unsigned int random_number(unsigned int max)
{
    return rand() / (RAND_MAX / max);
}

void shuffle(void *base, size_t nitems, size_t size)
{
    char *c_base = base;
    char swap[size];
    for (int i = 0; i < nitems; i++)
    {
        char *a = c_base + (i * size);
        char *b = c_base + (random_number(nitems - 1) * size);
        memcpy(swap, a, size);
        memcpy(a, b, size);
        memcpy(b, swap, size);
    }
}

void init2d(void **array, size_t width, size_t height, size_t size)
{
    char **c_array = (char **)array;
    char *start = (char *)array;
    for (size_t x = 0; x < width; x++)
        c_array[x] = start + (width * sizeof(int *)) + (x * height * size);
}

size_t sizeof_2d(size_t width, size_t height, size_t size)
{
    return (width * sizeof(char *)) + (width * height * size);
}

int find_lr_ints(char *text, char **left, char **right)
{
    *left = text;
    while (**left != 0 && (**left < '0' || **left > '9'))
        (*left)++;
    if (**left == 0)
        return 0;

    *right = text + strlen(text);
    while (**right < '0' || **right > '9')
        (*right)--;

    while (**right >= '0' && **right <= '9')
        (*right)--;
    (*right)++;
    return 1;
}