AdventOfCode2024/src/HistorianHysteria.cpp

71 lines
2.2 KiB
C++

// Solutions to the Advent Of Code 2024.
// Copyright (C) 2024 Stefan Müller
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <http://www.gnu.org/licenses/>.
#include <iostream>
#include <aoc/HistorianHysteria.hpp>
const std::string HistorianHysteria::getPuzzleName() const
{
return "Day 1: Historian Hysteria";
}
const std::string HistorianHysteria::getInputFileName() const
{
return "historian_hysteria.txt";
}
void HistorianHysteria::processDataLine(const std::string& line)
{
auto pos{ line.find(" ") };
left_.insert(std::stoi(line.substr(0, pos)));
right_.insert(std::stoi(line.substr(pos + 3)));
}
void HistorianHysteria::finish()
{
int prev{ 0 };
auto nSame{ 0 };
auto leftIterator{ left_.begin() };
auto rightIterator{ right_.begin() };
auto rightSameIterator{ right_.begin() };
while (leftIterator != left_.end())
{
part1 += abs(*leftIterator - *rightIterator);
if (prev != *leftIterator)
{
nSame = 0;
// Skips over numbers in the right list that are smaller than the current left number.
while (rightSameIterator != right_.end() && *rightSameIterator < *leftIterator)
{
rightSameIterator++;
}
// Counts the occurrences of the current left number in the right list.
while (rightSameIterator != right_.end() && *rightSameIterator == *leftIterator)
{
rightSameIterator++;
nSame++;
}
prev = *leftIterator;
}
part2 += *leftIterator * nSame;
leftIterator++;
rightIterator++;
}
}