day 05 part 1 finished
This commit is contained in:
82
2023/day05/index.js
Normal file
82
2023/day05/index.js
Normal file
@ -0,0 +1,82 @@
|
||||
import fs from 'node:fs'
|
||||
|
||||
function init() {
|
||||
const data = fs.readFileSync('example.txt', { encoding: "utf-8" }, data => data)
|
||||
const blocks = data.split('\n\n')
|
||||
|
||||
const garden = new Garden()
|
||||
garden.seeds = [...blocks[0].split(': ')[1].split(' ')]
|
||||
for (let i = 1; i < blocks.length; i++) {
|
||||
//console.log(blocks[i].split('\n')[0])
|
||||
const map = blocks[i].split('\n').slice(1).map(items => {
|
||||
let ranges = items.split(' ')
|
||||
return { dest: Number(ranges[0]), srcStart: Number(ranges[1]), srcEnd: (Number(ranges[1]) + Number(ranges[2]) - 1) }
|
||||
})
|
||||
garden.maps.push(map)
|
||||
}
|
||||
garden.runtwo()
|
||||
|
||||
}
|
||||
|
||||
class Garden {
|
||||
constructor() {
|
||||
this.seeds = []
|
||||
this.maps = []
|
||||
this.i = 0
|
||||
this.cache = new Map()
|
||||
}
|
||||
transform(value, map) {
|
||||
if (map) {
|
||||
return {
|
||||
dest: map.dest + (value - map.srcStart),
|
||||
srcStart: map.srcStart,
|
||||
srcEnd: map.srcEnd
|
||||
}
|
||||
}
|
||||
return {
|
||||
dest: value,
|
||||
srcStart: value,
|
||||
srcEnd: value
|
||||
}
|
||||
}
|
||||
|
||||
findDestination(src, iterator) {
|
||||
let cache = `${src}-${iterator}`
|
||||
if (iterator >= this.maps.length) return src
|
||||
if (this.cache.has(cache)) {
|
||||
console.log(`cached value for ${cache}`)
|
||||
return this.cache.get(cache)
|
||||
}
|
||||
let possible_destinations = this.maps[iterator]
|
||||
.filter(map => src >= map.srcStart && src <= map.srcEnd)
|
||||
.map(map => this.transform(src, map))
|
||||
|
||||
if (possible_destinations.length < 1)
|
||||
possible_destinations = [this.transform(src)]
|
||||
|
||||
let value = possible_destinations.reduce((current, next) => this.findDestination(parseInt(next.dest), iterator + 1), 1)
|
||||
this.cache.set(cache, value)
|
||||
return value
|
||||
}
|
||||
|
||||
run() {
|
||||
let locations = this.seeds.map(seed => this.findDestination(seed, this.i))
|
||||
console.log(Math.min.apply(null, locations))
|
||||
}
|
||||
runtwo() {
|
||||
let newSeedArray = []
|
||||
console.log(this.seeds)
|
||||
for (let i = 0; i < this.seeds.length; i = i + 2) {
|
||||
console.log(`pushing ${this.seeds[i]}`)
|
||||
for (let seed = parseInt(this.seeds[i]); seed <= parseInt(this.seeds[i + 1]); seed++) {
|
||||
console.log(`pushing ${seed}`)
|
||||
newSeedArray.push(seed)
|
||||
}
|
||||
}
|
||||
console.log(newSeedArray.length)
|
||||
let locations = newSeedArray.map(seed => this.findDestination(seed, this.i))
|
||||
console.log(Math.min.apply(null, locations))
|
||||
}
|
||||
}
|
||||
|
||||
init()
|
Reference in New Issue
Block a user