-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
97 lines (83 loc) · 2.06 KB
/
main.cpp
File metadata and controls
97 lines (83 loc) · 2.06 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#define NUM_NUMBERS 9
static const char* numbers[9] = {
"one","two","three","four",
"five","six", "seven","eight","nine"
};
int searchNumberInLine(char* line, int fromBack, int stage)
{
while(*line != '\n')
{
int num = -1;
if(*line >= '1' && *line <= '9')
{
num = *line-'0';
}
if(stage == 2)
{
for(int i = 0; i < NUM_NUMBERS; i++)
{
if(strncmp(line, numbers[i], strlen(numbers[i])) == 0)
{
num = i+1;
}
}
}
if(num != -1)
{
if(fromBack)
{
int found = searchNumberInLine(++line, fromBack, stage);
if(found != -1)
{
return found;
}
}
return num;
}
line++;
}
return -1;
}
int calculateCalibrationValue(char* line, int stage)
{
int first = searchNumberInLine(line, 0, stage);
int last = searchNumberInLine(line, 1, stage);
return first*10+last;
}
int day1(int stage)
{
FILE *file;
file = fopen("config", "r");
if(file == NULL)
return 0;
char* line;
size_t len;
int value = 0;
while(getline(&line, &len, file) != -1)
{
value += calculateCalibrationValue(line, stage);
free(line);
line = NULL;
}
fclose(file);
return value;
}
int main(int argc, char* argv[]) {
int stage = 1;
if(argc > 1)
{
stage = *argv[1] - '0';
}
printf("Stage: %d\n", stage);
double time1 = (double) clock();
time1 = time1 / CLOCKS_PER_SEC;
printf("Result Stage %d: %d\n", stage, day1(stage));
double time_diff = (((double) clock()) / CLOCKS_PER_SEC) - time1;
printf("The elapsed time is %lf seconds\n", time_diff);
return 0;
}