-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpuzzle05.js
79 lines (67 loc) · 2.36 KB
/
puzzle05.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
const fs = require("fs");
const files = fs.readFileSync("./puzzle05-input.txt", "utf8"); //Read the input
const arr = files.replace(/\r/g, ""); //remove all carriage returns and split by single line return
const [stacks, moves] = arr.split("\n\n");
const splitedStacks = stacks.split("\n");
splitedStacks.pop(); //remove the numbers below the stacks
const splitedStacksWithE = splitedStacks.map((x) => {
return x
.replace(/\s{4}/g, "e")
.replace(/\s|\[|\]/g, "") //replace the empty space on each stack with the lowercase letter e.
.split(""); //split each row into an array
});
//re-construct the stacks array into an object:
const reconstructedStacks = {};
for (let j = splitedStacksWithE.length - 1; j >= 0; j--) {
for (let i = 0; i < splitedStacksWithE[0].length; i++) {
k = i + 1;
if (!reconstructedStacks[k]) {
reconstructedStacks[k] = []; // initialize as empty array if not exist yet
}
if (splitedStacksWithE[j][i] !== "e") {
reconstructedStacks[k].push(splitedStacksWithE[j][i]);
}
}
}
//use the JSON method to create a deep copy of the reconstructedStacks object as the partII input
const reconstructedStacks2 = JSON.parse(JSON.stringify(reconstructedStacks));
const reconstructedMoves = moves.split("\n").map((x) =>
x
.replace(/move |from|to/g, "")
.split(/\s+/)
.map(Number)
);
//The below function gets the final result based on the final reconstructedStacks
function getTopCrates(yourFinalStacks) {
let topCrates = "";
for (let i = 1; i <= Object.keys(yourFinalStacks).length; i++) {
topCrates += yourFinalStacks[i][yourFinalStacks[i].length - 1];
}
console.log(topCrates);
}
function partI() {
for (let move of reconstructedMoves) {
for (let i = 1; i <= move[0]; i++) {
reconstructedStacks[move[2]].push(
reconstructedStacks[move[1]][reconstructedStacks[move[1]].length - 1]
);
reconstructedStacks[move[1]].pop();
}
}
getTopCrates(reconstructedStacks);
}
function partII() {
for (let move of reconstructedMoves) {
temp = [];
for (let i = 1; i <= move[0]; i++) {
temp.unshift(
reconstructedStacks2[move[1]][reconstructedStacks2[move[1]].length - 1]
);
reconstructedStacks2[move[1]].pop();
}
reconstructedStacks2[move[2]] = reconstructedStacks2[move[2]].concat(temp);
}
getTopCrates(reconstructedStacks2);
}
partI();
partII();