From 138af62cd2349dbd0beb5096058c576945986908 Mon Sep 17 00:00:00 2001 From: Alex Karle Date: Thu, 2 Dec 2021 09:45:26 -0500 Subject: [PATCH] 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 --- 2/c/a.c | 24 ++++++++++++++++++++++++ 2/c/b.c | 26 ++++++++++++++++++++++++++ Makefile | 4 ++++ 3 files changed, 54 insertions(+) create mode 100644 2/c/a.c create mode 100644 2/c/b.c diff --git a/2/c/a.c b/2/c/a.c new file mode 100644 index 0000000..dcab638 --- /dev/null +++ b/2/c/a.c @@ -0,0 +1,24 @@ +#include +#include +#include + +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 new file mode 100644 index 0000000..3f3faee --- /dev/null +++ b/2/c/b.c @@ -0,0 +1,26 @@ +#include +#include +#include + +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 index 9aec0fe..19e8b4a 100644 --- 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 $@ $< -- libgit2 1.8.1