Skip to content

Instantly share code, notes, and snippets.

@skejeton
Last active December 7, 2021 14:08
Show Gist options
  • Save skejeton/32a067a4ae0768452edafa062b75a5f6 to your computer and use it in GitHub Desktop.
Save skejeton/32a067a4ae0768452edafa062b75a5f6 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <inttypes.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
char* read_file(const char *path) {
FILE *f = fopen(path, "rb");
if (f == NULL)
return NULL;
fseek(f, 0, SEEK_END);
size_t fsz = (size_t) ftell(f);
fseek(f, 0, SEEK_SET);
char *input = (char*)malloc((fsz+1)*sizeof(char));
input[fsz] = 0;
fread(input, sizeof(char), fsz, f);
fclose(f);
return input;
}
long next_long(char **src) {
char *endptr = NULL;
long value = strtol(*src, &endptr, 10);
*src = endptr;
return value;
}
void ignore_seq(char **src, char *seq) {
size_t len = strlen(seq);
if (strncmp(*src, seq, len) == 0) {
*src += len;
}
}
bool iseof(char *src) {
while (*src == '\n' || *src == ' ' || *src == '\t')
src += 1;
return *src == 0;
}
typedef int64_t spawner_t;
typedef struct {
spawner_t spawners[10];
} fish_list_t;
void spawn(fish_list_t *list) {
list->spawners[8] += 1;
}
void append(fish_list_t *list, spawner_t fish) {
list->spawners[fish] += 1;
}
void iteration(fish_list_t *list) {
spawner_t new_spawners[10] = { 0 };
int64_t newfishes = list->spawners[0];
for (int i = 1; i < 10; i += 1) {
new_spawners[i-1] = list->spawners[i];
}
new_spawners[6] += newfishes;
new_spawners[8] += newfishes;
memcpy(list->spawners, new_spawners, sizeof(int64_t)*10);
}
void print(fish_list_t *list) {
int64_t total = 0;
for (int i = 0; i < 10; i += 1) {
total += list->spawners[i];
}
printf(" (%ld total)\n", total);
}
fish_list_t load_input(char *path) {
char *file = read_file(path);
char *orig_file = file;
if (file == NULL) {
fprintf(stderr, "Couldn't load %s\n", path);
exit(-1);
}
fish_list_t list = { 0 };
while (!iseof(file)) {
append(&list, (int8_t)next_long(&file));
ignore_seq(&file, ",");
}
free(orig_file);
return list;
}
int main() {
fish_list_t list = load_input("day6/test_input.txt");
for (int i = 0; i < 80; i += 1) {
iteration(&list);
}
printf("Part 1: ");
print(&list);
for (int i = 0; i < 256-80; i += 1) {
iteration(&list);
}
printf("Part 2: ");
print(&list);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment