-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.cpp
81 lines (76 loc) · 1.68 KB
/
5.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "common.h"
namespace {
struct Move {
long qty;
long src;
long dst;
};
auto parse(const auto &input) {
enum class mode { stack, move };
mode m{mode::stack};
std::vector<std::deque<char>> sts(10);
std::vector<Move> mvs{};
for (const auto &l : input) {
if (l.empty()) {
m = mode::move;
continue;
}
if (l[1] == '1') {
continue;
}
if (m == mode::stack) {
for (size_t i = 1; i < l.size(); i += 4) {
if (l[i] != ' ')
sts[static_cast<int>(i / 4)].push_front(l[i]);
}
} else if (m == mode::move) {
Move mv{};
sscanf(l.c_str(), "move %ld from %ld to %ld", &mv.qty, &mv.src, &mv.dst);
--mv.src;
--mv.dst;
mvs.emplace_back(std::move(mv));
}
}
return std::move(make_tuple(sts, mvs));
}
std::string p1(const auto &input) {
auto [sts, mvs] = parse(input);
for (auto mv : mvs) {
while (mv.qty--) {
sts[mv.dst].push_back(sts[mv.src].back());
sts[mv.src].pop_back();
}
}
std::ostringstream out;
for (const auto &st : sts) {
if (st.size())
out << st.back();
}
return out.str();
}
std::string p2(const auto &input) {
auto [sts, mvs] = parse(input);
for (auto mv : mvs) {
std::stack<char> t;
while (mv.qty--) {
t.push(sts[mv.src].back());
sts[mv.src].pop_back();
}
while (t.size()) {
sts[mv.dst].push_back(t.top());
t.pop();
}
}
std::ostringstream out;
for (const auto &st : sts) {
if (st.size())
out << st.back();
}
return out.str();
}
} // namespace
int main() {
const auto &input = gb::advent2021::readIn();
gb::advent2021::writeOut(p1(input));
gb::advent2021::writeOut(p2(input));
}