advent2021

Advent of Code 2021 Solutions
git clone git://bsandro.tech/advent2021
Log | Files | Refs | README | LICENSE

puzzle2.c (1087B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <errno.h>
      4 #include <string.h>
      5 #include <strings.h>
      6 
      7 #define MAX_LEN 32
      8 #define MAX_CMD 16
      9 
     10 int puzzle2(const char *filename) {
     11 	FILE *infile = fopen(filename, "r");
     12 	if (infile == NULL) {
     13 		fprintf(stderr, "fopen() error: %s\n", strerror(errno));
     14 		return -1;
     15 	}
     16 
     17 	static const char *cmd_up = "up";
     18 	static const char *cmd_down = "down";
     19 	static const char *cmd_forward = "forward";
     20 	char buf[MAX_LEN] = {0};
     21 	char cmd[MAX_CMD] = {0};
     22 	int depth = 0;
     23 	int distance = 0;
     24 	int aim = 0;
     25 	int arg = 0;
     26 
     27 	while (fgets(buf, MAX_LEN, infile) != NULL) {
     28 		if (sscanf(buf, "%15s %d", cmd, &arg) == 2) {
     29 			if (strncmp(cmd, cmd_up, MAX_CMD) == 0) {
     30 				aim -= arg;
     31 			} else if (strncmp(cmd, cmd_down, MAX_CMD) == 0) {
     32 				aim += arg;
     33 			} else if (strncmp(cmd, cmd_forward, MAX_CMD) == 0) {
     34 				distance += arg;
     35 				depth += aim * arg;
     36 			} else {
     37 				fprintf(stderr, "Invalid command string");
     38 				break;
     39 			}
     40 
     41 			bzero(buf, MAX_LEN);
     42 			bzero(cmd, MAX_CMD);
     43 		}
     44 	}
     45 
     46 	// mutiny! ignoring feof/ferror.
     47 
     48 	fclose(infile);
     49 	return depth * distance;
     50 }