Files
advent-of-code/2024/09/index.js

39 lines
1.4 KiB
JavaScript

import fs from 'node:fs'
function init(filename) {
const data = fs.readFileSync(filename, { encoding: 'utf-8' }, data => data)
const diskmap = [...data.split('')].map((sector, index) => index % 2 === 0 ? ''.padStart(sector, index / 2) : ''.padStart(sector, '.')).join("")
let reversed_table = [...diskmap].reverse().filter(sector => sector !== '.')
let new_diskmap = [...diskmap]
for (let i = 0; i < new_diskmap.length; i++) {
console.log(new_diskmap.join(""))
if (new_diskmap[i] === '.') {
const lastChar = reversed_table.shift()
const rightMostIndex = new_diskmap.lastIndexOf(lastChar);
if (rightMostIndex > i) {
[new_diskmap[i], new_diskmap[rightMostIndex]] = [new_diskmap[rightMostIndex], new_diskmap[i]];
}
}
}
/* might be part2 solution */
//let new_diskmap = table.split('')
// new_diskmap.map((value, index) => {
// if (value === '.') {
// for (let i = index + 1; i < new_diskmap.length; i++) {
// if (new_diskmap[i] !== '.') {
// [new_diskmap[index], new_diskmap[i]] = [new_diskmap[i], new_diskmap[index]];
// break;
// }
// }
// }
// });
let res = 0
new_diskmap.forEach((value, index) => {
res += !isNaN(value) ? index * value : 0
})
console.log(res)
}
init('example.txt')