-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadventofcodeday2.c
More file actions
75 lines (66 loc) · 1.53 KB
/
adventofcodeday2.c
File metadata and controls
75 lines (66 loc) · 1.53 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
typedef struct {
u_long **lids;
u_long sum;
} product_ids;
void init(product_ids *prod_ids) {
prod_ids->lids = malloc(2 * sizeof(u_long *));
for (int i = 0; i < 2; i++) {
prod_ids->lids[i] = malloc(sizeof(u_long));
}
prod_ids->sum = 0;
}
void free_prod_ids(product_ids *prod_ids) {
for (int i = 0; i < 2; i++) {
free(prod_ids->lids[i]);
}
free(prod_ids->lids);
free(prod_ids);
}
int check_id(char *id) {
char *tmp = malloc(128);
for (u_long i = 0; i < (u_long)(strlen(id) / 2); i++) {
tmp[i] = id[i];
tmp[i + 1] = '\0';
}
return strstr(id + strlen(id) / 2, tmp) != NULL;
}
void check_ids(product_ids *prod_ids) {
char *id = malloc(128);
for (u_long i = *prod_ids->lids[0]; i <= *prod_ids->lids[1]; i++) {
sprintf(id, "%lu", i);
if (strlen(id) % 2 == 0) {
if (check_id(id)) {
prod_ids->sum += i;
};
}
}
}
int main() {
/*
char *s = "532525253252525325";
printf("%lu\n", strtoul(s, NULL, 10));
*/
product_ids *prod_ids = malloc(sizeof(product_ids));
init(prod_ids);
FILE *file = fopen("input", "r");
if (file == NULL) {
printf("Error opening file\n");
return 1;
}
while (fscanf(file, "%lu-%lu", prod_ids->lids[0], prod_ids->lids[1])) {
check_ids(prod_ids);
int c = fgetc(file);
if (c != 44) {
break;
}
ungetc(c, file);
fseek(file, 1, SEEK_CUR);
}
printf("Final sum is: %lu\n", prod_ids->sum);
free_prod_ids(prod_ids);
return 0;
}