57 lines
1.6 KiB
JavaScript
57 lines
1.6 KiB
JavaScript
import fs from 'node:fs'
|
|
|
|
function init(filename) {
|
|
const data = fs.readFileSync(filename, { encoding: 'utf-8' }, data => data)
|
|
const reader = new Reader()
|
|
data.split('\n\n').forEach(schematic => reader.readSchematics(schematic))
|
|
reader.part1()
|
|
}
|
|
|
|
class Reader {
|
|
constructor() {
|
|
this.Keys = []
|
|
this.Locks = []
|
|
}
|
|
|
|
getHeights(schematic) {
|
|
const lines = schematic.split('\n')
|
|
let pins = 0
|
|
let pin = [0, 0, 0, 0, 0]
|
|
while (pins < 5) {
|
|
let height = 0
|
|
for (let row = 0; row < lines.length; row++) {
|
|
if (lines[row][pins] === '#') pin[pins] += 1
|
|
}
|
|
pins++
|
|
}
|
|
return pin.map(p => p - 1).join(",")
|
|
}
|
|
fits(key, lock) {
|
|
const k = key.split(',').map(k => parseInt(k))
|
|
const l = lock.split(',').map(l => parseInt(l))
|
|
let fits = true
|
|
for (let i = 0; i < k.length; i++) {
|
|
if (k[i] + l[i] > 5) { fits = false }
|
|
}
|
|
//console.log(`key ${key} ${fits ? "fits" : "doesn't fit"} into ${lock}`)
|
|
return fits
|
|
}
|
|
readSchematics(schematic) {
|
|
const isKey = schematic[0] == '.' ? true : false
|
|
if (isKey) { this.Keys.push(this.getHeights(schematic)) }
|
|
else { this.Locks.push(this.getHeights(schematic)) }
|
|
|
|
}
|
|
part1() {
|
|
let foundKeys = 0
|
|
this.Keys.forEach((key, index) => {
|
|
this.Locks.forEach((lock, index) => {
|
|
foundKeys += this.fits(key, lock) ? 1 : 0
|
|
})
|
|
|
|
})
|
|
console.log(foundKeys)
|
|
}
|
|
}
|
|
|
|
init('input.txt') |