advent-of-code/2023/1/main.cpp
2023-12-03 16:15:40 -08:00

61 lines
890 B
C++

#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;
while (!cin.eof()) {
string line;
getline(cin, line);
if (line.empty())
break;
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';
}