Advent-of-Code/2022/5/main.cpp
2022-12-07 21:13:01 -05:00

120 lines
2.4 KiB
C++

#include <algorithm>
#include <fstream>
#include <iostream>
#include <stack>
#include <string>
#include <vector>
void DebugOutput(std::vector<std::vector<char>> &stacks)
{
// DEBUG:
for(const auto &st : stacks)
{
std::cout << "Stack: " << std::endl;
for(const auto &ch : st)
std::cout << "[" << ch << "]" << std::endl;
std::cout << std::endl;
}
}
std::vector<std::string> SplitStr(std::string str, const std::string &delim)
{
std::vector<std::string> rtn;
for(auto split = str.find(delim); split != std::string::npos; split = str.find(delim))
{
rtn.push_back(str.substr(0, split));
str = str.substr(split + delim.size()); // chop off beginning
}
if(str.size())
rtn.push_back(str);
return rtn;
}
int main()
{
std::ifstream ifs("data.txt");
if(!ifs.is_open())
{
std::cerr << "Missing data.txt." << std::endl;
return -1;
}
std::vector<std::vector<char>> stacks;
std::vector<std::vector<char>> stacks2;
// Step 1: Parse Starting Position
for(std::string line; std::getline(ifs, line); )
{
if(line == "")
break;
stacks.resize((line.size() + 1) / 4);
for(auto idx = 0; (idx * 4) < line.size(); ++idx)
if(line[1 + idx * 4] != ' ')
stacks[idx].push_back(line[1 + idx * 4]);
}
// Step 2: Clean up data:
for(auto &st : stacks)
{
// clear out last line of each, seeing as how they're just index numbers:
st.pop_back();
// reverse list since we parsed top to bottom and inserted backwards...
std::reverse(st.begin(), st.end());
}
// DebugOutput(stacks);
stacks2 = stacks;
// Step 3: Parse Actions
for(std::string line; std::getline(ifs, line); )
{
if(line == "")
continue;
auto actions = SplitStr(line, " ");
if(actions.size() != 6)
{
std::cerr << "Data corrupt: " << line << std::endl;
exit(-1);
}
long amt = std::atoi(actions[1].c_str());
long from = std::atoi(actions[3].c_str()) - 1;
long to = std::atoi(actions[5].c_str()) - 1;
// Part 1:
for(auto i = 0; i < amt; ++i)
{
stacks[to].push_back(stacks[from].back());
stacks[from].pop_back();
}
// Part 2:
std::stack<char> temp;
for(auto i = 0; i < amt; ++i)
{
temp.push(stacks2[from].back());
stacks2[from].pop_back();
}
for(auto i = 0; i < amt; ++i)
{
stacks2[to].push_back(temp.top());
temp.pop();
}
}
// DebugOutput(stacks);
for(const auto &st : stacks)
std::cout << st.back();
std::cout << std::endl;
for(const auto &st : stacks2)
std::cout << st.back();
std::cout << std::endl;
return 0;
}