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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#if 0
#define PART_1
#else
#define PART_2
#endif
#if 0
#define FILE_PATH "example.txt"
#define WIDTH 10
#define HEIGHT 10
#else
#define FILE_PATH "input.txt"
#define WIDTH 10000
#define HEIGHT 10000
#endif
int board[WIDTH][HEIGHT] = {0};
void draw_line(int x1, int y1, int x2, int y2)
{
if(x1 == x2)
{
for(int y = MIN(y1, y2); y <= MAX(y1, y2); y++)
board[x1][y]++;
}
else if(y1 == y2)
{
for(int x = MIN(x1, x2); x <= MAX(x1, x2); x++)
board[x][y1]++;
}
#ifdef PART_2
else
{
int direction_x = (x1 < x2) ? 1 : -1;
int direction_y = (y1 < y2) ? 1 : -1;
int y = y1;
int x = x1;
while(!((y == y2) && (x == x2)))
{
board[x][y]++;
x+=direction_x;
y+=direction_y;
}
}
#endif
}
void parse()
{
FILE *fp = fopen(FILE_PATH, "r");
if(!fp) {
fprintf(stderr, "ERROR: Could not open file: %s", FILE_PATH);
exit(EXIT_FAILURE);
}
char *vec1, *vec2;
char line[256];
while(fgets(line, sizeof(line), fp) != NULL)
{
vec1 = strtok(line, " -> ");
vec2 = strtok(NULL, " -> ");
int x1, y1, x2, y2;
x1 = atoi(strtok(vec1, ","));
y1 = atoi(strtok(NULL, ","));
x2 = atoi(strtok(vec2, ","));
y2 = atoi(strtok(NULL, ","));
draw_line(x1, y1, x2, y2);
}
}
void print_board()
{
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < WIDTH; j++)
{
if(board[j][i] == 0)
putc('.', stdout);
else if(board[j][i] == 1)
putc('#', stdout);
else
putc('@', stdout);
}
putc('\n', stdout);
}
}
void part_1()
{
parse();
int count = 0;
for(int i = 0; i < HEIGHT; i++)
for(int j = 0; j < WIDTH; j++)
if(board[j][i] >= 2) count++;
printf("Count is %d\n", count);
}
void part_2()
{
parse();
int count = 0;
for(int i = 0; i < HEIGHT; i++)
for(int j = 0; j < WIDTH; j++)
if(board[j][i] >= 2) count++;
// print_board();
printf("Count is %d\n", count);
}
int main(void)
{
#ifdef PART_1
part_1();
#endif
#ifdef PART_2
part_2();
#endif
return 0;
}
|