#include #include #include // parse string into array of numbers bool parse_numbers(char *str_row, unsigned long int *row, int len) { int num = 0; for (int i = 0; str_row[i]; i++) { bool inced = false; while (str_row[i] < '0' || str_row[i] > '9') { if (str_row[i] == '\0') goto feck; if (!inced) num++; i++; inced = true; } // printf("assigning row[%d] = %lu when len=%d\n", num, row[num] * 10 + str_row[i] - '0', len); row[num] = row[num] * 10 + str_row[i] - '0'; } feck: return 1; } unsigned long int int_cat(unsigned long int a, unsigned long int b) { unsigned long int bee = b; a *= 10; while ((bee /= 10) > 0) { a *= 10; } return a += b; } // power! x to the y! int pow(int x, int y) { int ans = 1; for (int i = 0; i < y; i++) ans *= x; return ans; } bool possible(unsigned long int *row, int len) { // row[0] is the answer, len - 1 numbers, len - 2 operations //printf("answer: %d\n", row[0]); int variants = pow(4, len - 2); for (int i = 0; i < variants; i++) { unsigned long int sum = row[1]; for (int j = 2; j < len; j++) { if ((i >> ((j - 2) * 2) & 3) == 0) { sum = int_cat(sum, row[j]); } else if ((i >> ((j - 2) * 2) & 3) == 1) { sum = sum * row[j]; } else { sum = sum + row[j]; } } // printf("sum: %d\n", sum); if (sum == row[0]) { // printf("sum %lu worked\n", sum); return 1; } } return 0; } int main() { FILE *input; input = fopen("./input", "r"); char line[100] = {0}; unsigned long int sum = 0; while (fgets(line, sizeof(line), input)) { // count numonums, allocate array int numbers = 1; for (int c = 0; line[c]; c++) numbers += (line[c] == ' '); unsigned long int *row = calloc(numbers, sizeof(unsigned long int)); parse_numbers(line, row, numbers); if (possible(row, numbers)) sum = sum + row[0]; free(row); } printf("sum: %llu\n", sum); }