-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathb.test.ts
82 lines (67 loc) · 1.98 KB
/
b.test.ts
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
import { expect, test } from "bun:test";
function zip(arr: string[]): string[] {
return Array.from({ length: arr[0].length }, (_, i) => arr.map((a) => a[i]).join(""));
}
function zip2<T>(arr1: T[], arr2: T[]): [T, T][] {
const result: [T, T][] = [];
for (let i = 0; i < arr1.length; i++) {
result.push([arr1[i], arr2[i]]);
}
return result;
}
function findMirrorIndex(arr: string[]): number | undefined {
for (let i = 1; i < arr.length; i++) {
const a = arr.slice(0, i).reverse();
const b = arr.slice(i);
if (a.length < b.length) {
b.length = a.length;
} else {
a.length = b.length;
}
let s = 0;
for (const [x, y] of zip2(a, b)) {
const xx = x.split("");
const yy = y.split("");
for (const [aa, bb] of zip2(xx, yy)) {
s += aa === bb ? 0 : 1;
}
}
if (s === 1) {
return i;
}
}
}
function solution(input: string) {
const records = input.split("\n\n").map((block) => block.split("\n"));
let left = 0;
let top = 0;
for (const record of records) {
const row = findMirrorIndex(record);
if (row !== undefined) {
top += row;
continue;
}
const zipped = zip(record);
const col = findMirrorIndex(zipped);
if (col !== undefined) {
left += col;
continue;
}
throw new Error("Unexpected");
}
return left + 100 * top;
}
test("example", async () => {
const file = Bun.file(`${import.meta.dir}/example.txt`);
const input = await file.text();
const actual = solution(input);
const expected = 400;
expect(actual).toBe(expected);
});
test("puzzle input", async () => {
const file = Bun.file(`${import.meta.dir}/input.txt`);
const input = await file.text();
const actual = solution(input);
const expected = 37876;
expect(actual).toBe(expected);
});