commit 138af62cd2349dbd0beb5096058c576945986908 (patch)
parent 20f5c35c65f2bfedfdd63825d7bb95b2b18a94ce
Author: Alex Karle <alex@alexkarle.com>
Date: Thu, 2 Dec 2021 09:45:26 -0500
day2: Add C implementation
Things learned:
* Use scanf instead of fscanf (stdin implied)
* scanf has a max-len specifier to make it somewhat mem safe
Diffstat:
3 files changed, 54 insertions(+), 0 deletions(-)
diff --git a/2/c/a.c b/2/c/a.c
@@ -0,0 +1,24 @@
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+int main(void) {
+ int depth = 0;
+ int pos = 0;
+ int val;
+ char comm[256];
+ while(scanf("%255s %d\n", comm, &val) != EOF) {
+ if (!strcmp(comm, "forward")) {
+ pos += val;
+ } else if (!strcmp(comm, "up")) {
+ depth -= val;
+ } else if (!strcmp(comm, "down")) {
+ depth += val;
+ } else {
+ fprintf(stderr, "bad command: %s\n", comm);
+ exit(1);
+ }
+ }
+ printf("%d\n", pos * depth);
+ return 0;
+}
diff --git a/2/c/b.c b/2/c/b.c
@@ -0,0 +1,26 @@
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+int main(void) {
+ int depth = 0;
+ int pos = 0;
+ int aim = 0;
+ int val;
+ char comm[256];
+ while(scanf("%255s %d\n", comm, &val) != EOF) {
+ if (!strcmp(comm, "forward")) {
+ pos += val;
+ depth += val * aim;
+ } else if (!strcmp(comm, "up")) {
+ aim -= val;
+ } else if (!strcmp(comm, "down")) {
+ aim += val;
+ } else {
+ fprintf(stderr, "bad command: %s\n", comm);
+ exit(1);
+ }
+ }
+ printf("%d\n", pos * depth);
+ return 0;
+}
diff --git a/Makefile b/Makefile
@@ -3,6 +3,8 @@ CFLAGS = -g -O2 -Wall -Wpedantic -Wextra
TARGETS = \
1/c/a \
1/c/b \
+ 2/c/a \
+ 2/c/b \
.PHONY: all
all: $(TARGETS)
@@ -11,6 +13,8 @@ all: $(TARGETS)
clean:
rm -f $(TARGETS)
+2/c/b: 2/c/b.c
+2/c/a: 2/c/a.c
1/c/b: 1/c/b.c
1/c/a: 1/c/a.c
$(CC) $(CFLAGS) -o $@ $<