From 314c6215f355387e39c9dab027e67b110857f537 Mon Sep 17 00:00:00 2001 From: tristan Date: Mon, 9 Dec 2024 17:41:57 +0000 Subject: [PATCH] 2024 day 9 part 2 in javascript --- 2024/09/solution.js | 6 +++-- 2024/09/solution2.js | 59 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 2024/09/solution2.js diff --git a/2024/09/solution.js b/2024/09/solution.js index 4cba1bf..a1696fd 100644 --- a/2024/09/solution.js +++ b/2024/09/solution.js @@ -49,7 +49,9 @@ const newfiles = files.concat(inserted) .filter(file => file.size > 0) .sort((a, b) => a.start > b.start) -const checksum = newfiles.reduce((acc, current) => acc + (current.id * current.size * (current.start + (current.size - 1) / 2)), 0) +const checksum = fs => fs.reduce((acc, current) => + acc + (current.id * current.size * (current.start + (current.size - 1) / 2)), +0) -console.log(checksum) +console.log(checksum(newfiles)) diff --git a/2024/09/solution2.js b/2024/09/solution2.js new file mode 100644 index 0000000..2712435 --- /dev/null +++ b/2024/09/solution2.js @@ -0,0 +1,59 @@ + +const input = (await Bun.file("input.txt").text()).trim() + +// const input = "2933133121414131402"; +/* + * 0123456789 + * 0..1.....2 + * 02.1 + * 021 + */ + + +const files = []; + +const spaces = [[], [], [], [], [], [], [], [], [], [], ]; + +let pos = 0; +for (let i = 0; i < input.length; i++ ) { + const size = parseInt(input[i]) + if (size == 0) continue + if (i % 2 == 0) { + files.push({size, id: i / 2, start: pos,}) + } else { + spaces[size].push(pos) + } + pos += size; +} + +for (let i = files.length - 1; i >= 0; i--) { + const file = files[i] + const fitspaces = []; + for (let size = files[i].size; size <= 9; size ++ ) { + if (spaces[size].length == 0) { + continue + } + const start = spaces[size][0] + if (start > file.start) { + continue + } + fitspaces.push({size, start}) + } + if (fitspaces.length == 0) continue + fitspaces.sort((a, b) => a.start > b.start) + const space = fitspaces[0] + files[i].start = space.start; + spaces[space.size].shift() + const newspacestart = space.start + files[i].size + const newspacesize = space.size - file.size + if (newspacesize == 0) continue + spaces[newspacesize].push(newspacestart) + spaces[newspacesize].sort((a, b) => a > b) +} + +const checksum = fs => fs.reduce((acc, current) => + acc + (current.id * current.size * (current.start + (current.size - 1) / 2)), +0) + +console.log(checksum(files)) +