From 50efc984f96c196053927ae7b3d05ce0d37f5f92 Mon Sep 17 00:00:00 2001 From: Peter Date: Thu, 2 Dec 2021 18:54:41 +0800 Subject: [PATCH] Day 2 solutions --- 2/2-1.c | 32 ++++++++++++++++++++++++++++++++ 2/2-2.c | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 2/2-1.c create mode 100644 2/2-2.c diff --git a/2/2-1.c b/2/2-1.c new file mode 100644 index 0000000..7223296 --- /dev/null +++ b/2/2-1.c @@ -0,0 +1,32 @@ +#include +#include +#include + +int main(int argc, char const *argv[]) +{ + FILE *p_file = fopen("input", "r"); + char instruction[50]; + + int horizontal, depth = 0; + + while (fgets(instruction, sizeof instruction, p_file) != NULL) + { + char direction[50]; + int *amount = malloc(sizeof(int)); + if (sscanf(instruction, "%s %i", direction, amount) != 2) + exit(EXIT_FAILURE); + if (strcmp(direction, "up") == 0) + (*amount) *= -1; + if (strcmp(direction, "forward") == 0) + { + horizontal += *amount; + } + else + { + depth += *amount; + } + // printf("POSITION horizontal %d, depth %d\n", horizontal, depth); + } + printf("%d\n", depth * horizontal); + return 0; +} diff --git a/2/2-2.c b/2/2-2.c new file mode 100644 index 0000000..45bde73 --- /dev/null +++ b/2/2-2.c @@ -0,0 +1,36 @@ +#include +#include +#include + +int main(int argc, char const *argv[]) +{ + FILE *p_file = fopen("input", "r"); + char instruction[50]; + + int horizontal, depth, aim = 0; + + while (fgets(instruction, sizeof instruction, p_file) != NULL) + { + char direction[50]; + int *amount = malloc(sizeof(int)); + if (sscanf(instruction, "%s %i", direction, amount) != 2) + exit(EXIT_FAILURE); + if (strcmp(direction, "up") == 0) + { + aim -= *amount; + } + else if (strcmp(direction, "down") == 0) + { + aim += *amount; + } + else // FORWARD + { + horizontal += *amount; + depth += (*amount) * aim; + } + // printf("POSITION horizontal %d\t depth %d\t aim %d\n", + // horizontal, depth, aim); + } + printf("%d\n", depth * horizontal); + return 0; +}