-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
323 lines (273 loc) · 6.72 KB
/
utils.js
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import fs from "fs";
import path from "path";
/**
* @deprecated use `runDay` instead
*/
export function runSolution(label, fn, answer = null) {
let start = Date.now();
let res = null;
try {
res = fn();
} catch (err) {
console.error(err);
res = "ERROR";
}
let time = (Date.now() - start) / 1000;
if (answer === null) {
console.log("❓ ", label, res, `[sec ${time}]`);
return;
}
if (res === answer) {
console.log("✅", label, res, `[sec ${time}]`);
} else {
console.log(`❌`, label, `[sec ${time}]`);
console.log(` expected:`, answer);
console.log(` actual: `, res);
}
}
export function runDay(year, day, iters = 1) {
let DD = String(day).padStart(2, "0");
let inputFolder = new URL(`./inputs/${year}/`, import.meta.url).pathname;
if (!fs.existsSync(path.join(inputFolder, `day${DD}.txt`))) {
throw new Error(
`Input file for ${year}/${day} not found. Too soon for ${day} december ${year}?`,
);
}
let ansFolder = new URL(`./${year}/answers/`, import.meta.url).pathname;
let part1 = fileToStringOrEmpty(path.join(ansFolder, `day${DD}-part1.txt`));
let part2 = fileToStringOrEmpty(path.join(ansFolder, `day${DD}-part2.txt`));
let inputData = fs
.readFileSync(path.join(inputFolder, `day${DD}.txt`))
.toString()
.trim();
console.log(`🎄${year}/${DD} https://adventofcode.com/${year}/day/${day}`);
if (iters > 1) {
console.log(` best total`);
}
let answers = [];
let runner = {
part(part, fn, label = "") {
let answer = part === 1 ? part1 : part2;
let res;
let minTime = Infinity;
let totalTime = Date.now();
try {
for (let i = 0; i < iters; i++) {
let start = Date.now();
res = String(fn(inputData));
minTime = Math.min(minTime, Date.now() - start);
}
totalTime = Date.now() - totalTime;
} catch (err) {
console.error(err);
res = "ERROR";
}
let time = formatTime(minTime);
totalTime = iters > 1 ? ` [${formatTime(totalTime)}]` : "";
if (!answer) {
console.log(` ❓ part${part} ${res} [${time}] ${label}`);
answers[part] = res;
} else {
if (res === answer) {
console.log(` ✅ part${part} [${time}]${totalTime} ${label}`);
} else {
console.log(` ❌ part${part} [${time}]${totalTime} ${label}`);
console.log(` expected:`, answer);
console.log(` actual: `, res);
}
}
return runner;
},
end(saveCorrectAns) {
if (!saveCorrectAns) return;
if (!part1 && answers[1]) {
fs.writeFileSync(
path.join(ansFolder, `day${DD}-part1.txt`),
answers[1],
);
}
if (!part2 && answers[2]) {
fs.writeFileSync(
path.join(ansFolder, `day${DD}-part2.txt`),
part2 || answers[2],
);
}
},
};
return runner;
}
function fileToStringOrEmpty(p) {
try {
return fs.readFileSync(p).toString().trim();
} catch (e) {
return "";
}
}
export function formatTime(timeMsec) {
let sec = Math.floor(timeMsec / 1000);
let min = Math.floor(sec / 60);
sec = String(sec % 60).padStart(2, "0");
let msec = String(timeMsec % 1000).padStart(3, "0");
return `${min}:${sec}.${msec}`;
}
export function isNumericChar(char) {
return char && char.charCodeAt(0) >= 48 && char.charCodeAt(0) <= 57;
}
export function uniq(arr) {
return [...new Set(arr)];
}
export function sortNum(arr) {
return arr.slice().sort((a, b) => a - b);
}
export function ints(str) {
return str.match(/[-+]?\d+/g).map(Number);
}
export function sum(arr) {
return arr.reduce((a, b) => a + b, 0);
}
export function prod(arr) {
return arr.reduce((a, b) => a * b, 1);
}
export function allNeibs8(i, j) {
return [
[i, j + 1],
[i, j - 1],
[i + 1, j],
[i - 1, j],
[i + 1, j + 1],
[i + 1, j - 1],
[i - 1, j + 1],
[i - 1, j - 1],
];
}
export function lcm(list) {
let res = list[0];
for (let i = 1; i < list.length; i++) {
res = lcm(res, list[i]);
}
return res;
function lcm(a, b) {
return (a * b) / gcd(a, b);
}
function gcd(a, b) {
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return a;
}
}
export function gcd(list) {
let res = list[0];
for (let i = 1; i < list.length; i++) {
res = _gcd(res, list[i]);
}
return res;
function _gcd(a, b) {
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return a;
}
}
export function printGrid(grid) {
let res = grid.map((row) => row.join("")).join("\n");
return res;
}
export function makeGrid(inp) {
return inp.split("\n").map((line) => line.split(""));
}
export function findInGrid(grid, char) {
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if (grid[i][j] === char) {
return [i, j];
}
}
}
return null;
}
export function makeGridWithBorder(inp, border) {
let lines = inp.split("\n");
let res = [];
res.push(border.repeat(lines[0].length + 2).split(""));
for (let line of lines) {
res.push((border + line + border).split(""));
}
res.push(border.repeat(lines[0].length + 2).split(""));
return res;
}
export function printGridCb(grid, cb) {
let res = grid
.map((row, i) => {
return row
.map((cell, j) => {
return cb(cell, i, j);
})
.join("");
})
.join("\n");
return res;
}
export function waitHard(msec) {
let start = Date.now();
while (Date.now() - start < msec) {
//
}
}
export function rotateGrid90(grid) {
// rotate T[][] or string[] clockwise. Returns T[][] or string[][]
let newGrid = [];
for (let i = 0; i < grid[0].length; i++) {
let col = grid.map((row) => row[i]).reverse();
newGrid.push(col);
}
return newGrid;
}
export function forEachInGrid(grid, cb) {
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[0].length; j++) {
cb(grid[i][j], i, j);
}
}
}
export function PriorityQueue() {
// push(n, data) - add to the queue
// pop() - returns "data" with the lowest "n"
let arr = [];
let map = {};
let size = 0;
return {
push(n, data) {
if (map[n] === undefined) {
map[n] = [];
}
map[n].push(data);
size++;
},
pop() {
let min;
for (const key in map) {
min = key;
break;
}
let res = map[min].pop();
if (map[min].length === 0) {
delete map[min];
}
size--;
return res;
},
size() {
return size;
},
isEmpty() {
return size === 0;
},
};
}
export const BLACK = "█";
export const GREY = "░";