|
| 1 | +import { readFileSync } from "node:fs"; |
| 2 | + |
| 3 | +const lines = readFileSync("day05.txt", { encoding: "utf-8" }) // read day??.txt content |
| 4 | + .replace(/\r/g, "") // remove all \r characters to avoid issues on Windows |
| 5 | + .trimEnd(); // Remove ending whitespace |
| 6 | + |
| 7 | +const [rawStacks, rawMoves] = lines.split("\n\n").map((x) => x.split("\n")); |
| 8 | + |
| 9 | +const parsedStacks = rawStacks.map((line) => |
| 10 | + [...line].filter((value, index) => index % 4 === 1) |
| 11 | +); |
| 12 | + |
| 13 | +const indexes = parsedStacks.pop(); |
| 14 | + |
| 15 | +const stacks = {}; |
| 16 | + |
| 17 | +for (const line of parsedStacks) { |
| 18 | + for (let i = 0; i < line.length; i++) { |
| 19 | + if (line[i] !== " ") { |
| 20 | + // Add line[i] to the stack indexes[i] |
| 21 | + if (!stacks[indexes[i]]) { |
| 22 | + stacks[indexes[i]] = []; |
| 23 | + } |
| 24 | + stacks[indexes[i]].unshift(line[i]); |
| 25 | + } |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +const moves = []; |
| 30 | +for (const move of rawMoves) { |
| 31 | + const match = /move (\d+) from (\d+) to (\d+)/g.exec(move); |
| 32 | + moves.push({ |
| 33 | + count: parseInt(match[1]), |
| 34 | + from: parseInt(match[2]), |
| 35 | + to: parseInt(match[3]), |
| 36 | + }); |
| 37 | +} |
| 38 | + |
| 39 | +function part1() { |
| 40 | + const localStacks = JSON.parse(JSON.stringify(stacks)); |
| 41 | + for (const move of moves) { |
| 42 | + for (let i = 0; i < move.count; i++) { |
| 43 | + const crate = localStacks[move.from].pop(); |
| 44 | + localStacks[move.to].push(crate); |
| 45 | + } |
| 46 | + } |
| 47 | + console.log( |
| 48 | + indexes |
| 49 | + .map((value) => { |
| 50 | + const stack = localStacks[value]; |
| 51 | + return stack[stack.length - 1]; |
| 52 | + }) |
| 53 | + .join("") |
| 54 | + ); |
| 55 | +} |
| 56 | + |
| 57 | +function part2() { |
| 58 | + const localStacks = JSON.parse(JSON.stringify(stacks)); |
| 59 | + for (const move of moves) { |
| 60 | + const crates = localStacks[move.from].splice(-move.count, move.count); |
| 61 | + localStacks[move.to] = localStacks[move.to].concat(crates); |
| 62 | + } |
| 63 | + console.log( |
| 64 | + indexes |
| 65 | + .map((value) => { |
| 66 | + const stack = localStacks[value]; |
| 67 | + return stack[stack.length - 1]; |
| 68 | + }) |
| 69 | + .join("") |
| 70 | + ); |
| 71 | +} |
| 72 | + |
| 73 | +part1(); |
| 74 | +part2(); |
0 commit comments