advent-of-code/2023/1/main.cpp

57 lines
861 B
C++
Raw Normal View History

2023-12-03 14:34:24 -08:00
#include <bits/stdc++.h>
using namespace std;
const string NUMBERS[] = {
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int ret = 0;
string line;
2023-12-03 16:15:40 -08:00
while (getline(cin, line) && !line.empty()) {
2023-12-03 14:34:24 -08:00
int pi = INT_MAX, pl = -1, vi = 0, vl = 0;
for (int i = 0; i < line.size(); i++) {
unsigned char c = line[i] - '0';
if (c <= 9) {
if (vi == 0) {
pi = i;
vi = c;
}
pl = i;
vl = c;
}
}
for (int n = 1; n <= 9; n++) {
const auto strn = NUMBERS[n - 1];
int i = 0;
int posi = line.find(strn);
if (posi == string::npos)
continue;
int posl = line.rfind(strn);
if (posi < pi) {
pi = posi;
vi = n;
}
if (posl > pl) {
pl = posl;
vl = n;
}
}
ret += vi * 10 + vl;
}
cout << ret << '\n';
}