71 lines
2 KiB
TypeScript
71 lines
2 KiB
TypeScript
type stack = string[];
|
|
type cargo = stack[];
|
|
type instruction = {
|
|
amount: number;
|
|
from: number;
|
|
to: number;
|
|
};
|
|
|
|
function getInitialData(): [cargo, instruction[]] {
|
|
const input = Deno.readTextFileSync('./input.txt').trimEnd();
|
|
const [stackInput, instructionInput] = input
|
|
.split('\n\n')
|
|
.map((data) => data.split('\n'));
|
|
|
|
// Parse Crate Data
|
|
const columns = stackInput.pop()!.trim().split(/\s+/);
|
|
const cargoMap = columns.map((col) => -3 + parseInt(col) * 4);
|
|
|
|
const cargo: cargo = cargoMap.map((_) => [] as stack);
|
|
for (const layer of stackInput) {
|
|
cargoMap.forEach((pos: number, index: number) => {
|
|
const crate = layer.at(pos);
|
|
if (crate && crate !== ' ') cargo[index].push(crate);
|
|
});
|
|
}
|
|
cargo.forEach((stack) => {
|
|
stack.reverse();
|
|
});
|
|
|
|
// Parse Instruction Data
|
|
const instructions: instruction[] = [];
|
|
for (const line of instructionInput) {
|
|
const instruction = line.match(
|
|
/^move (\d+) from (\d+) to (\d+)$/,
|
|
)! as string[];
|
|
instructions.push({
|
|
amount: parseInt(instruction[1]),
|
|
from: parseInt(instruction[2]) - 1,
|
|
to: parseInt(instruction[3]) - 1,
|
|
});
|
|
}
|
|
return [cargo, instructions];
|
|
}
|
|
|
|
function moveCratesPart1(cargo: cargo, instructions: instruction[]) {
|
|
for (const instruction of instructions) {
|
|
let count = 0;
|
|
while (count < instruction.amount) {
|
|
cargo[instruction.to].push(cargo[instruction.from].pop()!);
|
|
count++;
|
|
}
|
|
}
|
|
return cargo.reduce((prev, cur) => prev + cur.at(-1), '');
|
|
}
|
|
|
|
function moveCratesPart2(cargo: cargo, instructions: instruction[]) {
|
|
for (const instruction of instructions) {
|
|
cargo[instruction.to].push(
|
|
...cargo[instruction.from].splice(-instruction.amount),
|
|
);
|
|
}
|
|
return cargo.reduce((prev, cur) => prev + cur.at(-1), '');
|
|
}
|
|
|
|
const [cargo, instructions] = getInitialData();
|
|
console.log(
|
|
`Solution Part 1:`,
|
|
moveCratesPart1(structuredClone(cargo), instructions),
|
|
);
|
|
console.log(`Solution Part 2:`, moveCratesPart2(cargo, instructions));
|