-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday05_part2.js
More file actions
67 lines (55 loc) · 1.55 KB
/
day05_part2.js
File metadata and controls
67 lines (55 loc) · 1.55 KB
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
var fs = require('fs');
var path = require('path');
var filePath = './inputDay05.txt';
let buffer = fs.readFileSync(path.join(__dirname, filePath));
let lines = buffer.toString().split('\n');
let numStacks = 9;
let stackHeight = 8;
let stacks = new Array(numStacks);
for (let i = 0; i < stacks.length; ++i) {
stacks[i] = new Array();
}
//read stack state
let currentLine = 0;
for (let i = 0; i < stackHeight; ++i) {
for (let stackIdx = 0; stackIdx < numStacks; ++stackIdx) {
let crate = lines[i][1 + stackIdx * 4];
if (crate != ' ')
putCrateToFront(stacks[stackIdx], crate);
}
};
//read and process instructions
for (let currentLine = stackHeight + 2; currentLine < lines.length; ++currentLine) {
let line = lines[currentLine];
if (line.length == 0)
break;
//move 1 from 5 to 2
const regexp = /move (\d+) from (\d+) to (\d+)/g;
const match = regexp.exec(line);
let takenCrates = [];
for (let i = 0; i < match[1]; ++i) {
let crate = takeCrate(stacks[match[2] - 1]);
takenCrates.unshift(crate);
}
takenCrates.forEach((crate) => {
putCrate(stacks[match[3] - 1], crate);
});
};
//final result
let topCrates = '';
for (let i = 0; i < stacks.length; ++i) {
topCrates += (takeCrate(stacks[i]));
}
console.log(topCrates);
//helper
function takeCrate(stack) {
if (stack.length <= 0)
return '';
return stack.pop();
}
function putCrate(stack, create) {
stack.push(create);
}
function putCrateToFront(stack, create) {
stack.unshift(create);
}