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'
class Block {
constructor() {
this.Id = BigInt
this.Size = BigInt
}
}
class Disk {
constructor() {
this.Map = [{}]
}
}
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]];
}
}
}
let table = ""
let files = [...data.split('').filter((val, idx) => idx % 2 === 0)]
let free_spaces = [...data.split('').filter((val, idx) => idx % 2 !== 0)]
let diskmap = [...data.split('')]
/* 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;
// }
// }
// }
// });
diskmap.forEach((sector, index) => {
table += index % 2 === 0 ? ''.padStart(sector, index / 2) : ''.padStart(sector, '.')
let res = 0
new_diskmap.forEach((value, index) => {
res += !isNaN(value) ? index * value : 0
})
console.log(table)
console.log(res)
}
init('easy_example.txt')
init('example.txt')

File diff suppressed because one or more lines are too long