summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorVincent Douillet <vincent@vdouillet.fr>2021-12-08 09:51:04 +0100
committerVincent Douillet <vincent@vdouillet.fr>2021-12-08 09:51:04 +0100
commit40aa90ca888cbe67552893ba82f83b8f80b0c43f (patch)
tree4b8550116b23f4c54ce5791b3fac637ce2972b8e
parentdaad1e7e3abf5a27a41d8b5e52a4536068030327 (diff)
day 7
-rw-r--r--07.c95
-rw-r--r--Makefile5
2 files changed, 99 insertions, 1 deletions
diff --git a/07.c b/07.c
new file mode 100644
index 0000000..20caf95
--- /dev/null
+++ b/07.c
@@ -0,0 +1,95 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <limits.h>
+#include "input.h"
+
+#define ABS(x) (x < 0 ? -(x) : x)
+#define MIN(x, y) (x < y ? x : y)
+
+#define INPUT "input/07.txt"
+#define INPUT_DOMAIN_MAX 2000
+
+#define EXPECTED1 349769L
+#define EXPECTED2 99540554L
+
+void part1(struct input_str* input) {
+ char* start = input->lines[0];
+ char* end = start;
+ int sub_count_by_alt[INPUT_DOMAIN_MAX] = { 0 };
+
+ // parse input
+ long sub_count = 0;
+ while(*end != '\n') {
+ long alt = strtol(start, &end, 0);
+ start = end;
+ if(*end == ',')
+ start++;
+
+ sub_count_by_alt[alt]++;
+ sub_count++;
+ }
+
+ // brute force
+ long fuel_min = LONG_MAX;
+ for(int a = 0; a < INPUT_DOMAIN_MAX; a++) {
+ long current_fuel = 0;
+ for(int b = 0; b < INPUT_DOMAIN_MAX; b++) {
+ current_fuel += sub_count_by_alt[b] * ABS(b - a);
+ }
+ fuel_min = MIN(fuel_min, current_fuel);
+ }
+
+ CHECK(fuel_min, EXPECTED1);
+}
+
+long compute_fuel(int distance) {
+ long fuel = 0;
+ for(int i = 1; i <= distance; i++) {
+ fuel += i;
+ }
+ return fuel;
+}
+
+void part2(struct input_str* input) {
+ char* start = input->lines[0];
+ char* end = start;
+ int sub_count_by_alt[INPUT_DOMAIN_MAX] = { 0 };
+
+ // parse input
+ long sub_count = 0;
+ while(*end != '\n') {
+ long alt = strtol(start, &end, 0);
+ start = end;
+ if(*end == ',')
+ start++;
+
+ sub_count_by_alt[alt]++;
+ sub_count++;
+ }
+
+ // brute force
+ long fuel_min = LONG_MAX;
+ for(int a = 0; a < INPUT_DOMAIN_MAX; a++) {
+ long current_fuel = 0;
+ for(int b = 0; b < INPUT_DOMAIN_MAX; b++) {
+ current_fuel += sub_count_by_alt[b] * compute_fuel(ABS(b - a));
+ }
+ fuel_min = MIN(fuel_min, current_fuel);
+ }
+
+ CHECK(fuel_min, 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;
+}
diff --git a/Makefile b/Makefile
index 97c64b6..a2e394d 100644
--- a/Makefile
+++ b/Makefile
@@ -1,7 +1,7 @@
CC=cc
CFLAGS=-std=c1x -W -Wall -g
LDFLAGS=
-EXEC=01 02 03 04 05 06
+EXEC=01 02 03 04 05 06 07
all: $(EXEC)
@@ -26,5 +26,8 @@ all: $(EXEC)
06: input.o list.o 06.o
$(CC) -o $@ $> $(LDFLAGS)
+07: input.o 07.o
+ $(CC) -o $@ $> $(LDFLAGS)
+
clean:
rm -rf *.o $(EXEC)