From 1fce1637670c682f76c384685dd91df741eb6534 Mon Sep 17 00:00:00 2001 From: Reimar Date: Wed, 17 Dec 2025 12:28:48 +0100 Subject: [PATCH] Solve day 3 part 2 --- day_3.cpp | 38 +++++++++++++++++++++----------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/day_3.cpp b/day_3.cpp index 5c441a9..6f9a1f3 100644 --- a/day_3.cpp +++ b/day_3.cpp @@ -5,31 +5,35 @@ int main() { std::ifstream file("input.txt"); - int joltage_sum = 0; + long long int joltage_sum = 0; + const int digit_count = 2; // Use 12 for part 2 std::string bank; while (getline(file, bank)) { - int first_index; - for (int i = 9; i > 0; i--) { - char digit = i + 48; + int indices[digit_count]; - first_index = bank.find(digit); + for (int digit_index = 0; digit_index < digit_count; digit_index++) { + for (int i = 9; i > 0; i--) { + char digit = i + 48; - if (first_index != bank.size() - 1 && first_index != std::string::npos) - break; + // Start from previous index + int start_pos = digit_index == 0 ? 0 : indices[digit_index - 1] + 1; + + int index = bank.find(digit, start_pos); + + if (index < bank.size() - digit_count + digit_index + 1 && index != std::string::npos) { + indices[digit_index] = index; + break; + } + } } - int second_index; - for (int i = 9; i > 0; i--) { - char digit = i + 48; - - second_index = bank.find(digit, first_index + 1); - - if (second_index != std::string::npos) - break; + // Collect characters into a single number + std::string joltage_str; + for (int index : indices) { + joltage_str += bank[index]; } - - int joltage = std::stoi(std::string { bank[first_index], bank[second_index] }); + long long int joltage = std::stoll(joltage_str); std::cout << joltage << std::endl;