#include #include #include #include #include struct antenna { char type; int xy[2]; struct antenna *next; }; void add_antenna(struct antenna *head, char type, int *xy) { // traverse list until last member while(head->next) head = head->next; // allocate and store ptr if (head->type) { head->next = malloc(sizeof(struct antenna)); head = head->next; } head->type = type; head->xy[0] = xy[0]; head->xy[1] = xy[1]; head->next = 0; } int main () { struct antenna *list = malloc(sizeof(struct antenna)); list->type = '\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 < height; i++) { for (int j = 0; j < width; j++) { grid[j][i] = fgetc(input); if (grid[j][i] != '.') { // store antenna in list int xy[] = {j, i}; add_antenna(list, grid[j][i], xy); printf("Antenna %c coords: %d/%d\n", grid[j][i], j, i); } } // skip newline fgetc(input); } fclose(input); struct antenna *current = list; struct antenna *other = list; // for each antenna in list while (current) { // find delta to other of same frequency while (other) { if (current->type == other->type && current != other) { int delta[2]; delta[0] = other->xy[0] - current->xy[0]; delta[1] = other->xy[1] - current->xy[1]; // apply # to other + delta int pos[2] = {other->xy[0], other->xy[1]}; while ( (pos[0] + delta[0]) >= 0 && (pos[0] + delta[0]) < width && (pos[1] + delta[1]) >= 0 && (pos[1] + delta[1]) < height) { pos[0] = pos[0] + delta[0]; pos[1] = pos[1] + delta[1]; grid[pos[0]][pos[1]] = '#'; } pos[0] = other->xy[0]; pos[1] = other->xy[1]; while ( (pos[0] - delta[0]) >= 0 && (pos[0] - delta[0]) < width && (pos[1] - delta[1]) >= 0 && (pos[1] - delta[1]) < height) { pos[0] = pos[0] - delta[0]; pos[1] = pos[1] - delta[1]; grid[pos[0]][pos[1]] = '#'; } } other = other->next; } other = list; current = current->next; } // iterate through array again and sum it int sum_x = 0; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (grid[j][i] == '#') sum_x++; printf("%c", grid[j][i]); } printf("\n"); } printf("total antinodes: %d\n", sum_x); }