parent
37d59142ab
commit
85712eff12
2 changed files with 84 additions and 3 deletions
@ -1,9 +1,84 @@ |
||||
#include "Day08.h" |
||||
|
||||
Result Day08::Task1() { |
||||
return Day::Task1(); |
||||
Map map = parseMap(); |
||||
vector<uint8_t> instructions = parseInstructions(); |
||||
|
||||
uint64 steps = 0; |
||||
size_t instructionIndex = 0; |
||||
string node = "AAA"; |
||||
while (node != "ZZZ"){ |
||||
node = map[node][instructions[instructionIndex]]; |
||||
steps++; |
||||
instructionIndex = (++instructionIndex) % instructions.size(); |
||||
} |
||||
|
||||
return to_string(steps); |
||||
} |
||||
|
||||
Result Day08::Task2() { |
||||
return Day::Task2(); |
||||
Map map = parseMap(); |
||||
vector<uint8_t> instructions = parseInstructions(); |
||||
|
||||
vector<string> nodes; |
||||
for (auto [node, path] : map) |
||||
if (node.ends_with('A')) |
||||
nodes.push_back(node); |
||||
|
||||
vector<uint64> allSteps; |
||||
|
||||
for (string &node : nodes){ |
||||
uint64 steps = 0; |
||||
size_t instructionIndex = 0; |
||||
|
||||
while (!node.ends_with('Z')){ |
||||
node = map[node][instructions[instructionIndex]]; |
||||
steps++; |
||||
instructionIndex = (++instructionIndex) % instructions.size(); |
||||
} |
||||
|
||||
allSteps.push_back(steps); |
||||
} |
||||
|
||||
uint64 lcm = 1; |
||||
for (uint64 steps : allSteps) |
||||
lcm = LCM(lcm, steps); |
||||
|
||||
return to_string(lcm); |
||||
} |
||||
|
||||
Day08::Map Day08::parseMap() const { |
||||
Map map; |
||||
|
||||
for (size_t i = 2; i < input.size(); i++){ |
||||
string line = input[i]; |
||||
string source = line.substr(0, 3); |
||||
string left = line.substr(7, 3); |
||||
string right = line.substr(12, 3); |
||||
map[source] = {left, right}; |
||||
} |
||||
|
||||
return map; |
||||
} |
||||
|
||||
vector<uint8_t> Day08::parseInstructions() const { |
||||
vector<uint8_t> instructions; |
||||
|
||||
for (const char c : input[0]) |
||||
instructions.push_back(c == 'L' ? 0 : 1); |
||||
|
||||
return instructions; |
||||
} |
||||
|
||||
uint64 Day08::GCD(uint64 a, uint64 b) { |
||||
while (b != 0){ |
||||
uint64 t = b; |
||||
b = a % b; |
||||
a = t; |
||||
} |
||||
return a; |
||||
} |
||||
|
||||
uint64 Day08::LCM(uint64 a, uint64 b) { |
||||
return a * b / GCD(a, b); |
||||
} |
Loading…
Reference in new issue