adventofcode/2022/05/part1.js

79 lines
1.6 KiB
JavaScript
Raw Normal View History

2022-12-05 16:16:31 +00:00
import * as R from "remeda";
2022-12-07 23:42:05 +00:00
import fs from "fs-extra";
import path from "path";
import { fileURLToPath } from "url";
2022-12-05 16:16:31 +00:00
2022-12-07 23:42:05 +00:00
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");
2022-12-05 16:16:31 +00:00
function parseHeaps(text) {
2022-12-07 23:36:16 +00:00
const lines = text.split("\n").filter(R.identity);
lines.reverse();
2022-12-05 16:16:31 +00:00
2022-12-07 23:36:16 +00:00
let [header, ...crates] = lines;
2022-12-05 16:16:31 +00:00
2022-12-07 23:36:16 +00:00
const stacks = [];
2022-12-05 16:16:31 +00:00
2022-12-07 23:36:16 +00:00
while (header.trimEnd()) {
header = header.replace(/^(\s+)\d/, (...args) => {
crates = crates.map((c) => c.slice(args[1].length));
2022-12-05 16:16:31 +00:00
2022-12-07 23:36:16 +00:00
const stack = [];
2022-12-05 16:16:31 +00:00
2022-12-07 23:36:16 +00:00
crates = crates.map((l) =>
l.replace(/./, (c) => {
if (c !== " ") stack.push(c);
return "";
})
);
2022-12-05 16:16:31 +00:00
2022-12-07 23:36:16 +00:00
stacks.push(stack);
2022-12-05 16:16:31 +00:00
2022-12-07 23:36:16 +00:00
return "";
});
}
2022-12-05 16:16:31 +00:00
2022-12-07 23:36:16 +00:00
return stacks;
2022-12-05 16:16:31 +00:00
}
function parseCommands(text) {
2022-12-07 23:36:16 +00:00
return text
.split("\n")
.filter(R.identity)
.map((line) => line.match(/\d+/g).map((x) => parseInt(x)));
2022-12-05 16:16:31 +00:00
}
2022-12-07 23:36:16 +00:00
function moveStacks([stacks, commands]) {
for (let [move, from, to] of commands) {
console.log({ move, from, to });
2022-12-05 16:16:31 +00:00
2022-12-07 23:36:16 +00:00
while (move-- > 0) {
stacks[to - 1].push(stacks[from - 1].pop());
2022-12-05 16:16:31 +00:00
}
2022-12-07 23:36:16 +00:00
}
2022-12-05 16:16:31 +00:00
2022-12-07 23:36:16 +00:00
return stacks;
2022-12-05 16:16:31 +00:00
}
2022-12-07 23:42:05 +00:00
export const spy = (x) => {
2022-12-07 23:36:16 +00:00
console.log(x);
return x;
};
2022-12-05 16:16:31 +00:00
2022-12-07 23:42:05 +00:00
export const parseLines = ([heaps, commands]) => [
parseHeaps(heaps),
parseCommands(commands),
];
2022-12-05 16:16:31 +00:00
export const solutionPart1 = R.createPipe(
2022-12-07 23:36:16 +00:00
(text) => text.split("\n\n"),
2022-12-07 23:42:05 +00:00
parseLines,
2022-12-07 23:36:16 +00:00
moveStacks,
R.map((x) => x.pop()),
(x) => x.join("")
);