adventofcode/2022/07/part1.js

68 lines
1.4 KiB
JavaScript
Raw Normal View History

2022-12-07 23:43:09 +00:00
import * as R from "remeda";
import { readFile } from "../05/part1.js";
import path from "path";
const readInput = (...args) =>
readFile(...args)
.split("\n")
.filter((x) => x);
export const puzzleInput = readInput(import.meta.url, "input");
export const sample = readInput(import.meta.url, "sample");
export function parseInput(lines) {
lines = [...lines];
let currentDir = "/";
const data = {};
while (lines.length > 0) {
const line = lines.shift();
let match = line.match(/\$ cd (.*)/);
if (match) {
currentDir = match[1].startsWith("/")
? match[1]
: path.join(currentDir, match[1]);
if (!data[currentDir]) data[currentDir] = 0;
continue;
}
if (/^\d+/.test(line)) {
const [size] = line.match(/\d+/);
data[currentDir] += parseInt(size);
}
}
return data;
}
export function cumulative(individual) {
const isIn = (k, targetKey) => {
const result =
k === targetKey ||
k.startsWith(targetKey.endsWith("/") ? targetKey : targetKey + "/");
return result;
};
return R.pipe(
individual,
R.mapValues((v, targetKey) => {
const sum = R.sumBy(
Object.values(R.pickBy(individual, (v, k) => isIn(k, targetKey))),
R.identity
);
2022-12-07 23:43:32 +00:00
return sum;
})
2022-12-07 23:43:09 +00:00
);
}
export default R.createPipe(
parseInput,
cumulative,
R.pickBy((v) => v <= 100000),
R.values,
R.sumBy(R.identity)
);