Public
Edited
Nov 17, 2022
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
class Img {
constructor(lines, data, algo, width, height, surroundings = 0) {
this.algo = algo
this.lines = lines
this.surroundings = surroundings
this.width = width
this.height = height

if (data === null) {
let img = new Map()
lines.forEach( (line, lineIdx) => {
for (let charIdx = 0; charIdx < line.length; charIdx++) {
img.set(`${charIdx} ${lineIdx}`, line[charIdx] === '#' ? 1 : 0)
}
})
this.data = img
} else {
this.data = data
}
}

getPixelBinaryNb(pixelX, pixelY) {
let bits = ''
for (let y of [-1, 0, 1]) {
for (let x of [-1, 0, 1]) {
bits += this.data.get(`${pixelX + x} ${pixelY + y}`) ?? this.surroundings
}
}
return parseInt(bits, 2)
}

getSurroundingsBinaryNb() {
return parseInt(this.surroundings === 1 ? '111111111' : '000000000', 2)
}

getLitPixelsCount() {
if (this.surroundings === 1)
return Infinity
else
return Array.from(this.data.values()).filter(d => d === 1).length
}

enhance(iterations = 1) {
let img = this
for (let i = 0; i < iterations; i++) {
let enhancedImgData = new Map()
for (let yIdx = -1; yIdx <= img.height; yIdx++) {
for (let xIdx = -1; xIdx <= img.width; xIdx++) {
let binNb = img.getPixelBinaryNb(xIdx, yIdx)
enhancedImgData.set(`${xIdx + 1} ${yIdx + 1}`, img.algo[binNb] === '#' ? 1 : 0)
}
}
let enhancedSurroundings = img.algo[img.getSurroundingsBinaryNb()] === '#' ? 1 : 0
img = new Img(null, enhancedImgData, img.algo, img.width + 2, img.height + 2, enhancedSurroundings)
}
return img
}
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
enhancedTwice.getLitPixelsCount()
Insert cell
Insert cell
enhanced50Times = dataset.enhance(50)
Insert cell
enhanced50Times.getLitPixelsCount()
Insert cell
Insert cell
Insert cell
Insert cell
function readInput(txt) {
let lines = txt.replaceAll('\r','').split("\n").filter(d => d.length > 0)
let algo = lines.shift()
let img = new Map()
lines.forEach( (line, lineIdx) => {
for (let charIdx = 0; charIdx < line.length; charIdx++) {
img.set(`${charIdx} ${lineIdx}`, line[charIdx] === '#' ? 1 : 0)
}
})
return new Img(lines, null, algo, lines[0].length, lines.length)
}
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more