diff options
-rw-r--r-- | .gitignore | 2 | ||||
-rw-r--r-- | 03/.gitignore | 1 | ||||
-rw-r--r-- | 03/main.cc | 89 | ||||
-rw-r--r-- | 03/makefile | 4 |
4 files changed, 95 insertions, 1 deletions
@@ -1 +1 @@ -*/input.txt +*/*.txt diff --git a/03/.gitignore b/03/.gitignore new file mode 100644 index 0000000..ba2906d --- /dev/null +++ b/03/.gitignore @@ -0,0 +1 @@ +main diff --git a/03/main.cc b/03/main.cc new file mode 100644 index 0000000..b452c95 --- /dev/null +++ b/03/main.cc @@ -0,0 +1,89 @@ +#include <bits/stdc++.h> +using namespace std; + +const vector<char> SYMBOLS = {'#', '$', '%', '&', '*', '+', '-', '/', '=', '@'}; +const vector<char> NUMBERS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; + +int main() { + // phase 1 -- read lines into buffer + vector<string> lines; + for (string line; getline(cin, line);) + lines.push_back(line); + size_t rows = lines.size(); + size_t cols = lines[0].size(); + + // phase 2 -- create valid number mask + vector<vector<bool>> valid_mask(rows, vector<bool>(cols, false)); + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + // row and column offset for checking diagonals too + for (int roff = -1; roff <= 1; roff++) { + for (int coff = -1; coff <= 1; coff++) { + // skip any x,y coordinates that are outide the "grid" + int y = i + roff; + if (y < 0) continue; + if (y >= rows) continue; + int x = j + coff; + if (x < 0) continue; + if (x >= cols) continue; + + for (char symbol : SYMBOLS) + if (lines[y][x] == symbol) + valid_mask[i][j] = true; + } + } + } + } + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) + printf("%c", lines[i][j]); + printf("\n"); + } + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) + printf("%c", valid_mask[i][j] ? 'x' : ' '); + printf("\n"); + } + + // phase 3 -- read each number and add to output if any of its digits are + // true in valid_mask + int output = 0; + int digit = 0; + int valid_digit = false; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + char cell = lines[i][j]; + bool valid = valid_mask[i][j]; + int last_digit = digit; + for (char num : NUMBERS) { + if (cell != num) + continue; + + // printf("[%c]", cell); + digit *= 10; + digit += cell - '0'; + if (valid) + valid_digit = true; + } + if (digit == last_digit && digit != 0) { + // printf(" (inline, %d, %s)\n", digit, valid_digit ? "valid" : "not valid"); + if (valid_digit) + output += digit; + digit = 0; + valid_digit = false; + } + } + if (digit != 0) { + // printf(" (EOL, %d, %s)\n", digit, valid_digit ? "valid" : "not valid"); + if (valid_digit) + output += digit; + digit = 0; + valid_digit = false; + } + } + + printf(">> %d\n", output); + + return 0; +} diff --git a/03/makefile b/03/makefile new file mode 100644 index 0000000..a78e3da --- /dev/null +++ b/03/makefile @@ -0,0 +1,4 @@ +main: main.cc +clean: + $(RM) main + |