summaryrefslogtreecommitdiff
path: root/04.c
diff options
context:
space:
mode:
Diffstat (limited to '04.c')
-rw-r--r--04.c71
1 files changed, 71 insertions, 0 deletions
diff --git a/04.c b/04.c
new file mode 100644
index 0000000..dfb653b
--- /dev/null
+++ b/04.c
@@ -0,0 +1,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;
+}