aoc_omni/c/2020/lib/util.c
2025-11-30 21:22:21 -05:00

57 lines
1.2 KiB
C

#include <stdio.h>
#include <stdlib.h>
char *load_input() {
FILE *fp = fopen("input.txt", "r");
fseek(fp, 0L, SEEK_END);
int sz = ftell(fp);
rewind(fp);
char *data_buffer = malloc((sz + 1) * sizeof(char));
fread(data_buffer, sz, 1, fp);
data_buffer[sz] = 0;
fclose(fp);
return data_buffer;
}
InputWithSize *load_input_with_size() {
FILE *fp = fopen("input.txt", "r");
fseek(fp, 0L, SEEK_END);
int sz = ftell(fp);
rewind(fp);
char *data_buffer = malloc((sz + 1) * sizeof(char));
fread(data_buffer, sz, 1, fp);
data_buffer[sz] = 0;
fclose(fp);
InputWithSize *input_with_size = malloc(sizeof(InputWithSize));
input_with_size->size = sz + 1;
input_with_size->data_buffer = data_buffer;
return input_with_size;
}
void free_input_with_size(InputWithSize *input_with_size) {
free(input_with_size -> data_buffer);
free(input_with_size);
}
void print_binary(int q) {
char c[33] = {0};
for (int i = 0; i < 32; i++) {
c[i] = q & (1<<i) ? '1' : '0';
}
puts(c);
}
// http://www.cse.yorku.ca/~oz/hash.html
// djb2 hash
unsigned long hash_string(unsigned char *str) {
unsigned long hash = 5381;
int c;
while (c = *str++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}