adventofcode2022/05/code.js

85 lines
2.0 KiB
JavaScript

const fs = require('fs');
const inputArray = fs.readFileSync('input.txt').toString().split("\n");
// Part One
/*
[Q] [P] [P]
[G] [V] [S] [Z] [F]
[W] [V] [F] [Z] [W] [Q]
[V] [T] [N] [J] [W] [B] [W]
[Z] [L] [V] [B] [C] [R] [N] [M]
[C] [W] [R] [H] [H] [P] [T] [M] [B]
[Q] [Q] [M] [Z] [Z] [N] [G] [G] [J]
[B] [R] [B] [C] [D] [H] [D] [C] [N]
1 2 3 4 5 6 7 8 9
*/
let stacks = [
["C", "Q", "B"],
["Z", "W", "Q", "R"],
["V", "L", "R", "M", "B"],
["W", "T", "V", "H", "Z", "C"],
["G", "V", "N", "B", "H", "Z", "D"],
["Q", "V", "F", "J", "C", "P", "N", "H"],
["S", "Z", "W", "R", "T", "G", "D"],
["P", "Z", "W", "B", "N", "M", "G", "C"],
["P", "F", "Q", "W", "M", "B", "J", "N"],
]
for (i in inputArray) {
const contents = inputArray[i].split(" ");
if (contents[0] === 'move') {
const count = parseInt(contents[1]);
const source = parseInt(contents[3]) - 1;
const destination = parseInt(contents[5]) - 1;
for (let i = 0; i < count; i++) {
stacks[destination].unshift(stacks[source].shift());
}
}
}
let tops = "";
for (i in stacks) {
tops += stacks[i][0];
}
console.log(tops);
// Part Two
stacks = [
["C", "Q", "B"],
["Z", "W", "Q", "R"],
["V", "L", "R", "M", "B"],
["W", "T", "V", "H", "Z", "C"],
["G", "V", "N", "B", "H", "Z", "D"],
["Q", "V", "F", "J", "C", "P", "N", "H"],
["S", "Z", "W", "R", "T", "G", "D"],
["P", "Z", "W", "B", "N", "M", "G", "C"],
["P", "F", "Q", "W", "M", "B", "J", "N"],
]
for (i in inputArray) {
const contents = inputArray[i].split(" ");
if (contents[0] === 'move') {
const count = parseInt(contents[1]);
const source = parseInt(contents[3]) - 1;
const destination = parseInt(contents[5]) - 1;
const moved = [];
for (let i = 0; i < count; i++) {
moved.push(stacks[source].shift());
}
stacks[destination].unshift(...moved);
}
}
tops = "";
for (i in stacks) {
tops += stacks[i][0];
}
console.log(tops);
// functions