summaryrefslogtreecommitdiff
path: root/02.c
diff options
context:
space:
mode:
Diffstat (limited to '02.c')
-rw-r--r--02.c88
1 files changed, 88 insertions, 0 deletions
diff --git a/02.c b/02.c
new file mode 100644
index 0000000..30af77f
--- /dev/null
+++ b/02.c
@@ -0,0 +1,88 @@
+#include <stdio.h>
+#include <err.h>
+#include <string.h>
+#include "input.h"
+
+#define INPUT "input/02.txt"
+
+enum direction { forward, up, down };
+
+struct submarine_move {
+ enum direction dir;
+ int length;
+};
+
+void parse_move(char* string, struct submarine_move* move) {
+ if(*string == 'f')
+ move->dir = forward;
+ else if(*string == 'u')
+ move->dir = up;
+ else if(*string == 'd')
+ move->dir = down;
+ else
+ err(1, "direction inconnue %c", *string);
+
+ size_t stringLength = strlen(string);
+ char digit = string[stringLength - 2];
+ if(digit < '0' || digit > '9')
+ err(1, "longueur inconnue %c", digit);
+ move->length = digit - '0';
+}
+
+void part1(struct input_str* input) {
+ struct submarine_move currentMove;
+ long forwardDst = 0;
+ long downDst = 0;
+ for(size_t i = 0; i < input->line_count; i++) {
+ parse_move(input->lines[i], &currentMove);
+ switch(currentMove.dir) {
+ case forward:
+ forwardDst += currentMove.length;
+ continue;
+ case up:
+ downDst -= currentMove.length;
+ continue;
+ case down:
+ downDst += currentMove.length;
+ continue;
+ }
+ }
+ printf("%ld\n", forwardDst * downDst);
+}
+
+void part2(struct input_str* input) {
+ struct submarine_move currentMove;
+ long forwardDst = 0;
+ long downDst = 0;
+ long aim = 0;
+ for(size_t i = 0; i < input->line_count; i++) {
+ parse_move(input->lines[i], &currentMove);
+ switch(currentMove.dir) {
+ case forward:
+ forwardDst += currentMove.length;
+ downDst += currentMove.length * aim;
+ continue;
+ case up:
+ aim -= currentMove.length;
+ continue;
+ case down:
+ aim += currentMove.length;
+ continue;
+ }
+ }
+ printf("%ld\n", forwardDst * downDst);
+}
+
+int main() {
+ // read input data
+ struct input_str input;
+ input_str_read(&input, INPUT);
+
+ // do stuff
+ part1(&input);
+ part2(&input);
+
+ // cleanup & exit
+ input_str_free(&input);
+ return 0;
+}