#include #include #if 0 #define FILE_PATH "example.txt" #else #define FILE_PATH "input.txt" #endif #define WIDTH 10 #define HEIGHT 10 int board[WIDTH][HEIGHT] = {0}; size_t flashes = 0; void parse() { FILE *fp = fopen(FILE_PATH, "r"); if(!fp) { fprintf(stderr,"ERROR: Could not open file: %s", FILE_PATH); return; } char ch; int i = 0; while((ch = fgetc(fp)) != EOF) { if(ch == '\n') continue; board[i%WIDTH][i/HEIGHT] = ch - '0'; i++; } fclose(fp); } int step() { for(int i = 0; i < HEIGHT; i++) for(int j = 0; j < WIDTH; j++) board[j][i] += 1; int new_board[WIDTH][HEIGHT] = {0}; size_t old_flashes = 0 - 1; while(old_flashes != flashes) { old_flashes = flashes; memcpy(new_board, board, sizeof(board)); for(int i = 0; i < HEIGHT; i++) for(int j = 0; j < WIDTH; j++) if(board[j][i] > 9) { flashes++; new_board[j][i] = 0; for(int y = -1; y <= 1; y++) for(int x = -1; x <= 1; x++) if(i+y < 0 || i+y >= HEIGHT || j+x < 0 || j+x >= WIDTH || (y == 0 && x == 0)) continue; else if(new_board[j+x][i+y] != 0) new_board[j+x][i+y]++; } memcpy(board, new_board, sizeof(board)); } int empty_board[WIDTH][HEIGHT] = {0}; if(memcmp(board, empty_board, sizeof(board)) == 0) return 1; return 0; } void print_board() { for(int i = 0; i < HEIGHT; i++) { for(int j = 0; j < WIDTH; j++) { printf("%d", board[j][i]); } puts(""); } } void part_1() { parse(); for(int i = 0; i < 100; i++) step(); printf("flashes: %ld\n", flashes); } void part_2() { parse(); for(int i = 0; i < 1000000; i++) if(step()) { printf("synced at step: %d\n", i + 1); return; } } int main(void) { part_1(); part_2(); return 0; }