mirror of
https://github.com/SebastianStork/advent-of-code.git
synced 2026-01-21 15:41:34 +01:00
Solve 2024 day 7 part 1
This commit is contained in:
parent
38f737d72d
commit
c644cf55d8
4 changed files with 941 additions and 0 deletions
75
2024/day-07/main.cpp
Normal file
75
2024/day-07/main.cpp
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
#include <cmath>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
struct Equation
|
||||
{
|
||||
long result;
|
||||
vector<int> numbers;
|
||||
};
|
||||
|
||||
void readInput(vector<Equation> &equations)
|
||||
{
|
||||
string line;
|
||||
while (getline(cin, line)) {
|
||||
stringstream stream(line);
|
||||
Equation equation;
|
||||
|
||||
string result;
|
||||
getline(stream, result, ':');
|
||||
equation.result = stol(result);
|
||||
|
||||
int number;
|
||||
while (stream >> number) {
|
||||
equation.numbers.push_back(number);
|
||||
}
|
||||
|
||||
equations.push_back(equation);
|
||||
}
|
||||
}
|
||||
|
||||
long computeEquationResult(const vector<int> &numbers, const size_t operatorMask)
|
||||
{
|
||||
long testResult = numbers[0];
|
||||
|
||||
for (size_t numberIndex = 1; numberIndex < numbers.size(); numberIndex++) {
|
||||
if (operatorMask & (1 << (numberIndex - 1))) {
|
||||
testResult += numbers[numberIndex];
|
||||
} else {
|
||||
testResult *= numbers[numberIndex];
|
||||
}
|
||||
}
|
||||
|
||||
return testResult;
|
||||
}
|
||||
|
||||
bool isValidEquation(const Equation &equation)
|
||||
{
|
||||
const int operatorCount = equation.numbers.size() - 1;
|
||||
const size_t operatorMaskLimit = pow(2, operatorCount) - 1;
|
||||
|
||||
for (size_t operatorMask = 0; operatorMask <= operatorMaskLimit; operatorMask++) {
|
||||
if (computeEquationResult(equation.numbers, operatorMask) == equation.result) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
vector<Equation> equations;
|
||||
readInput(equations);
|
||||
|
||||
long totalCalibrationResult = 0;
|
||||
for (const Equation &equation : equations) {
|
||||
totalCalibrationResult += equation.result * isValidEquation(equation);
|
||||
}
|
||||
|
||||
// Part one
|
||||
cout << "Total Calibration Result: " << totalCalibrationResult << endl;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue