-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadventofcodeday6.c
More file actions
67 lines (63 loc) · 1.35 KB
/
adventofcodeday6.c
File metadata and controls
67 lines (63 loc) · 1.35 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void do_moltiplication(char **lines, int i, int n, ulong *sum) {
ulong product = 1;
ulong j;
int offset;
for (int i = 0; i < n; i++) {
sscanf(lines[i], "%lu %n", &j, &offset);
product *= j;
lines[i] += offset;
}
*sum += product;
}
void do_sum(char **lines, int i, int n, ulong *sum) {
ulong j;
int offset;
for (int i = 0; i < n; i++) {
sscanf(lines[i], "%lu %n", &j, &offset);
*sum += j;
lines[i] += offset;
}
}
void perform_calculations(char **lines, int n) {
ulong sum = 0;
char operand = 0;
int loop = 1;
int i = 0;
while (loop) {
sscanf(lines[n - 1] + i, "%c", &operand);
switch (operand) {
case 43:
do_sum(lines, i, n - 1, &sum);
break;
case 42:
do_moltiplication(lines, i, n - 1, &sum);
break;
}
i++;
if (lines[n - 1][i] == '\0') {
loop = 0;
}
}
printf("Sum: %lu\n", sum);
}
int main(void) {
char **lines = NULL;
size_t len = 0;
FILE *file = fopen("input", "r");
if (file == NULL) {
printf("Error opening file\n");
return 1;
}
int i;
int nread;
for (i = 0, nread = 0; nread != -1; i++) {
lines = realloc(lines, (i + 1) * sizeof(char *));
nread = (int)getline(&lines[i], &len, file);
}
perform_calculations(lines, i - 1);
fclose(file);
}