-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday24.c
More file actions
115 lines (96 loc) · 2.71 KB
/
day24.c
File metadata and controls
115 lines (96 loc) · 2.71 KB
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
115
// Advent of Code - Day 24
// @curiouskiwi @gary_anderson
// 24 Dec 2020
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define FILENAME "data.txt"
//#define FILENAME "sample.txt"
#define LINE 50
#define DIM 200
// white tiles are false, black are true
bool tilearea[DIM][DIM] = {{false}};
int countblacktiles();
int main(void)
{
FILE *file = fopen(FILENAME, "r");
if (!file) return -1;
char buffer[LINE];
while(fgets(buffer, sizeof(buffer), file))
{
int x = DIM/2; int y = DIM/2; char *ptr = buffer;
// sesenwnenenewseeswwswswwnenewsewsw
while (*ptr != '\n')
{
switch (*ptr)
{
// e, se, sw, w, nw, ne
case 'e': x++;
break;
case 'w': x--;
break;
case 'n': y++; ptr++;
if (*ptr == 'e')
x++;
break;
case 's': y--; ptr++;
if (*ptr == 'w')
x--;
break;
default: printf("PROBLEM!\n"); return -1;
}
ptr++;
}
// flip the tile
tilearea[x][y] = !tilearea[x][y];
}
fclose(file);
printf("Part 1; %i\n", countblacktiles());
// PART 2
// all tiles are flipped simultaneously so we need a copy
bool copyarea[DIM][DIM];
// rearrange each day for 100 days
for (int c = 0; c < 100; c++)
{
memcpy(copyarea, tilearea, sizeof(copyarea));
for (int x = 1; x < DIM-1; x++)
{
for (int y = 1; y < DIM-1; y++)
{
// count black neighbours
int counter = 0;
if (copyarea[x][y+1]) counter++;
if (copyarea[x+1][y+1]) counter++;
if (copyarea[x+1][y]) counter++;
if (copyarea[x][y-1]) counter++;
if (copyarea[x-1][y-1]) counter++;
if (copyarea[x-1][y]) counter++;
if (copyarea[x][y])
{
if (counter == 0 || counter > 2)
tilearea[x][y] = false;
}
else
{
if (counter == 2)
tilearea[x][y] = true;
}
}
}
}
printf("Part 2: %i\n", countblacktiles());
}
// black tiles are 'true'
int countblacktiles()
{
int count = 0;
for (int i = 0; i < DIM; i++)
{
for (int j = 0; j < DIM; j++)
{
if (tilearea[i][j])
count++;
}
}
return count;
}