aoc2024/01/mylib.c
2024-12-01 05:52:45 +01:00

85 lines
1.5 KiB
C

#include "_.h"
// NOT MY CODE
// https://stackoverflow.com/questions/9210528/split-string-with-delimiters-in-c
char** str_split(char* str, const char a_delim)
{
char *a_str = strdup(str);
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}
count += last_comma < (a_str + strlen(a_str) - 1);
count++;
result = malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok(a_str, delim);
while (token)
{
//assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
//assert(idx == count - 1);
*(result + idx) = 0;
}
free(a_str);
return result;
}
int str_index(char *str, char c) {
int i = 0;
while (str[i])
if (str[i++] == c)
return i;
return -1;
}
int number_of_element(char *str, char c) {
int nbr = 0;
for (int i = 0; str[i] != '\0'; i++)
if (str[i] == c)
nbr++;
return nbr;
}
long gmc(long a, long b) {
if (b == 0)
return a;
return gmc(b, a % b);
}
long lmc(long a, long b) {
return (a / gmc(a, b)) * b;
}
long lmcs(int array[], int n) {
long result = array[0];
for (int i = 1; i < n; i++)
result = lmc(result, array[i]);
return result;
}