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");
|
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;
|
std::string bank;
|
||||||
while (getline(file, bank)) {
|
while (getline(file, bank)) {
|
||||||
int first_index;
|
int indices[digit_count];
|
||||||
for (int i = 9; i > 0; i--) {
|
|
||||||
char digit = i + 48;
|
|
||||||
|
|
||||||
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)
|
// Start from previous index
|
||||||
break;
|
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;
|
// Collect characters into a single number
|
||||||
for (int i = 9; i > 0; i--) {
|
std::string joltage_str;
|
||||||
char digit = i + 48;
|
for (int index : indices) {
|
||||||
|
joltage_str += bank[index];
|
||||||
second_index = bank.find(digit, first_index + 1);
|
|
||||||
|
|
||||||
if (second_index != std::string::npos)
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
long long int joltage = std::stoll(joltage_str);
|
||||||
int joltage = std::stoi(std::string { bank[first_index], bank[second_index] });
|
|
||||||
|
|
||||||
std::cout << joltage << std::endl;
|
std::cout << joltage << std::endl;
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user