Day 7: Part 2

This commit is contained in:
Fawkes100 2024-12-12 08:26:26 +01:00
parent d8254a5414
commit 6a168bab4e

View File

@ -55,7 +55,18 @@ std::vector<Equation> parseEquations(std::vector<std::string>& stringEquations)
return equations;
}
bool backtrack(int index, uint64_t current_value, const Equation& equation) {
uint64_t concatenate(uint64_t a, uint64_t b) {
uint64_t temp = b;
while (temp > 0) {
a *= 10; // Multipliziere a mit 10, um Platz für die nächste Ziffer zu schaffen
temp /= 10; // Teile temp durch 10, um die Länge zu bestimmen
}
return a + b; // Verkette die Zahlen
}
bool backtrack(int index, uint64_t current_value, const Equation& equation, bool enableConcatOp) {
// Basisfall: We have processed all numbers
if(index == equation.numbers.size()) {
return current_value == equation.testValue;
@ -65,25 +76,31 @@ bool backtrack(int index, uint64_t current_value, const Equation& equation) {
uint64_t next_number = equation.numbers.at(index);
// Option 1 : Add the next number
if(backtrack(index + 1, current_value + next_number, equation)) {
if(backtrack(index + 1, current_value + next_number, equation, enableConcatOp)) {
return true;
}
if(backtrack(index + 1, current_value * next_number, equation)) {
if(backtrack(index + 1, current_value * next_number, equation, enableConcatOp)) {
return true;
}
if(enableConcatOp) {
if(backtrack(index + 1, concatenate(current_value, next_number), equation, enableConcatOp)) {
return true;
}
}
return false;
}
bool isEquationCorrect(const Equation& equation) {
return backtrack(1, equation.numbers[0], equation);
bool isEquationCorrect(const Equation& equation, bool enableConcatOp) {
return backtrack(1, equation.numbers[0], equation, enableConcatOp);
}
std::vector<Equation> determineCorrectEquations(std::vector<Equation>& equations) {
std::vector<Equation> determineCorrectEquations(std::vector<Equation>& equations, bool enableCocatOp) {
std::vector<Equation> correctEquations;
for(const auto& equation : equations) {
if(isEquationCorrect(equation)) {
if(isEquationCorrect(equation, enableCocatOp)) {
correctEquations.push_back(equation);
}
}
@ -101,7 +118,11 @@ uint64_t calcTotalCalibResult(std::vector<Equation>& equations) {
int main() {
std::vector<std::string> input = readTextFromFile("../input.txt");
std::vector<Equation> equatons = parseEquations(input);
std::vector<Equation> correctEquations = determineCorrectEquations(equatons);
std::vector<Equation> correctEquations = determineCorrectEquations(equatons, false);
std::cout << "The total calibration value is " << calcTotalCalibResult(correctEquations) << std::endl;
std::vector<Equation> correctEquationsConcat = determineCorrectEquations(equatons, true);
std::cout << "The total calibration with Concat Op value is " << calcTotalCalibResult(correctEquationsConcat) << std::endl;
std::cout << "Test: " << concatenate(15, 6) << std::endl;
return 0;
}