commit 6f73f35dfebaab334028271e8d40c8e0485b7178
parent ec79421a5a9c955ee159e40b0dea1733b8bd1bf5
Author: bsandro <[email protected]>
Date: Thu, 2 Dec 2021 09:23:55 +0200
Day 02, puzzle 2
Diffstat:
3 files changed, 54 insertions(+), 3 deletions(-)
diff --git a/day02/main.c b/day02/main.c
@@ -1,6 +1,6 @@
#include <stdio.h>
#include "puzzle1.h"
-//#include "puzzle2.h"
+#include "puzzle2.h"
int main(int argc, char *argv[]) {
printf("Advent of Code: day 02\n");
@@ -17,8 +17,8 @@ int main(int argc, char *argv[]) {
int counter1 = puzzle1(filename);
printf("Puzzle #1: %d\n", counter1);
- //int counter2 = puzzle2(filename);
- //printf("Puzzle #2: %d\n", counter2);
+ int counter2 = puzzle2(filename);
+ printf("Puzzle #2: %d\n", counter2);
return 0;
}
diff --git a/day02/puzzle2.c b/day02/puzzle2.c
@@ -0,0 +1,50 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <string.h>
+#include <strings.h>
+
+#define MAX_LEN 32
+#define MAX_CMD 16
+
+int puzzle2(const char *filename) {
+ FILE *infile = fopen(filename, "r");
+ if (infile == NULL) {
+ fprintf(stderr, "fopen() error: %s\n", strerror(errno));
+ return -1;
+ }
+
+ static const char *cmd_up = "up";
+ static const char *cmd_down = "down";
+ static const char *cmd_forward = "forward";
+ char buf[MAX_LEN] = {0};
+ char cmd[MAX_CMD] = {0};
+ int depth = 0;
+ int distance = 0;
+ int aim = 0;
+ int arg = 0;
+
+ while (fgets(buf, MAX_LEN, infile) != NULL) {
+ if (sscanf(buf, "%15s %d", cmd, &arg) == 2) {
+ if (strncmp(cmd, cmd_up, MAX_CMD) == 0) {
+ aim -= arg;
+ } else if (strncmp(cmd, cmd_down, MAX_CMD) == 0) {
+ aim += arg;
+ } else if (strncmp(cmd, cmd_forward, MAX_CMD) == 0) {
+ distance += arg;
+ depth += aim * arg;
+ } else {
+ fprintf(stderr, "Invalid command string");
+ break;
+ }
+
+ bzero(buf, MAX_LEN);
+ bzero(cmd, MAX_CMD);
+ }
+ }
+
+ // mutiny! ignoring feof/ferror.
+
+ fclose(infile);
+ return depth * distance;
+}
diff --git a/day02/puzzle2.h b/day02/puzzle2.h
@@ -0,0 +1 @@
+int puzzle2(const char *filename);