diff --git a/2024/src/2024/day09/day09.test.ts b/2024/src/2024/day09/day09.test.ts index 7f3f015..f63c473 100644 --- a/2024/src/2024/day09/day09.test.ts +++ b/2024/src/2024/day09/day09.test.ts @@ -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 () => { diff --git a/2024/src/2024/day09/day09.ts b/2024/src/2024/day09/day09.ts index 8eaaa7e..d1f0629 100644 --- a/2024/src/2024/day09/day09.ts +++ b/2024/src/2024/day09/day09.ts @@ -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; @@ -59,9 +60,7 @@ function fragmentAndCalcChecksum(line: string) { } } - const checksum = collapseAndCalcChecksum(expandedDisk); - - return checksum; + return collapseAndCalcChecksum(expandedDisk); } export function expandDiskMap(line: string) { @@ -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; } \ No newline at end of file