-
Notifications
You must be signed in to change notification settings - Fork 0
/
day_one.c
91 lines (84 loc) · 1.79 KB
/
day_one.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
#include "string_utilities.h"
#include <stdlib.h>
#include <stdbool.h>
typedef char* string;
static string numbers[] = {"one","two","three","four","five","six","seven","eight","nine",NULL };
bool is_eol(char c) {
return c == '\n' || c == '\0';
}
bool match_num(char *input, int *num) {
int index = 0;
while (numbers[index] != NULL) {
char *pn = numbers[index];
char *inp = input;
while (*pn != '\0' && *inp != '\0' && *pn == *inp) {
pn++; inp++;
}
if (*pn == '\0') {
*num = (index + 1);
return true;
}
index++;
}
return false;
}
int process_line(char *input, int len, bool include_words) {
char *p = input;
// find first int at start
int fnum = 0;
while (*p != '\0') {
if (is_digit(*p)) {
fnum = *p - '0';
break;
} else if (include_words && match_num(p, &fnum)) {
break;
}
p++;
}
p = input + len;
// work backwards to find int
int snum = 0;
while (!is_digit(*p) && (!include_words || !match_num(p, &snum))) {
p--;
}
if (is_digit(*p)) {
snum = *p - '0';
}
return (fnum * 10) + snum;
}
int run_file(char *input, bool includeWords) {
// for each line
char *start = input;
int len = 0;
int total = 0;
while (*input != '\0') {
while (!is_eol(*input)) {
input++;
len++;
}
bool isNewLine = *input == '\n';
*input = '\0';
total += process_line(start, len, includeWords);
// move past newline (unless end)
if (isNewLine) {
input++;
}
start = input;
len = 0;
}
return total;
}
int main (int argc, char **argv) {
char *contents;
if (argc > 2) {
contents = string_from_file(argv[2]);
} else {
contents = string_from_file("day01inp.txt");
}
if (argc > 1 && argv[1][0] == 'b') {
printf("Part B Total: %d\n", run_file(contents, true));
} else {
printf("Part A Total: %d\n", run_file(contents, false));
}
free(contents);
}