adventofcode/2022/05/part1.js
2022-12-07 18:42:05 -05:00

79 lines
1.6 KiB
JavaScript

import * as R from "remeda";
import fs from "fs-extra";
import path from "path";
import { fileURLToPath } from "url";
export const readFile = (url, file) =>
fs.readFileSync(path.join(fileURLToPath(new URL(".", url)), file), "utf8");
export const sample = readFile(import.meta.url, "sample");
export const puzzleInput = readFile(import.meta.url, "input");
function parseHeaps(text) {
const lines = text.split("\n").filter(R.identity);
lines.reverse();
let [header, ...crates] = lines;
const stacks = [];
while (header.trimEnd()) {
header = header.replace(/^(\s+)\d/, (...args) => {
crates = crates.map((c) => c.slice(args[1].length));
const stack = [];
crates = crates.map((l) =>
l.replace(/./, (c) => {
if (c !== " ") stack.push(c);
return "";
})
);
stacks.push(stack);
return "";
});
}
return stacks;
}
function parseCommands(text) {
return text
.split("\n")
.filter(R.identity)
.map((line) => line.match(/\d+/g).map((x) => parseInt(x)));
}
function moveStacks([stacks, commands]) {
for (let [move, from, to] of commands) {
console.log({ move, from, to });
while (move-- > 0) {
stacks[to - 1].push(stacks[from - 1].pop());
}
}
return stacks;
}
export const spy = (x) => {
console.log(x);
return x;
};
export const parseLines = ([heaps, commands]) => [
parseHeaps(heaps),
parseCommands(commands),
];
export const solutionPart1 = R.createPipe(
(text) => text.split("\n\n"),
parseLines,
moveStacks,
R.map((x) => x.pop()),
(x) => x.join("")
);