Solve day 3 part 2

This commit is contained in:
Reimar 2025-12-17 12:28:48 +01:00
parent 06c7f55681
commit 1fce163767

View File

@ -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;
int indices[digit_count];
for (int digit_index = 0; digit_index < digit_count; digit_index++) {
for (int i = 9; i > 0; i--) {
char digit = i + 48;
first_index = bank.find(digit);
// Start from previous index
int start_pos = digit_index == 0 ? 0 : indices[digit_index - 1] + 1;
if (first_index != bank.size() - 1 && first_index != std::string::npos)
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;
}
}
int joltage = std::stoi(std::string { bank[first_index], bank[second_index] });
// Collect characters into a single number
std::string joltage_str;
for (int index : indices) {
joltage_str += bank[index];
}
long long int joltage = std::stoll(joltage_str);
std::cout << joltage << std::endl;