#include #include #include #include #include int main () { int guard[2]; int rot = 0; int dir[4][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}}; // 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 **grid = malloc(width * sizeof(char*)); grid[0] = malloc(width * height); for (int i = 1; i < width; i++) { grid[i] = grid[0] + i * height; } // put the data in the array for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { grid[j][i] = fgetc(input); if (grid[j][i] == '^') { guard[0] = j; guard[1] = i; printf("guard coords: %d/%d\n", guard[0], guard[1]); } } // skip newline fgetc(input); } fclose(input); // sum it int sum_x = 0; // step (mark current X, check forward, step or rotate) until oob while (true) { // graphics! /* printf("\e[1;1H\e[2J"); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { printf("%c", grid[j][i]); } printf("\n"); } usleep(2000); printf("\e[1;1H\e[2J"); */ if (grid[guard[0]][guard[1]] != 'X') { sum_x++; grid[guard[0]][guard[1]] = 'X'; } // oob? if (guard[0] + dir[rot][0] < 0 || guard[0] + dir[rot][0] >= height || guard[1] + dir[rot][1] < 0 || guard[1] + dir[rot][1] >= height) break; if (grid[guard[0] + dir[rot][0]][guard[1] + dir[rot][1]] == '#') rot = (rot + 1) % 4; // step guard[0] += dir[rot][0]; guard[1] += dir[rot][1]; } printf("total Xs: %d\n", sum_x); }