Skip to content

Instantly share code, notes, and snippets.

@tungurlakachakcak
Created December 12, 2023 08:34
Show Gist options
  • Save tungurlakachakcak/04a745c466c72f9b7838a115df595752 to your computer and use it in GitHub Desktop.
Save tungurlakachakcak/04a745c466c72f9b7838a115df595752 to your computer and use it in GitHub Desktop.
Advent Of Code - Day 1
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
#include <math.h>
using namespace std;
int main()
{
ifstream infile("input.txt");
if (!infile.is_open()) {
cout << "File prob\n"; return -1;
}
string line;
unsigned long long sum = 0;
string nums[10]{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
while (infile.good()) {
getline(infile, line);
int idxs[10]{ -1,-1,-1,-1,-1,-1,-1,-1 };
int maxidxs[10] = { -1,-1,-1,-1,-1,-1,-1,-1 };
long long minIdx = 99999999, firstN = 0, lastN = 0, maxIdx = -1;
// Find the index of first and last digit or 'digit word'
for (size_t i = 0; i < 10; i++) {
idxs[i] = min(line.find(nums[i], 0), line.find(to_string(i), 0));
maxidxs[i] = max(static_cast<int>(line.rfind(nums[i])), static_cast<int>(line.rfind(to_string(i))));
}
// Look through the indexes and get the actual first and last digit
for (size_t i = 0; i < 10; i++) {
if (idxs[i] != -1 && idxs[i] < minIdx) {
minIdx = idxs[i];
firstN = i;
}
if (maxidxs[i] > maxIdx) {
maxIdx = maxidxs[i];
lastN = i;
}
}
sum += (10 * firstN) + lastN;
}
cout << "Sum " << sum << "\n";
infile.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment