From 846a6326f87709d6b645e3fd20bde069c3fdf44b Mon Sep 17 00:00:00 2001 From: Logan Hunt Date: Thu, 1 Dec 2022 22:42:01 -0700 Subject: [PATCH] Day 2 - C --- README.md | 3 ++- day-01/sol.c | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 day-01/sol.c diff --git a/README.md b/README.md index 399d616..2932562 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,8 @@ - [x] BASH - [Day 0](./day-0) -- [] C +- [x] C + - [Day 1](./day-1) - [] Clojure - [] Common LISP - [] C++ diff --git a/day-01/sol.c b/day-01/sol.c new file mode 100644 index 0000000..612692a --- /dev/null +++ b/day-01/sol.c @@ -0,0 +1,74 @@ +#include + +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#define MIN(a, b) ((a) < (b) ? (a) : (b)) + +/* + USAGE: ./sol +*/ + +int get_my_score(char elf, char me) +{ + int elf_choice = (int)(elf - 'A') + 1; + int my_choice = (int)(me - 'X') + 1; + int i_won = 0; + if (elf_choice == my_choice) + return my_choice + 3; + + switch (elf_choice + my_choice) + { + case 3: + i_won = (elf_choice == 1); + break; + case 4: + i_won = (elf_choice == 3); + break; + case 5: + i_won = (elf_choice == 2); + break; + } + + return my_choice + i_won * 6; +} + +const int wins[3] = {2, 3, 1}; +const int loss[3] = {3, 1, 2}; + +int get_my_score_2(char elf, char me) +{ + int elf_choice = (int)(elf - 'A') + 1; + int outcome = (int)(me - 'X') + 1; + + if (outcome == 2) + return elf_choice + 3; + + if (outcome == 1) + return loss[elf_choice - 1]; + return 6 + wins[elf_choice - 1]; +} + +int main(int argc, char *argv[]) +{ + char *fileName = argv[1]; + + FILE *file = fopen(fileName, "r"); + char line[256]; + char elf, me; + + int score1 = 0; + int score2 = 0; + while (1) + { + int i = fscanf(file, "%c %c\n", &elf, &me); + if (i == EOF) + break; + score1 += get_my_score(elf, me); + score2 += get_my_score_2(elf, me); + } + + printf("Score one: %d\n", score1); + printf("Score two: %d\n", score2); + + fclose(file); + return 0; +}