Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <vector>
- #include <string>
- #include <string_view>
- #include <set>
- size_t getNumStart(std::string_view str, size_t idx)
- {
- char ch = str[idx];
- while(std::isdigit(ch))
- {
- idx--;
- ch = str[idx];
- }
- return idx+1;
- }
- int extractNum(std::string_view str, size_t idx)
- {
- std::string num = "";
- char ch = str[idx];
- while(std::isdigit(ch))
- {
- num+=ch;
- idx++;
- ch = str[idx];
- }
- return std::stoi(num);
- }
- std::set<size_t> countedNumbers;
- int countPosition(std::string_view str, size_t idx)
- {
- if(std::isdigit(str[idx]))
- {
- size_t sIdx = getNumStart(str, idx);
- if(countedNumbers.find(sIdx)==countedNumbers.end())
- {
- countedNumbers.insert(sIdx);
- return extractNum(str, sIdx);
- }
- }
- return 0;
- }
- int processPositionP1(std::string_view str, size_t idx, const std::vector<int> &offsets)
- {
- int sum = 0;
- char ch = str[idx];
- if(ch != '.' && !std::isdigit(ch))
- {
- for(int offset: offsets)
- {
- sum += countPosition(str, idx+offset);
- }
- }
- return sum;
- }
- int processPositionP2(std::string_view str, size_t idx, const std::vector<int> &offsets)
- {
- int sum = 0;
- char ch = str[idx];
- if(ch == '*')
- {
- int counted = 0;
- for(int offset: offsets)
- {
- int pos = countPosition(str, idx+offset);
- if(pos!=0)
- {
- sum = (sum==0) ? pos : pos*sum;
- counted++;
- }
- if(counted>=2)break;
- }
- if(counted==2)
- {
- return sum;
- }
- }
- return 0;
- }
- int main()
- {
- auto file = std::fstream("./input", std::ios_base::in);
- std::string text;
- int lineLen = 0;
- long int sump1 = 0;
- long int sump2 = 0;
- while(file)
- {
- std::string s;
- std::getline(file,s);
- lineLen = (lineLen) ? lineLen : s.size()+1;
- text+=s+'.';
- }
- file.close();
- std::vector<int> offsets = {1,-1,lineLen,-lineLen,lineLen+1, lineLen-1, -lineLen+1, -lineLen-1};
- for(size_t i = 0; i < text.size(); i++)
- {
- sump1 += processPositionP1(text, i, offsets);
- }
- countedNumbers.clear();
- for(size_t i = 0; i < text.size(); i++)
- {
- sump2 += processPositionP2(text, i, offsets);
- }
- std::cerr << "p1: " << sump1 << " p2: " << sump2 << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement