#include "common.h" #include #include namespace aoc2022 { struct hook { int64_t value = 0; hook* prev = nullptr; hook* next = nullptr; }; struct message { static const int LEN = 5000; // static const int LEN = 7; hook msg[LEN]; hook* head = nullptr; hook* zero = nullptr; 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; } void print() const noexcept { hook* n = head->next; while (n != head) { printf("%ld ", n->value); n = n->next; } printf("\n"); } hook* get(int index) { index %= LEN; return &msg[index]; } void put(hook* n, hook* x) { x->prev->next = x->next; x->next->prev = x->prev; x->next = n->next; n->next->prev = x; x->prev = n; n->next = x; } hook* next(hook* x, int64_t i) { hook* n = x; bool foward = i > 0; i = std::abs(i) % (LEN - 1); if (foward) { while (i > 0) { n = n->next; if (n != head && n != x) { i--; } } } else { // i < 0 while (i >= 0) { n = n->prev; if (n != head && n != x) { i--; } } } return n; } hook* nth(int n) { hook* x = zero; while(n > 0) { x = x->next; if (x != head) { n--; } } return x; } void relocate() { for (int i = 0; i < LEN; i++) { hook* h = &msg[i]; if (h->value != 0) { hook* n = next(h, h->value); // printf("%ld put to %ld and %ld\n", h->value, n->value, n->next->value); put(n, h); // print(); } } } void multiply(size_t n) { for (int i = 0; i < LEN; i++) { msg[i].value *= n; } } message(line_view lv) { const char* p = lv.line; head = new hook; head->value = INT32_MAX; hook* hs[LEN]; for (int i = 0; i < LEN; i++) { hs[i] = &msg[i]; if (i == 0) { head->next = hs[i]; hs[i]->prev = head; hs[i]->next = &msg[i + 1]; } else if (i == LEN - 1) { hs[i]->prev = &msg[i - 1]; hs[i]->next = head; head->prev = hs[i]; } else { hs[i]->prev = &msg[i - 1]; hs[i]->next = &msg[i + 1]; } } int n{0}; while (p < lv.line + lv.length) { if (*p != ' ') { get_number(&p, &hs[n]->value); if (hs[n]->value == 0) { zero = hs[n]; } n++; } p++; } } }; std::pair day20(line_view); } // namespace aoc2022