aboutsummaryrefslogtreecommitdiff
path: root/2016/src
diff options
context:
space:
mode:
Diffstat (limited to '2016/src')
-rw-r--r--2016/src/day10.cpp102
1 files changed, 102 insertions, 0 deletions
diff --git a/2016/src/day10.cpp b/2016/src/day10.cpp
new file mode 100644
index 0000000..7c1f4f9
--- /dev/null
+++ b/2016/src/day10.cpp
@@ -0,0 +1,102 @@
1#include <fstream>
2#include <iostream>
3#include <map>
4#include <sstream>
5#include <string>
6#include <tuple>
7
8using namespace std;
9
10using Sink = tuple<string, int>;
11
12vector<string>
13split(const string& line, char sep)
14{
15 vector<string> parts;
16 stringstream input{ line };
17
18 for ( string part; getline(input, part, sep); ) {
19 parts.emplace_back(part);
20 }
21
22 return parts;
23}
24
25map<int, tuple<Sink, Sink, vector<int>>>
26read_file(string_view filename)
27{
28 fstream input{ filename };
29
30 map<int, tuple<Sink, Sink, vector<int>>> bots;
31
32 for ( string line; getline(input, line); ) {
33 const auto parts = split(line, ' ');
34
35 if ( parts.at(0) == "bot" ) {
36 const Sink low_sink = { parts.at(5), stoi(parts.at(6)) };
37 const Sink hi_sink = { parts.at(10), stoi(parts.at(11)) };
38
39 auto& bot = bots[stoi(parts.at(1))];
40
41 get<0>(bot) = low_sink;
42 get<1>(bot) = hi_sink;
43 }
44 else if ( parts.at(0) == "value" ) {
45 auto& bot = bots[stoi(parts.at(5))];
46
47 get<2>(bot).push_back(stoi(parts.at(1)));
48 }
49 }
50
51 return bots;
52}
53
54void
55solve(map<int, tuple<Sink, Sink, vector<int>>> bots)
56{
57 map<int, int> outputs;
58
59 const auto store = [&](const Sink& sink, int value) {
60 if ( get<0>(sink) == "bot" ) {
61 auto& to_bot = bots[get<1>(sink)];
62 get<2>(to_bot).push_back(value);
63 }
64 else {
65 outputs[get<1>(sink)] = value;
66 }
67 };
68
69 while ( true ) {
70 auto it = ranges::find_if(bots, [](auto& bot) {
71 const auto& [id, values] = bot;
72 return (get<2>(values).size() == 2);
73 });
74 if ( it == bots.end() ) {
75 break;
76 }
77
78 auto& [id, values] = *it;
79 auto& [low_sink, hi_sink, chips] = values;
80
81 ranges::sort(chips);
82 store(low_sink, chips.at(0));
83 store(hi_sink, chips.at(1));
84
85 // part1
86 if ( chips.at(0) == 17 && chips.at(1) == 61 ) {
87 cout << id << endl;
88 }
89
90 chips.clear();
91 }
92
93 // part2
94 cout << outputs[0] * outputs[1] * outputs[2] << endl;
95}
96
97int
98main()
99{
100 auto bots = read_file("data/day10.txt");
101 solve(bots);
102}