parent
ee36ea57db
commit
14ff577615
3 changed files with 113 additions and 3 deletions
@ -1,9 +1,102 @@ |
||||
#include "Day03.h" |
||||
|
||||
Result Day03::Task1() { |
||||
return Day::Task1(); |
||||
uint32_t sum = 0; |
||||
|
||||
auto isSymbol = [this](int32_t x, int32_t y) -> bool { |
||||
if (x < 0 || x > input[0].length() - 1 || |
||||
y < 0 || y > input.size() - 1){ |
||||
return false; |
||||
} |
||||
char c = input[y][x]; |
||||
return !isDigit(c) && c != '.'; |
||||
}; |
||||
|
||||
for (const auto &[number, position] : parseEngineNumbers()){ |
||||
auto &[value, size] = number; |
||||
auto &[x, y] = position; |
||||
|
||||
bool symbolFound = false; |
||||
for (int32_t sx = x - 1; sx < x + size + 1; sx++){ |
||||
for (int32_t sy = y - 1; sy < y + 2; sy++){ |
||||
if (isSymbol(sx, sy)){ |
||||
symbolFound = true; |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
if (symbolFound) |
||||
sum += value; |
||||
} |
||||
|
||||
return to_string(sum); |
||||
} |
||||
|
||||
Result Day03::Task2() { |
||||
return Day::Task2(); |
||||
uint32_t sum = 0; |
||||
|
||||
map<pair<size_t, size_t>, set<EngineNumber>> stars; |
||||
|
||||
auto isStar = [this](int32_t x, int32_t y) -> bool { |
||||
if (x < 0 || x > input[0].length() - 1 || |
||||
y < 0 || y > input.size() - 1){ |
||||
return false; |
||||
} |
||||
return input[y][x] == '*'; |
||||
}; |
||||
|
||||
for (const auto &[number, position] : parseEngineNumbers()){ |
||||
auto &[value, size] = number; |
||||
auto &[x, y] = position; |
||||
|
||||
for (int32_t sx = x - 1; sx < x + size + 1; sx++){ |
||||
for (int32_t sy = y - 1; sy < y + 2; sy++){ |
||||
if (isStar(sx, sy)){ |
||||
if (stars.contains({sx, sy})){ |
||||
stars[{sx, sy}].insert({number, position}); |
||||
} else { |
||||
stars[{sx, sy}] = {{number, position}}; |
||||
} |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
for (auto &[position, numbers] : stars){ |
||||
if (numbers.size() == 2){ |
||||
sum += numbers.begin()->first.first * (++numbers.begin())->first.first; |
||||
} |
||||
} |
||||
|
||||
return to_string(sum); |
||||
} |
||||
|
||||
vector<Day03::EngineNumber> Day03::parseEngineNumbers() const { |
||||
vector<EngineNumber> numbers; |
||||
|
||||
for (size_t y = 0; y < input.size(); y++){ |
||||
const string& line = input[y]; |
||||
uint32_t value = 0; |
||||
uint8_t valueLength = 0; |
||||
bool readingValue = false; |
||||
|
||||
for (size_t x = 0; x < line.length(); x++){ |
||||
uint8_t digit; |
||||
if (isDigit(line[x], digit)){ |
||||
value = value * 10 + digit; |
||||
valueLength++; |
||||
readingValue = true; |
||||
if (x == line.length() - 1) |
||||
numbers.push_back({{value, valueLength}, {x - valueLength, y}}); |
||||
} else { |
||||
if (readingValue) |
||||
numbers.push_back({{value, valueLength}, {x - valueLength, y}}); |
||||
readingValue = false; |
||||
valueLength = 0; |
||||
value = 0; |
||||
} |
||||
} |
||||
} |
||||
|
||||
return numbers; |
||||
} |
Loading…
Reference in new issue