-
Notifications
You must be signed in to change notification settings - Fork 0
/
part1.js
43 lines (39 loc) · 908 Bytes
/
part1.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
const { readFileSync } = require("fs");
// Parse Input
const inputFile = "input.txt";
const diskMap = readFileSync(inputFile)
.toString()
.trim()
.split("")
.map((x) => parseInt(x));
// Generate Blocks View
let blocksView = [];
let blocksCount = 0;
diskMap.forEach((value, i) => {
if (i % 2 == 0) {
blocksView.push(...new Array(value).fill(i / 2));
blocksCount += value;
} else {
blocksView.push(...new Array(value).fill("."));
}
});
// Reorganize blocks
[...blocksView].reverse().forEach((b, i) => {
let firstFreeSpace = blocksView.indexOf(".");
if (
firstFreeSpace > 0 &&
b != "." &&
blocksView.length - 1 - i > firstFreeSpace
) {
blocksView[firstFreeSpace] = b;
blocksView[blocksView.length - 1 - i] = ".";
}
});
// Compute Result
let result = 0;
blocksView.forEach((v, i) => {
if (v !== ".") {
result += v * i;
}
});
console.log(result);