blob: 60ee62d5b986bd6d868b76dfcfd4b1dfaa1de0b4 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
|
#include "common.h"
#include <vector>
#include <stdint.h>
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<int, int64_t> day20(line_view);
} // namespace aoc2022
|