#include "aoc.h" namespace aoc2017 { static int64_t& get(char x, int64_t rs[26]) { return rs[x - 'a']; } static void get_number(const char** pp, int64_t* d) { const char* p = *pp; int sign = 1; if (*p == '-') { sign = -1; p++; } while (*p >= '0' && *p <= '9') { *d = *d * 10 + *p - '0'; p++; } *d *= sign; *pp = p; } static int64_t get_number(const char* p, int64_t rs[26]) { int64_t d{0}; if (*p == '-' || (*p >= '0' && (*p <= '9'))) { get_number(&p, &d); } else { d = get(*p, rs); } return d; } typedef void (*f23)(size_t* i, const char* p1, const char* p2, int64_t rs[26]); static void set(size_t* i, const char* p1, const char* p2, int64_t rs[26]) { get(*p1, rs) = get_number(p2, rs); *i += 1; } static void sub(size_t* i, const char* p1, const char* p2, int64_t rs[26]) { get(*p1, rs) -= get_number(p2, rs); *i += 1; } static void mul(size_t* i, const char* p1, const char* p2, int64_t rs[26]) { get(*p1, rs) *= get_number(p2, rs); *i += 1; } static void jnz(size_t* i, const char* p1, const char* p2, int64_t rs[26]) { auto d1 = get_number(p1, rs); auto d2 = get_number(p2, rs); *i += d1 != 0 ? d2 : 1; } static struct { f23 f; const char* s; int c; } fs[4] = {{set, "set", 0}, {sub, "sub", 0}, {mul, "mul", 0}, {jnz, "jnz", 0}}; static size_t exec(size_t index, const std::vector& todos, int64_t rs[26]) { if (index < todos.size()) { auto& todo = todos[index]; const char* p = todo.line; auto match = [](const char* p, const char* p0) -> bool { for (int i = 0; i < 3; i++) { if (*(p + i) != *(p0 + i)) { return false; } } return true; }; for (auto& fx : fs) { if (match(p, fx.s)) { fx.c += 1; fx.f(&index, p + 4, p + 6, rs); break; } } } return index; } static void part1(std::vector todos) { size_t index{0}; int64_t rs[26] = {0}; while (index < todos.size()) { index = exec(index, todos, rs); } } // static void part2(std::vector todos) { // size_t index{0}; // int64_t rs[26] = {0}; // // [9:jnz 1 -23] a[1] b[106717] c[123700] d[106700] e[106700] f[0] g[-17000] h[1] // rs[0] = 1; // a is 1 // rs[1] = 106717; // rs[2] = 123700; // rs[3] = 106700; // rs[4] = 106700; // rs[5] = 0; // rs[6] = -17000; // rs[7] = 1; // // auto print = [](int64_t is[26]) { // for (char c = 'a'; c <= 'h'; c++) { // printf("%c[%ld] ", c, is[c - 'a']); // } // printf("\n"); // }; // // while (index < todos.size()) { // std::cout << todos[index] << " "; // index = exec(index, todos, rs); // print(rs); // } // } std::pair day23(line_view file) { std::vector todos; per_line(file, [&todos](line_view lv) { todos.push_back({lv.line, lv.length - 1}); return true; }); part1(todos); int64_t t0 = fs[2].c; // part2(todos); return {t0, 0}; } } // namespace aoc2017