AoC2024/10/main.c
2024-12-10 20:59:48 +01:00

127 lines
2.8 KiB
C

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
struct list {
int xy[2];
struct list *next;
};
int score_trail(int x, int y, int width, int height, char **map, struct list *peaks)
{
int dir[4][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
int score = 0;
int first = map[x][y];
// init list
if (peaks == NULL) {
peaks = malloc(sizeof(struct list));
peaks->xy[0] = -1;
peaks->xy[1] = -1;
peaks->next = NULL;
}
// if find 9, check if its already in list, else append it
// could have been its own func
if (map[x][y] == '9') {
printf("found %dx%d\n", x, y);
if (peaks->xy[0] == -1 ) {
printf("was first, init first trail\n");
peaks->xy[0] = x;
peaks->xy[1] = y;
return 1;
}
// while (!(peaks->xy[0] == x && peaks->xy[1] == y) && peaks->next) {
while (peaks->next) {
printf("checking next peaklist...\n");
peaks = peaks->next;
}
/*
if (peaks->xy[0] == x && peaks->xy[1] == y) {
printf("found same, exit\n");
return 0;
}
*/
// printf("allocate new peak, jump to it, and set it\n");
peaks->next = malloc(sizeof(struct list));
peaks = peaks->next;
peaks->xy[0] = x;
peaks->xy[1] = y;
peaks->next = NULL;
return 1;
}
// look in every direction for grid[j][i] + 1, recurse it
for (int i = 0; i < 4; i++) {
if (x + dir[i][0] >= 0 &&
x + dir[i][0] < width &&
y + dir[i][1] >= 0 &&
y + dir[i][1] < height) {
if (map[x + dir[i][0]][y + dir[i][1]] == map[x][y] + 1)
score_trail(x + dir[i][0], y + dir[i][1],
width, height, map, peaks);
}
}
// please count and cleanup the list
if (first == '0') {
struct list *tmp;
while (peaks) {
score++;
tmp = peaks;
peaks = peaks->next;
free(tmp);
}
return score;
}
return 0;
}
int main ()
{
// figure out data dimensions
FILE *input = fopen("./input", "r");
int width = 0;
int height = 1;
while (fgetc(input) != '\n') width++;
for (char c = fgetc(input); c != EOF; c = fgetc(input)) {
if (c == '\n')
height++;
}
rewind(input);
printf("Dimensions: %d x %d\n", width, height);
// make 2d array
char **map = malloc(width * sizeof(char*));
map[0] = malloc(width * height);
for (int i = 1; i < width; i++) {
map[i] = map[0] + i * height;
}
// put the data in the array
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
map[j][i] = fgetc(input);
}
fgetc(input);
}
fclose(input);
// sum it
int scoreSum = 0;
// find trailheads, check their score, sumit (hehehe)
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (map[j][i] == '0') {
printf("\tExamining %dx%d:\n", j, i);
int score = score_trail(j, i, width, height, map, NULL);
scoreSum += score;
if (score)
printf("score sum trail head %dx%d: %d\n", j, i, score);
}
}
}
printf("total score: %d\n", scoreSum);
}