2023-12-03 17:57:26 +04:00
|
|
|
#define _GNU_SOURCE
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <stdint.h>
|
|
|
|
#include <stdbool.h>
|
2023-12-03 19:01:32 +04:00
|
|
|
|
|
|
|
#define ISDIGIT(c) (c >= 0x30 && c <= 0x39)
|
2023-12-03 17:57:26 +04:00
|
|
|
|
|
|
|
int main(int argc, char **argv) {
|
|
|
|
FILE *input;
|
|
|
|
char *line = NULL;
|
|
|
|
size_t line_length = 0;
|
|
|
|
|
|
|
|
if (argc == 1 || argv[1][0] == '-')
|
|
|
|
input = stdin;
|
|
|
|
else if ((input = fopen(argv[1], "r")) == NULL) {
|
|
|
|
printf("Cannot open file %s\n", argv[1]);
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
char **engine = NULL;
|
|
|
|
ssize_t engine_line_size = 0;
|
|
|
|
ssize_t engine_lines = 0;
|
|
|
|
|
|
|
|
while (getline(&line, &line_length, input) != -1) {
|
|
|
|
ssize_t len = strlen(line)-1;
|
|
|
|
if (engine == NULL) {
|
|
|
|
engine = (char **) calloc(len, sizeof(char*));
|
|
|
|
engine_line_size = len;
|
|
|
|
}
|
|
|
|
|
|
|
|
engine[engine_lines] = (char*) calloc(len, sizeof(char));
|
|
|
|
memcpy(engine[engine_lines], line, len);
|
|
|
|
++engine_lines;
|
|
|
|
|
|
|
|
memset(line, 0, line_length);
|
|
|
|
}
|
|
|
|
|
|
|
|
int32_t part_number = 0;
|
|
|
|
|
|
|
|
int32_t n = 0;
|
|
|
|
int32_t multiplier = 1;
|
|
|
|
bool adjacent = false;
|
|
|
|
|
|
|
|
for (ssize_t i = engine_lines-1; i >= 0; --i) {
|
|
|
|
for (ssize_t j = engine_line_size-1; j >= 0; --j) {
|
2023-12-03 19:01:32 +04:00
|
|
|
if (ISDIGIT(engine[i][j])) {
|
2023-12-03 17:57:26 +04:00
|
|
|
n += (engine[i][j]&0xf) * multiplier;
|
|
|
|
multiplier *= 10;
|
|
|
|
|
2023-12-03 19:01:32 +04:00
|
|
|
if (adjacent == false && ((j+1 <= engine_line_size-1 && !ISDIGIT(engine[i][j+1]) && engine[i][j+1] != '.') ||
|
|
|
|
(j-1 >=0 && !ISDIGIT(engine[i][j-1]) && engine[i][j-1] != '.') ||
|
|
|
|
(i+1 <= engine_lines-1 && !ISDIGIT(engine[i+1][j]) && engine[i+1][j] != '.') ||
|
|
|
|
(i-1 >= 0 && !ISDIGIT(engine[i-1][j]) && engine[i-1][j] != '.') ||
|
|
|
|
((i+1 <= engine_lines-1 && j+1 <= engine_line_size-1) && !ISDIGIT(engine[i+1][j+1]) && engine[i+1][j+1] != '.') ||
|
|
|
|
((i+1 <= engine_lines-1 && j-1 >= 0) && !ISDIGIT(engine[i+1][j-1]) && engine[i+1][j-1] != '.') ||
|
|
|
|
((i-1 >= 0 && j+1 <= engine_line_size-1) && !ISDIGIT(engine[i-1][j+1]) && engine[i-1][j+1] != '.') ||
|
|
|
|
((i-1 >= 0 && j-1 >= 0) && !ISDIGIT(engine[i-1][j-1]) && engine[i-1][j-1] != '.'))) {
|
2023-12-03 17:57:26 +04:00
|
|
|
adjacent = true;
|
|
|
|
}
|
|
|
|
}
|
2023-12-03 19:01:32 +04:00
|
|
|
if ((!ISDIGIT(engine[i][j]) || j == 0) && n != 0) {
|
2023-12-03 17:57:26 +04:00
|
|
|
if (adjacent)
|
|
|
|
part_number += n;
|
|
|
|
n = 0;
|
|
|
|
multiplier = 1;
|
|
|
|
adjacent = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for (ssize_t i = 0; i < engine_lines; ++i)
|
|
|
|
free(engine[i]);
|
|
|
|
free(engine);
|
|
|
|
|
|
|
|
printf("%d\n", part_number);
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|