1.c (3160B)
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <ctype.h> 5 #include <stdbool.h> 6 7 int main() { 8 int LINE_LENGTH = 140; 9 FILE *inputfile = fopen("./input", "r"); 10 char line[2048] = { 0 }; 11 size_t len = 0; 12 ssize_t read; 13 if (inputfile == NULL) { 14 printf("Input file not found. Exiting."); 15 exit(1); 16 } 17 char **lines = malloc(sizeof(char *) * LINE_LENGTH); 18 int line_count = 0; 19 while (fgets(line, 1024, inputfile)) { 20 lines[line_count] = malloc(sizeof(char) * 2048); 21 strcpy(lines[line_count], line); 22 line_count++; 23 } 24 int *goodnumbers = malloc(sizeof(int) * 4096); 25 int goodnumber_count = 0; 26 for (int i = 0; i < LINE_LENGTH; i++) { 27 char *line = lines[i]; 28 for (int j = 0; j < strlen(lines[i]); j++) { 29 bool append = false; 30 char *number = malloc(sizeof(char) * 2048); 31 while (isdigit(*(line + j)) != 0) { 32 number[strlen(number)] = line[j]; 33 // check left and right is symbol or not 34 int prev = j - 1; 35 int next = j + 1; 36 if (prev > 0) { 37 if (line[prev] != '.' && isdigit(line[prev]) == 0) { 38 // append to good numbers 39 append = true; 40 } 41 // check if on first line, as we can't go back further then check is previous line previous char is symbol or not 42 if (i != 0 && lines[i - 1][prev] != '.' && isdigit(lines[i - 1][prev]) == 0) { 43 append = true; 44 } 45 // check if next line exists 46 if (i != LINE_LENGTH - 1 && lines[i + 1][prev] != '.' && isdigit(lines[i + 1][prev]) == 0) { 47 append = true; 48 } 49 } 50 if (next <= strlen(line) - 1) { 51 if (line[next] != '.' && line[next] != '\n' && isdigit(line[next]) == 0) { 52 append = true; 53 } 54 55 if (i != 0 && lines[i - 1][next] != '.' && lines[i - 1][next] != '\n' && isdigit(lines[i - 1][next]) == 0) { 56 append = true; 57 } 58 if (i != LINE_LENGTH - 1 && lines[i + 1][next] != '.' && lines[i + 1][next] != '\n' && isdigit(lines[i + 1][next]) == 0) { 59 append = true; 60 } 61 } 62 if (i != 0 && lines[i - 1][j] != '.' && isdigit(lines[i - 1][j]) == 0) { 63 append = true; 64 } 65 if (i != LINE_LENGTH - 1 && lines[i + 1][j] != '.' && isdigit(lines[i + 1][j]) == 0) { 66 append = true; 67 } 68 j++; 69 } 70 if (append) { 71 goodnumbers[goodnumber_count] = atoi(number); 72 goodnumber_count++; 73 append = false; 74 } 75 76 } 77 } 78 int sum = 0; 79 for (int i = 0; i < goodnumber_count; i++) { 80 sum += goodnumbers[i]; 81 } 82 printf("Sum: %d\n", sum); 83 }