From ae27321e81cd4eee3c7340c99b8bf29bc9bb5891 Mon Sep 17 00:00:00 2001 From: eriedaberrie Date: Sun, 3 Dec 2023 14:34:24 -0800 Subject: [PATCH] 2023 day 1: add C++ solution --- 2023/1/main.cpp | 60 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 2023/1/main.cpp diff --git a/2023/1/main.cpp b/2023/1/main.cpp new file mode 100644 index 0000000..c2a8254 --- /dev/null +++ b/2023/1/main.cpp @@ -0,0 +1,60 @@ +#include +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; + for (;;) { + getline(cin, line); + if (cin.eof()) + 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'; +}