blob: 5afbe00e72a59ea9ca1fd30b6540e56a506b9d68 (
plain) (
blame)
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
|
#define _GNU_SOURCE
#include <sys/types.h>
#include <ctype.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
static unsigned long long parse_number(void);
static unsigned long long parse_digit(void);
static unsigned long long parse_result(void);
#ifdef PART2
static unsigned long long parse_sum(void);
static unsigned long long parse_product(void);
#endif
char *g_current;
/* Convert the current number from a string to an int */
unsigned long long
parse_number(void)
{
unsigned long long number = 0;
while (isdigit(*g_current))
number = number * 10 + *g_current++ - '0';
return number;
}
/* Parse the current digit pointed to by `g_current` */
unsigned long long
parse_digit(void)
{
if (isdigit(*g_current))
return parse_number();
/* If not a digit, it's a parenthesis */
g_current++;
unsigned long long result = parse_result();
g_current++;
return result;
}
#ifdef PART2
/* Parse and compute a sum */
unsigned long long
parse_sum(void)
{
unsigned long long result = parse_digit();
while (*g_current == '+') {
g_current++;
result += parse_digit();
}
return result;
}
/* Parse and compute a product */
unsigned long long
parse_product(void)
{
unsigned long long result = parse_sum();
while (*g_current == '*') {
g_current++;
result *= parse_sum();
}
return result;
}
#endif
/* Parse and compute a sum */
unsigned long long
parse_result(void)
{
#ifdef PART2
return parse_product();
#else
unsigned long long result = parse_digit();
while (*g_current == '+' || *g_current == '*') {
if (*g_current++ == '+')
result += parse_digit();
else
result *= parse_digit();
}
return result;
#endif
}
/* Remove the spaces from user input */
static void
remove_spaces(char *str)
{
char const *c = str;
do
while (*c == ' ')
c++;
while ((*str++ = *c++));
}
int
main(void)
{
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
if (!(fp = fopen("input", "r")))
err(EXIT_FAILURE, "fopen");
unsigned long long acc = 0;
while ((read = getline(&line, &len, fp)) != -1) {
remove_spaces(line);
g_current = line;
acc += parse_result();
}
printf("%llu\n", acc);
return EXIT_SUCCESS;
}
|