-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
96 lines (81 loc) · 2.05 KB
/
main.c
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
#include <stdio.h>
#include <string.h>
int is_number(char c) {
return (c >= '0' && c <= '9');
}
void replace_number(char *original, char *target, char* numberText, char* number) {
char *substring = NULL;
char *search = original;
int pos = 0;
do {
substring = strstr(search, numberText);
pos = substring - original;
if (substring != NULL) {
strncpy(target + pos, number, 1);
}
search = search + 1;
}
while (substring != NULL);
}
char* replace_numbers(char *original) {
char* target = (char*)malloc(strlen(original) + 1);
strcpy(target, original);
replace_number(original, target, "one", "1");
replace_number(original, target, "two", "2");
replace_number(original, target, "three", "3");
replace_number(original, target, "four", "4");
replace_number(original, target, "five", "5");
replace_number(original, target, "six", "6");
replace_number(original, target, "seven", "7");
replace_number(original, target, "eight", "8");
replace_number(original, target, "nine", "9");
return target;
}
int get_calibration_value(const char *str) {
int result = 0;
int first = -1;
int last = -1;
for (int i = 0; str[i] != '\0'; i++) {
char c = str[i];
if (is_number(c)) {
if (first == -1) {
first = c - '0';
}
last = c - '0';
}
}
return first * 10 + last;
}
void solve(const char *filename) {
FILE *file = fopen(filename, "r");
int sum = 0;
if (file) {
char line[100];
while (fgets(line, sizeof(line), file)) {
int value = get_calibration_value(line);
sum = sum + value;
}
printf("%d\n", sum);
fclose(file);
}
}
void solve2(const char *filename) {
FILE *file = fopen(filename, "r");
char* target = NULL;
int sum = 0;
if (file) {
char line[100];
while (fgets(line, sizeof(line), file)) {
target = replace_numbers(line);
int value = get_calibration_value(target);
sum = sum + value;
}
printf("%d\n", sum);
fclose(file);
}
}
int main(void) {
solve("input");
solve2("input");
return 0;
}