-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart1.js
59 lines (47 loc) · 1.33 KB
/
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const { getInputString } = require('../utils/getInputString.js');
const file = getInputString(5, false);
const lines = file.split("\n");
const getStartingState = (lines) => {
const rows = [];
for (let line of lines) {
if (!line.includes("[")) {
break;
}
rows.push(line.replace(/\s\s\s\s/g, "[-]").replace(/(\s|\[|\])/g, ""));
}
const numRows = rows[0].length; // row length should be uniform
const state = [];
for (let i = 0; i < numRows; i++) {
let column = [];
for (const row of rows) {
column.push(row[i]);
}
state.push([...column.filter((char) => char !== "-")]);
}
return state;
};
const executeInstructions = (lines, state) => {
for (const line of lines) {
if (line.startsWith("move")) {
state = executeInstruction(line, state);
}
}
return state;
};
const executeInstruction = (instruction, state) => {
// extract the numbers from the instructions
const [a, count, b, from, c, to] = instruction.split(' ');
for (let i = 0; i < count; i++) {
const char = state[from - 1].shift();
state[to - 1].unshift(char);
}
return state;
};
const getMessage = (state) =>
state.reduce((acc, col) => {
acc += col[0];
return acc;
}, "");
let state = getStartingState(lines);
state = executeInstructions(lines, state);
console.log(getMessage(state));