1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
|
#include <stdio.h>
#include <string.h>
#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;
}
|