Skip to content

Commit

Permalink
2024D09: Part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
martapanc committed Dec 9, 2024
1 parent 3cd3268 commit 276c46d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 20 deletions.
2 changes: 1 addition & 1 deletion 2024/src/2024/day09/day09.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ describe('2024 Day 9', () => {
test('Part 1', async () => {
expect(await part1('testInput2')).toEqual(60);
expect(await part1('testInput1')).toEqual(1928);
expect(await part1('input')).toEqual(87084237216); //Too low
expect(await part1('input')).toEqual(6435922584968);
});

test('Part 2', async () => {
Expand Down
36 changes: 17 additions & 19 deletions 2024/src/2024/day09/day09.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,16 @@ function fragmentAndCalcChecksum(line: string) {
let lastBlock = expandedDisk[lastBlockIndex];
const [blockId, blockLength] = Object.entries(lastBlock)[0];

if (firstEmptyIndex === lastBlockIndex) {
break;
}

if (blockId === dot) {
expandedDisk.pop();
continue;
}

if (firstEmptyIndex === lastBlockIndex) {
break;
}


if (blockLength > emptyLength) {
firstEmptyBlock = { [blockId]: emptyLength };
expandedDisk[firstEmptyIndex] = firstEmptyBlock;
Expand All @@ -59,9 +60,7 @@ function fragmentAndCalcChecksum(line: string) {
}
}

const checksum = collapseAndCalcChecksum(expandedDisk);

return checksum;
return collapseAndCalcChecksum(expandedDisk);
}

export function expandDiskMap(line: string) {
Expand All @@ -84,21 +83,20 @@ export function expandDiskMap(line: string) {
}

export function collapseAndCalcChecksum(list: object[]) {
let collapsed = "";

list.forEach((block) => {
const [blockId, blockLength] = Object.entries(block)[0];
let checksum = 0;
let currentPosition = 0;

Array(blockLength).fill(0).forEach(i => {
collapsed += blockId;
})
});
for (const block of list) {
const [blockId, length] = Object.entries(block)[0];
const id = parseInt(blockId, 10);
const len = length;

let checksum = 0;
for (let i = 0; i < len; i++) {
checksum += id * (currentPosition + i);
}

collapsed.replace(".", "").split("").forEach((blockId, index) => {
checksum += Number.parseInt(blockId) * index;
});
currentPosition += len;
}

return checksum;
}

0 comments on commit 276c46d

Please sign in to comment.