diff --git a/src/days/08/Day08.cpp b/src/days/08/Day08.cpp index 047f516..1ae275f 100644 --- a/src/days/08/Day08.cpp +++ b/src/days/08/Day08.cpp @@ -1,9 +1,84 @@ #include "Day08.h" Result Day08::Task1() { - return Day::Task1(); + Map map = parseMap(); + vector 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(); -} \ No newline at end of file + Map map = parseMap(); + vector instructions = parseInstructions(); + + vector nodes; + for (auto [node, path] : map) + if (node.ends_with('A')) + nodes.push_back(node); + + vector 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 Day08::parseInstructions() const { + vector 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); +} diff --git a/src/days/08/Day08.h b/src/days/08/Day08.h index d0933bd..0a38f83 100644 --- a/src/days/08/Day08.h +++ b/src/days/08/Day08.h @@ -3,8 +3,14 @@ #include "../../Day.h" class Day08 : public Day { + typedef map> Map; protected: Result Task1() override; Result Task2() override; + + vector parseInstructions() const; + Map parseMap() const; + static uint64 GCD(uint64 a, uint64 b); + static uint64 LCM(uint64 a, uint64 b); }; \ No newline at end of file