advent2021

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

puzzle1.c (1053B)


      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 puzzle1(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 arg = 0;
     25 
     26 	while (fgets(buf, MAX_LEN, infile) != NULL) {
     27 		if (sscanf(buf, "%15s %d", cmd, &arg) == 2) {
     28 			if (strncmp(cmd, cmd_up, MAX_CMD) == 0) {
     29 				depth -= arg;
     30 			} else if (strncmp(cmd, cmd_down, MAX_CMD) == 0) {
     31 				depth += arg;
     32 			} else if (strncmp(cmd, cmd_forward, MAX_CMD) == 0) {
     33 				distance += arg;
     34 			} else {
     35 				fprintf(stderr, "Invalid command string");
     36 				break;
     37 			}
     38 
     39 			bzero(buf, MAX_LEN);
     40 			bzero(cmd, MAX_CMD);
     41 		}
     42 	}
     43 
     44 	// mutiny! ignoring feof/ferror.
     45 
     46 	fclose(infile);
     47 	return depth * distance;
     48 }