Added a page mapping for day 5 to reduce the array size

This commit is contained in:
Stefan Müller 2024-12-06 10:20:39 +01:00
parent bc3edfd93c
commit cf19ba7b61
2 changed files with 25 additions and 7 deletions

View File

@ -20,11 +20,16 @@
#include "PrintQueue.h"
PrintQueue::PrintQueue()
: Solver{}, isProcessingOrderingRules_{ true }, orderingRules_{}
: Solver{}, pageNoMapIndex_{ 0 }, isProcessingOrderingRules_{ true }, orderingRules_{}
{
for (size_t i = 0; i <= maxPageNo_; i++)
{
for (size_t j = 0; j <= maxPageNo_; j++)
pageNoMap_[i] = -1;
}
for (size_t i = 0; i < nPages_; i++)
{
for (size_t j = 0; j < nPages_; j++)
{
orderingRules_[i][j] = false;
}
@ -64,12 +69,21 @@ void PrintQueue::finish()
{
}
size_t PrintQueue::getMapped(const int pageNo)
{
if (pageNoMap_[pageNo] < 0)
{
pageNoMap_[pageNo] = pageNoMapIndex_++;
}
return pageNoMap_[pageNo];
}
void PrintQueue::processOrderingRule(const std::string& line)
{
auto pos{ line.find("|") };
auto before{ std::stoi(line.substr(0, pos)) };
auto after{ std::stoi(line.substr(pos + 1)) };
orderingRules_[before][after] = true;
orderingRules_[getMapped(before)][getMapped(after)] = true;
}
void PrintQueue::processUpdatePages(const std::string& line)
@ -85,7 +99,7 @@ void PrintQueue::processUpdatePages(const std::string& line)
size_t i{ 0 };
while (isCorrectOrder && i < pages.size())
{
isCorrectOrder = !orderingRules_[page][pages[i]];
isCorrectOrder = !orderingRules_[getMapped(page)][getMapped(pages[i])];
i++;
}
pages.push_back(page);
@ -100,7 +114,7 @@ void PrintQueue::processUpdatePages(const std::string& line)
// This works because the input defines a complete ordering on the occurring
// page numbers.
std::sort(pages.begin(), pages.end(),
[&](int const& a, int const& b) { return orderingRules_[a][b]; });
[&](int const& a, int const& b) { return orderingRules_[getMapped(a)][getMapped(b)]; });
part2 += pages[pages.size() / 2];
}
}

View File

@ -27,9 +27,13 @@ class PrintQueue :
void processDataLine(const std::string& line) override;
void finish() override;
private:
static const size_t maxPageNo_{ 99 };
static const int nPages_{ 49 };
static const int maxPageNo_{ 99 };
bool isProcessingOrderingRules_;
bool orderingRules_[maxPageNo_ + 1][maxPageNo_ + 1];
int pageNoMapIndex_;
int pageNoMap_[maxPageNo_ + 1];
bool orderingRules_[nPages_][nPages_];
size_t getMapped(const int pageNo);
void processOrderingRule(const std::string& line);
void processUpdatePages(const std::string& line);
};