Solve day 3 part 2
This commit is contained in:
parent
06c7f55681
commit
1fce163767
38
day_3.cpp
38
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;
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user