advent-of-code

advent of code attempts
git clone git://bvnf.space/advent-of-code.git
Log | Files | Refs

commit 7c2caea1b2df31b38e53c41606c550fffdc62774
parent c5680be46599039605d5f756896a33f7b4749a7d
Author: aabacchus <bvnfuller@gmail.com>
Date:   Thu,  2 Dec 2021 21:16:53 +0000

21.2.1 in C

this, on the other hand, took about seven minutes.

Diffstat:
A2021/02/2.c | 48++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 48 insertions(+), 0 deletions(-)

diff --git a/2021/02/2.c b/2021/02/2.c @@ -0,0 +1,48 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +int +main(int argc, char **argv) { + if (argc < 2) { + fprintf(stderr, "usage: %s datafile\n", *argv); + return 1; + } + + FILE *fd = fopen(argv[1], "r"); + if (fd == NULL) { + perror(argv[1]); + return 1; + } + + int coords[2] = {0, 0}; + + char *buf = NULL; + size_t buflen = 0; + while (getline(&buf, &buflen, fd) != -1) { + int param = atoi(strchr(buf, ' ') + 1); + switch (buf[0]) { + case 'f': /* forward */ + coords[0] += param; + break; + case 'u': /* up */ + coords[1] -= param; + break; + case 'd': /* down */ + coords[1] += param; + break; + } + } + + free(buf); + + printf("final coords: %d %d\n", coords[0], coords[1]); + printf("product: %d\n", coords[0] * coords[1]); + + if (fclose(fd) == EOF) { + perror("fclose"); + return 1; + } + + return 0; +}