Created
March 2, 2017 05:17
-
-
Save mavam/9754001af666a6e35921f740749a22a3 to your computer and use it in GitHub Desktop.
Advent of Code - Day 10 - Part Two
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cassert> | |
#include <iostream> | |
#include <vector> | |
#include <caf/all.hpp> | |
using namespace std; | |
using namespace caf; | |
// The same bot from part one. | |
behavior bot(event_based_actor* self, int id) { | |
self->set_default_handler(skip); | |
return { | |
[=](int first) { | |
self->become( | |
[=](int second) { | |
self->become( | |
[=](const actor& low, const actor& high) { | |
self->send(low, std::min(first, second)); | |
self->send(high, std::max(first, second)); | |
self->quit(); | |
} | |
); | |
} | |
); | |
} | |
}; | |
} | |
// The basic output actor. | |
behavior output(event_based_actor* self, int id) { | |
return { | |
[=](int) { | |
self->quit(); | |
} | |
}; | |
} | |
int main() { | |
// CAF's state. | |
actor_system_config cfg; | |
actor_system sys{cfg}; | |
// Initialize bots and outputs. | |
auto n = 512; | |
auto bots = vector<actor>{}; | |
auto outputs = vector<actor>{}; | |
bots.reserve(n); | |
outputs.reserve(n); | |
// Multiplies the output of bins 0, 1, and 2. | |
auto multiplier = sys.spawn( | |
[](event_based_actor* self) -> behavior { | |
return { | |
[=](int x) { | |
self->become( | |
[=](int y) { | |
self->become( | |
[=](int z) { | |
cout << x * y * z << endl; | |
self->quit(); | |
} | |
); | |
} | |
); | |
} | |
}; | |
} | |
); | |
for (auto id = 0; id < 3; ++id) { | |
bots.push_back(sys.spawn(bot, id)); | |
outputs.push_back(multiplier); | |
} | |
for (auto id = 3; id < n; ++id) { | |
bots.push_back(sys.spawn(bot, id)); | |
outputs.push_back(sys.spawn(output, id)); | |
} | |
// Read tokens from standard input and parse instructions. | |
string t; | |
while (cin) { | |
cin >> t; | |
if (t == "bot") { | |
// Example: bot 2 gives low to bot 1 and high to bot 0 | |
int source, sink; | |
string type; | |
cin >> source; | |
auto& sender = bots[source]; | |
cin >> t >> t >> t >> type >> sink; | |
auto& low = type == "bot" ? bots[sink] : outputs[sink]; | |
cin >> t >> t >> t >> type >> sink; | |
auto& high = type == "bot" ? bots[sink] : outputs[sink]; | |
anon_send(bots[source], low, high); // deliver instructions. | |
} else if (t == "value") { | |
// Example: value 5 goes to bot 2 | |
int value, sink; | |
cin >> value >> t >> t >> t >> sink; | |
anon_send(bots[sink], value); | |
} else if (cin) { | |
cerr << "unexpected token: " << t << endl; | |
return 1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment