Advent-of-Code/2022/8/main.cpp
2022-12-13 08:55:20 -05:00

140 lines
3.0 KiB
C++

#include <fstream>
#include <iostream>
#include <set>
#include <string>
#include <vector>
std::vector<int> ParseRow(auto begin, auto end)
{
std::vector<int> rtn_indexes;
std::vector<int> 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<int> ParseCol(auto begin, auto end, int col)
{
std::vector<int> rtn_indexes;
std::vector<int> 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<std::vector<int>> 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<std::pair<int, int>> 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<int> 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;
}