-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
144 lines (129 loc) · 2.95 KB
/
index.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
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
import run from "aocrunner";
const parseInput = (rawInput: string) => rawInput;
const part1 = (rawInput: string) => {
const input = parseInput(rawInput);
let blocks: string[] = [];
let isFreeSpace = false;
let idCounter = 0;
for (const char of input) {
for (let i = 0; i < Number(char); i++) {
if (isFreeSpace) {
blocks.push(".");
} else {
blocks.push(String(idCounter));
}
}
if (!isFreeSpace) idCounter++;
isFreeSpace = !isFreeSpace;
}
// slow
// let numIndex = blocks.length - 1;
// for (let i = 0; i < blocks.length; i++) {
// if (blocks[i] === ".") {
// for (let j = numIndex; j > 0; j--) {
// if (i > j) break;
// if (blocks[j] !== ".") {
// const char = blocks[j];
// blocks[j] = blocks[i];
// blocks[i] = char;
// numIndex--;
// break;
// }
// }
// }
// }
for (let i = 0; i < blocks.length; i++) {
if (blocks[i] !== ".") continue;
const last = blocks.pop()!;
if (last === ".") {
i--;
continue;
}
blocks[i] = last;
}
let checksum: number = 0;
for (let i = 0; i < blocks.length; i++) {
checksum += Number(blocks[i]) * i;
}
return checksum;
};
const part2 = (rawInput: string) => {
const input = parseInput(rawInput);
let blocks: string[] = [];
let isFreeSpace = false;
let idCounter = 0;
for (const char of input) {
for (let i = 0; i < Number(char); i++) {
if (isFreeSpace) {
blocks.push(".");
} else {
blocks.push(String(idCounter));
}
}
if (!isFreeSpace) idCounter++;
isFreeSpace = !isFreeSpace;
}
// console.log(blocks.join(""));
const arrLen = blocks.length;
for (let i = arrLen - 1; i >= 0; i--) {
const c = blocks[i];
if (c !== ".") {
let l = 1;
while (c === blocks[i - l]) {
l++;
}
i -= l - 1;
// find slot
let slotLen = 0;
let slotStart = 0;
for (let j = 0; j < arrLen; j++) {
// break if i cursor passes j cursor
if (j > i) break;
if (blocks[j] === ".") {
if (slotLen === 0) slotStart = j;
slotLen++;
} else {
slotLen = 0;
}
// slot found
if (slotLen === l) {
// swap positions
for (let k = 0; k < l; k++) {
blocks[slotStart + k] = c;
blocks[i + k] = ".";
}
break;
}
}
}
}
let checksum: number = 0;
for (let i = 0; i < blocks.length; i++) {
if (blocks[i] !== ".") {
checksum += Number(blocks[i]) * i;
}
}
return checksum;
};
run({
part1: {
tests: [
{
input: `2333133121414131402`,
expected: 1928,
},
],
solution: part1,
},
part2: {
tests: [
{
input: `2333133121414131402`,
expected: 2858,
},
],
solution: part2,
},
trimTestInputs: true,
onlyTests: false,
});