For a description of this problem, please check the Advent of Code website.
Example Input:
2333133121414131402
Part 1 Solution:
const fs = require('fs');const input = fs.readFileSync('./example-input.txt', 'utf8').trim().split('').map(Number);let disk = [];let fileID = 0;for (let i = 0; i < input.length; i++) {if (i % 2 === 0) {for (let j = 0; j < input[i]; j++) {disk.push(fileID);}fileID++;} else {for (let j = 0; j < input[i]; j++) {disk.push(null);}}}let l = 0;let r = disk.length - 1;while (l < r) {if (disk[l] !== null) {l++;continue;}if (disk[r] === null) {r--;continue;}disk[l] = disk[r];disk[r] = null;l++;r--;}let checkSum = 0;for (let i = 0; i < disk.length; i++) {if (disk[i] !== null) {checkSum += i * disk[i];}}console.log(checkSum);
Part 2 Solution:
const fs = require('fs');const input = fs.readFileSync('./example-input.txt', 'utf8').trim().split('').map(Number);let disk = [];let fileID = 0;let emptySpaces = [];for (let i = 0; i < input.length; i++) {if (i % 2 === 0) {for (let j = 0; j < input[i]; j++) {disk.push(fileID);}fileID++;} else {let startIndex = disk.length;for (let j = 0; j < input[i]; j++) {disk.push(null);}emptySpaces.push({ length: input[i], startIndex });}}for (let id = fileID; id >= 0; id--) {// Find all blocks belonging to the current filelet fileBlocks = disk.map((block, index) => (block === id ? index : -1)).filter(index => index !== -1);if (fileBlocks.length === 0) continue;let fileLength = fileBlocks.length;// Find an empty space large enough for the file and left of its current positionfor (let k = 0; k < emptySpaces.length; k++) {if (emptySpaces[k].length >= fileLength && emptySpaces[k].startIndex < fileBlocks[0]) {// Move the file to the empty spacefor (let l = 0; l < fileLength; l++) {disk[emptySpaces[k].startIndex + l] = id;}// Update the empty spaceif (emptySpaces[k].length === fileLength) {emptySpaces.splice(k, 1);} else {emptySpaces[k] = {length: emptySpaces[k].length - fileLength,startIndex: emptySpaces[k].startIndex + fileLength,};}// Clear the old file positionfor (let l = 0; l < fileLength; l++) {disk[fileBlocks[l]] = null;}break;}}}let checkSum = 0;for (let i = 0; i < disk.length; i++) {if (disk[i] !== null) {checkSum += i * disk[i];}}console.log(checkSum);