1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
#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;
for(size_t i = 0; i < lineCount; i++) {
parse_move(input[i], ¤tMove);
switch(currentMove.dir) {
case forward:
forwardDst += currentMove.length;
continue;
case up:
downDst -= currentMove.length;
continue;
case down:
downDst += currentMove.length;
continue;
}
}
printf("%ld\n", forwardDst * downDst);
free_strings(input, lineCount);
return 0;
}
|