#include "common.h" #include #include #include namespace aoc2022 { struct addx { int x; size_t operator()(size_t n) { return n + x; } }; struct mulx { int x; size_t operator()(size_t n) { return n * (x > 0 ? x : n); } }; typedef size_t(*func)(size_t); struct monkey { std::deque items; std::function op; int count = 0; int mod = 0; int to_t = 0; int to_f = 0; int get_number(const char* p) { int d{0}; while(*p >= '0' && *p <= '9') { d = d * 10 + *p - '0'; p++; } return d; } bool get_number(const char** pp, int* d) { const char *p = *pp; while(*p >= '0' && *p <= '9') { *d = 10 * (*d) + *p - '0'; p++; } *pp = p; return *d > 0; } void print() const noexcept { for (auto& i: items) { printf("%zu ", i); } printf("\nmod[%d] to_t[%d] to_f[%d]\n\n", mod, to_t, to_f); } monkey(line_view lv) { const char* p = lv.line; while (p < lv.line + lv.length) { if(*p == 's' && *(p+1) == ':') { int d{0}; const char *pp = p + 3; while(get_number(&pp, &d)) { items.push_back(d); d = 0; pp += 2; } } if(*p == ' ' && *(p+1) == '*') { int d = get_number(p + 3); op = [d](size_t x){ return x * (d > 0 ? d : x);}; // op = mulx{d}; } if(*p == ' ' && *(p+1) == '+') { int d = get_number(p + 3); op = [d](size_t x){ return x + d;}; // op = addx{d}; } if(*p == 'b' && *(p+1) == 'y') { mod = get_number(p + 3); } if(*p == 'u' && *(p+1) == 'e') { to_t = get_number(p + 20); } if(*p == 's' && *(p+1) == 'e') { to_f = get_number(p + 20); } p++; } } void transfer(monkey* ms, func f) { while (!items.empty()) { size_t x = items.front(); items.pop_front(); count += 1; size_t n = op(x); n = f(n); if ( n % mod == 0) { ms[to_t].items.push_back(n); } else { ms[to_f].items.push_back(n); } } } }; std::pair day11(line_view); }