diff options
author | Vincent Douillet <vincent@vdouillet.fr> | 2021-12-02 22:46:01 +0100 |
---|---|---|
committer | Vincent Douillet <vincent@vdouillet.fr> | 2021-12-02 22:46:01 +0100 |
commit | c851f16d1df21d7579af72d842521b951261b092 (patch) | |
tree | 2f1c4672b53afb8c575ff7c64d88b9020034219d /022.c |
day 1 & 2
Diffstat (limited to '022.c')
-rw-r--r-- | 022.c | 69 |
1 files changed, 69 insertions, 0 deletions
@@ -0,0 +1,69 @@ +#include <stdlib.h> +#include <stdio.h> +#include <err.h> +#include <string.h> +#include "input.h" + +#define INPUT "input/02.txt" + +enum direction { forward, up, down }; + +struct submarine_move { + enum direction dir; + int length; +}; + +void parse_move(char* string, struct submarine_move* move) { + if(*string == 'f') + move->dir = forward; + else if(*string == 'u') + move->dir = up; + else if(*string == 'd') + move->dir = down; + else + err(1, "direction inconnue %c", *string); + + size_t stringLength = strlen(string); + char digit = string[stringLength - 2]; + if(digit < '0' || digit > '9') + err(1, "longueur inconnue %c", digit); + move->length = digit - '0'; +} + +int main() { + // lecture du fichier d'entree + FILE* file=fopen(INPUT,"r"); + if(file == NULL) + err(1, "Le fichier %s n'existe pas\n", INPUT); + + size_t lineCount = count_lines(file); + char** input = malloc(lineCount * sizeof(char*)); + read_lines_as_string(file, input, lineCount); + // fermeture du fichier + fclose(file); + + // l'algo + struct submarine_move currentMove; + long forwardDst = 0; + long downDst = 0; + long aim = 0; + for(size_t i = 0; i < lineCount; i++) { + parse_move(input[i], ¤tMove); + switch(currentMove.dir) { + case forward: + forwardDst += currentMove.length; + downDst += currentMove.length * aim; + continue; + case up: + aim -= currentMove.length; + continue; + case down: + aim += currentMove.length; + continue; + } + } + printf("%ld\n", forwardDst * downDst); + + free_strings(input, lineCount); + return 0; +} |