From 01e9ab307ec7bc84d160d8fb56ade90026ca7ddf Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Sun, 13 Dec 2020 18:31:55 -0500 Subject: [PATCH] Add solution to day 13 part 2 --- day13/day13.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/day13/day13.cpp b/day13/day13.cpp index 758f1ca..ce37153 100644 --- a/day13/day13.cpp +++ b/day13/day13.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -65,6 +66,39 @@ int part1(int busStartTime, const std::vector &rawBusTimes) { return bestBusID * timeToWait; } +long part2(const std::vector rawBusTimes) { + int nextBusOffsset = 0; + // Holds both the bus time and its offset from the time t. + std::vector> busTimes; + busTimes.reserve(rawBusTimes.size()); + for (auto it = rawBusTimes.cbegin(); it != rawBusTimes.cend(); (it++, nextBusOffsset++)) { + auto rawBusTime = *it; + if (rawBusTime == OUT_OF_SERVICE_BUS) { + continue; + } + + int busTime = std::stoi(rawBusTime); + busTimes.emplace_back(busTime, nextBusOffsset); + } + + auto cursor = busTimes.cbegin(); + long t = cursor->first; + long stepSize = cursor->first; + cursor++; + while (cursor != busTimes.cend()) { + t += stepSize; + // Find the time that next bus that will start at the offset after t + if ((t + cursor->second) % cursor->first != 0) { + continue; + } + + stepSize = std::lcm(stepSize, cursor->first); + cursor++; + } + + return t; +} + int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << argv[0] << " " << std::endl; @@ -75,4 +109,5 @@ int main(int argc, char *argv[]) { auto parsedInput = splitInput(input); std::cout << part1(parsedInput.first, parsedInput.second) << std::endl; + std::cout << part2(parsedInput.second) << std::endl; }