#include #include #include #include #include std::vector ParseRow(auto begin, auto end) { std::vector rtn_indexes; std::vector values; // initialize list with the first value values.push_back(*begin); // iterate through the rest: for(auto i = begin + 1; i != end; ++i) { // if it's higher than the most recent one: const auto val = *i; if(val > values.back()) { values.push_back(val); rtn_indexes.push_back(std::distance(begin, i)); } } return rtn_indexes; } std::vector ParseCol(auto begin, auto end, int col) { std::vector rtn_indexes; std::vector values; // initialize list with the first value values.push_back((*begin)[col]); // iterate through the rest: for(auto i = begin + 1; i != end; ++i) { // if it's higher than the most recent one: const auto val = (*i)[col]; if(val > values.back()) { values.push_back(val); rtn_indexes.push_back(std::distance(begin, i)); } } return rtn_indexes; } int main() { std::ifstream ifs("data.txt"); if(!ifs.is_open()) { std::cerr << "Missing data.txt." << std::endl; return -1; } unsigned long total = 0; unsigned long total_pt2 = 0; std::vector> trees; // Parse: for(std::string line; std::getline(ifs, line); ) { if(line == "") continue; trees.push_back({}); for(const char &ch : line) trees.back().push_back(ch - '0'); } std::set> visible_coordinates; for(auto y = 0; y < trees.size(); ++y) { visible_coordinates.insert({0,y}); visible_coordinates.insert({trees[y].size()-1,y}); } for(auto x = 1; x < trees[0].size() - 1; ++x) { visible_coordinates.insert({x,0}); visible_coordinates.insert({x,trees.size()-1}); } // left to right, right to left IN EACH ROW: std::vector points; for(auto y = 1; y < trees.size() - 1; ++y) { // left to right: points = ParseRow(trees[y].begin(), trees[y].end()); for(const auto &point : points) visible_coordinates.insert({point,y}); // right to left: points = ParseRow(trees[y].rbegin(), trees[y].rend()); for(const auto &point : points) visible_coordinates.insert({trees[y].size() - point - 1,y}); } for(auto x = 1; x < trees.size() - 1; ++x) { // left to right: points = ParseCol(trees.begin(), trees.end(), x); for(const auto &point : points) visible_coordinates.insert({x,point}); // right to left: points = ParseCol(trees.rbegin(), trees.rend(), x); for(const auto &point : points) visible_coordinates.insert({x, trees.size() - point - 1}); } total += visible_coordinates.size(); for(auto y = 0; y < trees.size(); ++y) { for(auto x = 0; x < trees[y].size(); ++x) { if(visible_coordinates.contains({x,y})) std::cout << "\033[1;31m"; else std::cout << "\033[0m"; std::cout << trees[y][x]; } std::cout << std::endl; } std::cout << "\033[0m"; std::cout << " Total: " << total << std::endl; std::cout << "PT2 Total: " << total_pt2 << std::endl; return 0; }