-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.ts
119 lines (107 loc) · 3.06 KB
/
solver.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
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
import { toDictionary } from "../common.ts";
import { PuzzleSolver } from "../types/puzzle-solver.ts";
type File = {
id: number;
length: number;
freespace: number;
};
export default class Solver24D9 implements PuzzleSolver {
private disk: File[] = [];
parseInput(input: string[]) {
const digits = input[0].split("").map(Number);
let id = 0;
for (let i = 0; i < digits.length; i += 2) {
const length = digits[i];
const freespace = digits[i + 1] ?? 0;
this.disk.push({ id, length, freespace });
id++;
}
}
solvePart1() {
const compacted = compress(this.disk);
return calculateChecksum(compacted);
}
solvePart2() {
const defragmented = defrag(this.disk);
return calculateChecksum(defragmented);
}
}
function compress(disk: File[]): number[] {
const blocks = filesToBlocks(disk);
for (let i = 0; i < blocks.length; i++) {
if (blocks[i] !== -1) {
continue;
}
blocks[i] = getBlockFromEnd(i);
}
return blocks;
function getBlockFromEnd(minIndex: number) {
for (let i = blocks.length - 1; i > minIndex; i--) {
const block = blocks[i];
if (block === -1) {
continue;
}
blocks[i] = -1;
return block;
}
return -1;
}
}
function defrag(disk: File[]): number[] {
const filesById = toDictionary(disk, "id");
const blocks = filesToBlocks(disk);
let i = blocks.length - 1;
while (i >= 0) {
if (blocks[i] === -1) {
i--;
continue;
}
const file = filesById[blocks[i]];
const freespaceStart = findFreespace(i, file.length);
if (freespaceStart !== -1) {
for (let j = 0; j < file.length; j++) {
blocks[freespaceStart + j] = file.id;
blocks[i - j] = -1;
}
}
i -= file.length;
}
return blocks;
function findFreespace(maxIndex: number, length: number) {
for (let i = 0; i < maxIndex; i++) {
if (blocks[i] !== -1) {
continue;
}
for (let j = 0; j < length; j++) {
if (blocks[i + j] !== -1) {
i += j;
break;
}
if (j === length - 1) {
return i;
}
}
}
return -1;
}
}
function calculateChecksum(blocks: number[]) {
let result = 0;
for (let i = 0; i < blocks.length; i++) {
const id = blocks[i];
if (id === -1) {
continue;
}
result += i * id;
}
return result;
}
function createArray(length: number, value: number): number[] {
return Array.from<number>({ length }).fill(value);
}
function filesToBlocks(files: File[]): number[] {
return files.flatMap((file) => {
const { id, length, freespace } = file;
return [...createArray(length, id), ...createArray(freespace, -1)];
});
}