Advent of Code 2022 - 2nd attempt in c++
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

96 lines
2.2 KiB

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Instr {
unsigned count;
unsigned orig;
unsigned dest;
};
struct Input {
vector<vector<char>> stacks;
vector<Instr> instrs;
};
vector<vector<char>> parse_stacks()
{
vector<vector<char>> data;
for (string line; getline(cin, line);) {
if (line.empty()) break;
unsigned count = (line.size() + 1) / 4;
while (data.size() < count) data.resize(count);
for (unsigned i = 0; i < count; i++) {
auto pos = line.begin() + i * 4;
if (pos[0] == '[' && pos[2] == ']') data[i].push_back(pos[1]);
}
}
for (auto &x : data) reverse(x.begin(), x.end());
return data;
}
vector<Instr> parse_instrs()
{
vector<Instr> data;
for (string line; getline(cin, line);) {
Instr cur;
sscanf(line.c_str(), "move %u from %u to %u",
&cur.count, &cur.orig, &cur.dest);
data.push_back(cur);
}
return data;
}
Input parse()
{
Input data;
data.stacks = parse_stacks();
data.instrs = parse_instrs();
return data;
}
string p1(const Input &input)
{
auto stacks = input.stacks;
for (auto &instr : input.instrs) {
auto &o = stacks.at(instr.orig - 1);
auto &d = stacks.at(instr.dest - 1);
if (o.size() < instr.count) throw "instr error";
for (unsigned i = 0; i < instr.count; i++) {
d.push_back(o.back());
o.pop_back();
}
}
string out;
for (auto &s : stacks) out.push_back(s.back());
return out;
}
string p2(const Input &input)
{
auto stacks = input.stacks;
for (auto &instr : input.instrs) {
auto &o = stacks.at(instr.orig - 1);
auto &d = stacks.at(instr.dest - 1);
if (o.size() < instr.count) throw "instr error";
// std::copy maybe?
for (unsigned i = 0; i < instr.count; i++) {
d.push_back(*(o.end() - instr.count + i));
}
o.resize(o.size() - instr.count);
}
string out;
for (auto &s : stacks) out.push_back(s.back());
return out;
}
int main()
{
auto input = parse();
cout << p1(input) << endl;
cout << p2(input) << endl;
}