day09 example is working

This commit is contained in:
2024-12-22 22:19:37 +01:00
parent 98bf0f9dd1
commit d332e1cda1
2 changed files with 46 additions and 8 deletions

View File

@ -1,17 +1,54 @@
import fs from 'node:fs' import fs from 'node:fs'
class Block {
constructor() {
this.Id = BigInt
this.Size = BigInt
}
}
class Disk {
constructor() {
this.Map = [{}]
}
}
function init(filename) { function init(filename) {
const data = fs.readFileSync(filename, { encoding: 'utf-8' }, data => data) 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 table = "" let reversed_table = [...diskmap].reverse().filter(sector => sector !== '.')
let files = [...data.split('').filter((val, idx) => idx % 2 === 0)] let new_diskmap = [...diskmap]
let free_spaces = [...data.split('').filter((val, idx) => idx % 2 !== 0)] for (let i = 0; i < new_diskmap.length; i++) {
let diskmap = [...data.split('')] console.log(new_diskmap.join(""))
if (new_diskmap[i] === '.') {
diskmap.forEach((sector, index) => { const lastChar = reversed_table.shift()
table += index % 2 === 0 ? ''.padStart(sector, index / 2) : ''.padStart(sector, '.') const rightMostIndex = new_diskmap.lastIndexOf(lastChar);
}) if (rightMostIndex > i) {
console.log(table) [new_diskmap[i], new_diskmap[rightMostIndex]] = [new_diskmap[rightMostIndex], new_diskmap[i]];
}
}
} }
init('easy_example.txt') /* 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')

File diff suppressed because one or more lines are too long