Skip to content

Commit

Permalink
improve ex01
Browse files Browse the repository at this point in the history
  • Loading branch information
JellevanKraaij committed Dec 3, 2023
1 parent df78a8b commit 332d17c
Showing 1 changed file with 41 additions and 31 deletions.
72 changes: 41 additions & 31 deletions day03/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,27 @@

using namespace std;

array<pair<int, int>, 8> directions = {{{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}}};

inline bool isSymbol(char c) {
return (!isdigit(c) && c != '.');
}

enum Type { empty, symbol, number };
using Element = pair<Type, int>;
using Row = vector<Element>;
using Map = vector<Row>;

template <typename T>
bool checkSurrounding(T &map, int i, int j, function<bool(Element)> check) {
static const array<pair<int, int>, 8> directions = {{{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}}};
for (auto [id, jd] : directions) {
if (i + id < 0 || i + id >= map.size() || j + jd < 0 || j + jd >= map[i].size())
continue;
if (check(map[i + id][j + jd]))
return true;
}
return false;
}

int main(int argc, char **argv) {
if (argc != 2) {
cout << "Usage: " << argv[0] << " inputfile" << endl;
Expand All @@ -27,43 +42,38 @@ int main(int argc, char **argv) {
}

string line;
vector<vector<char>> map;
Map map;
while (getline(inputFile, line)) {
vector<char> row;
for (auto &c : line) {
row.push_back(c);
Row row;
for (size_t i = 0; i < line.size(); ++i) {
if (isdigit(line[i])) {
int number = stoi(line.substr(i));
for (; isdigit(line[i]); ++i)
row.push_back({Type::number, number});
--i;
} else if (isSymbol(line[i]))
row.push_back({Type::symbol, line[i]});
else
row.push_back({Type::empty, 0});
}
map.push_back(row);
}

int total = 0;
for (size_t i = 0; i < map.size(); ++i) {
stringstream ss;
bool symbol = false;
for (size_t j = 0; j < map[i].size() + 1; ++j) {
if (j < map[i].size() && isdigit(map[i][j])) {
ss << map[i][j];
for (auto [id, jd] : directions) {
if (i + id < 0 || i + id >= map.size() || j + jd < 0 || j + jd >= map[i].size())
continue;
if (isSymbol(map[i + id][j + jd]))
symbol = true;
}
} else {
if (ss.str().empty())
continue;
int value;
ss >> value;
ss = stringstream();
cout << value;
if (symbol) {
total += value;
symbol = false;
cout << "X";
}
cout << " ";
bool hasSymbol = false;
int number = 0;
for (size_t j = 0; j < map[i].size(); ++j) {
if (map[i][j].first == Type::number) {
number = map[i][j].second;
if (checkSurrounding(map, i, j, [](Element e) { return (e.first == Type::symbol); }))
hasSymbol = true;
}
if (map[i][j].first != Type::number && hasSymbol) {
total += number;
hasSymbol = false;
}
}
cout << endl;
}
cout << "Total: " << total << endl;
}

0 comments on commit 332d17c

Please sign in to comment.