Advertisement
Guest User

AoC day 16 part 2

a guest
Dec 16th, 2017
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream>
  3. #include <vector>
  4. #include <numeric>
  5. #include <algorithm>
  6. #include <functional>
  7.  
  8. using namespace std::placeholders;
  9.  
  10. void shift(std::vector<char>& dance, int val) {
  11.   for (int i = 0; i < val; i++) {
  12.     char c = dance.back(); dance.pop_back();
  13.     dance.insert(dance.begin(), c);
  14.   }
  15. }
  16.  
  17. void exchange(std::vector<char>& dance, int a, int b) {
  18.   int tmp = dance[a];
  19.   dance[a] = dance[b];
  20.   dance[b] = tmp;
  21. }
  22.  
  23. void partner(std::vector<char>& dance, char c1, char c2) {
  24.   auto p1 = std::find(std::begin(dance), std::end(dance), c1);
  25.   auto p2 = std::find(std::begin(dance), std::end(dance), c2);
  26.   std::iter_swap(p1, p2);
  27. }
  28.  
  29. void print(std::vector<char>& dance) {
  30.   for (auto& c: dance)
  31.     std::cout << c;
  32.   std::cout << std::endl;
  33. }
  34.  
  35. int main() {
  36.   std::string input, token;
  37.   std::getline(std::cin, input);
  38.   std::stringstream ss(input);
  39.  
  40.   std::vector<char> dance(16);
  41.   std::iota(dance.begin(), dance.end(), 'a');
  42.  
  43.   std::vector<std::function<void(std::vector<char>&)>> call;
  44.  
  45.   while (std::getline(ss, token, ',')) {
  46.     if (token.empty()) continue;
  47.     switch (token[0]) {
  48.       case 's': {
  49.         int s = std::stoi(token.substr(1))%16;
  50.         auto x = std::bind(shift, _1, s);
  51.         call.push_back(x);
  52.       } break;
  53.       case 'x': {
  54.         auto pos = token.find('/');
  55.         int a = std::stoi(token.substr(1, token.size()-pos));
  56.         int b = std::stoi(token.substr(pos+1));
  57.         auto x = std::bind(exchange, _1, a, b);
  58.         call.push_back(x);
  59.       } break;
  60.       case 'p': {
  61.         auto x = std::bind(partner, _1, token[1], token[3]);
  62.         call.push_back(x);
  63.       } break;
  64.       default: break;
  65.     }
  66.   }
  67.  
  68.   // find cycle
  69.   auto copy = dance;
  70.   unsigned long long cycle = 0;
  71.   do {
  72.     for (auto& c: call)
  73.       c(copy);
  74.     cycle++;
  75.   } while (copy != dance);
  76.  
  77.   std::cout << "Cycle: " << cycle << std::endl;
  78.  
  79.   for (unsigned long long i = 0; i < 1000000000 % cycle; i++) {
  80.     for (auto& c: call)
  81.       c(dance);
  82.   }
  83.  
  84.   print(dance);
  85.  
  86.   return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement