Skip to content

Commit

Permalink
Working optimized version
Browse files Browse the repository at this point in the history
Constantly looping to find the first available freespace
was bothering me
  • Loading branch information
romellem committed Jan 3, 2025
1 parent 35b7547 commit 4c37ce2
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions 2024/9/part-two.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,14 @@ for (let block of freespace) {

function findFreeSpace(file: File): Freespace | undefined {
const validFreespaces = Array.from(freespaceMap.entries())
.filter(([size]) => size >= file.size)
.map(([, blocks]) => blocks[0])
.filter((block: Freespace | undefined) => {
if (!block) {
return false;
}

return block.start < file.start && block.size >= file.size;
})
.sort((a, b) => a.start - b.start);

return validFreespaces[0];
Expand All @@ -96,8 +102,8 @@ function partialChecksumForFile(file: File): number {
let checksum = 0;
// Compute checksum and move files at the same time
for (let i = files.length - 1; i >= 0; i--) {
let endFile = files[i];
let freeSpace = findFreeSpace(endFile);
const endFile = files[i];
const freeSpace = findFreeSpace(endFile);

if (freeSpace !== undefined) {
endFile.start = freeSpace.start;
Expand All @@ -116,7 +122,6 @@ for (let i = files.length - 1; i >= 0; i--) {
}

checksum += partialChecksumForFile(endFile);
// console.log(checksum);
}

console.log(checksum);
Expand Down

0 comments on commit 4c37ce2

Please sign in to comment.