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
|
#include <stdlib.h>
#include <stdio.h>
#include <err.h>
#include <string.h>
#include "input.h"
#define INPUT "input/04.txt"
#define EXPECTED1 573L
#define EXPECTED2 867L
void part1(struct input_str* input) {
size_t overlap_count = 0;
int section_range[4];
for(size_t i = 0; i < input->line_count; i++) {
// strtok will butcher our line, so give it a copy!
char* line = copy_line(input->lines[i]);
for(int a = 0; a < 4; a++) {
char* section = NULL;
if(a == 0)
section = strtok(line, "-,");
else
section = strtok(NULL, "-,");
section_range[a] = atoi(section);
}
free(line);
line = NULL;
// check range inclusion
if((section_range[0] <= section_range[2] && section_range[1] >= section_range[3]) || (section_range[2] <= section_range[0] && section_range[3] >= section_range[1]))
overlap_count++;
}
CHECK(overlap_count, EXPECTED1)
}
void part2(struct input_str* input) {
size_t overlap_count = 0;
int section_range[4];
for(size_t i = 0; i < input->line_count; i++) {
// strtok will butcher our line, so give it a copy!
char* line = copy_line(input->lines[i]);
for(int a = 0; a < 4; a++) {
char* section = NULL;
if(a == 0)
section = strtok(line, "-,");
else
section = strtok(NULL, "-,");
section_range[a] = atoi(section);
}
free(line);
line = NULL;
// check range overlap
if((section_range[2] <= section_range[1] && section_range[3] >= section_range[0]) || (section_range[0] <= section_range[3] && section_range[1] >= section_range[2]))
overlap_count++;
}
CHECK(overlap_count, EXPECTED2)
}
int main() {
// read input
struct input_str input;
input_str_read(&input, INPUT);
// do stuff
part1(&input);
part2(&input);
// cleanup & exit
input_str_free(&input);
return 0;
}
|