day 9 part one finally done
This commit is contained in:
62
09/index.ts
62
09/index.ts
@@ -1,7 +1,7 @@
|
|||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import { printTime, now, toNum } from "../util";
|
import { printTime, now, toNum } from "../util";
|
||||||
|
|
||||||
const test = true;
|
const test = false;
|
||||||
|
|
||||||
const data = fs.readFileSync(
|
const data = fs.readFileSync(
|
||||||
test ? "./inputs/testinput" : "./inputs/input",
|
test ? "./inputs/testinput" : "./inputs/input",
|
||||||
@@ -9,36 +9,42 @@ const data = fs.readFileSync(
|
|||||||
);
|
);
|
||||||
|
|
||||||
let timer = now.instant();
|
let timer = now.instant();
|
||||||
|
|
||||||
|
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(
|
console.log(
|
||||||
"part one:",
|
"part one:",
|
||||||
data
|
sparceArray.reduce((checksum, curr, i) => {
|
||||||
.split("\n")
|
if (curr !== -1) {
|
||||||
.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>)
|
|
||||||
.reduce((disk, current, i, a) => {
|
|
||||||
console.log(disk, current, i, a);
|
|
||||||
if (current === -1) {
|
|
||||||
while (true) {
|
|
||||||
let tail = a.pop();
|
|
||||||
if (tail === -1 || tail === undefined) {
|
|
||||||
continue;
|
|
||||||
} else {
|
|
||||||
return [...disk, tail];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return [...disk, current];
|
|
||||||
}
|
|
||||||
}, [] as Array<number>)
|
|
||||||
.reduce((checksum, curr, i) => {
|
|
||||||
console.log(curr, i);
|
|
||||||
return checksum + curr * i;
|
return checksum + curr * i;
|
||||||
}, 0),
|
}
|
||||||
|
return checksum;
|
||||||
|
}, 0),
|
||||||
printTime(now.instant().since(timer))
|
printTime(now.instant().since(timer))
|
||||||
);
|
);
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user