AdventOfCode2024/09/index.ts

57 lines
1.3 KiB
TypeScript
Raw Normal View History

import fs from "node:fs";
import { printTime, now, toNum } from "../util";
2024-12-14 19:03:47 +00:00
const test = false;
const data = fs.readFileSync(
test ? "./inputs/testinput" : "./inputs/input",
"utf8"
);
let timer = now.instant();
2024-12-14 19:03:47 +00:00
let sparceArray = data
.split("\n")
.slice(0, -1)[0]
.split("")
.map(toNum)
.reduce((disk, curr, index) => {
const fill = index % 2 === 0 ? index / 2 : -1; // -1 represents free space
return [...disk, ...Array.from({ length: curr }, () => fill)];
}, [] as Array<number>);
let rightCursor = sparceArray.length - 1;
let leftCursor = 0;
while (leftCursor < rightCursor) {
if (sparceArray[leftCursor] === -1) {
while (sparceArray[rightCursor] === -1) {
rightCursor--;
}
if (leftCursor > rightCursor) {
// don't let them overrun each other
break;
}
sparceArray[leftCursor] = sparceArray[rightCursor];
sparceArray[rightCursor] = -1;
}
leftCursor++;
}
console.log(
"part one:",
2024-12-14 19:03:47 +00:00
sparceArray.reduce((checksum, curr, i) => {
if (curr !== -1) {
return checksum + curr * i;
2024-12-14 19:03:47 +00:00
}
return checksum;
}, 0),
printTime(now.instant().since(timer))
);
// timer = now.instant();
// console.log(
// "part two:",
// data.split("\n").slice(0, -1),
// printTime(now.instant().since(timer))
// );