Published
Edited
Dec 13, 2021
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
return fold(input.dots, input.folds[0], input.dimensions).dots
}
Insert cell
function fold(dots, fold, dimensions) {
let newDots = dots.map( dot => {
let [x,y] = dot
if (fold.axis === "x") {
if (x > fold.position)
return `${fold.position - (x-fold.position)} ${y}`
else
return `${x} ${y}`
} else {
if (y > fold.position)
return `${x} ${fold.position - (y-fold.position)}`
else
return `${x} ${y}`
}
})

let newDimensions = [
fold.axis === "x" ? fold.position : dimensions[0],
fold.axis === "y" ? fold.position : dimensions[1]
]
return {
dots: Array.from(new Set(newDots)).map( dot => dot.split(" ").map(parseFloat)),
dimensions: newDimensions
}
}
Insert cell
Insert cell
function displayPaper(dots, dimensions) {
let svg = d3.create("svg")
.attr("width", dimensions[0] * dotScale)
.attr("height", dimensions[1] * dotScale)
svg.selectAll(".dots")
.data(dots)
.join("rect")
.attr("x", d => d[0] * dotScale)
.attr("y", d => d[1] * dotScale)
.attr("width", dotScale)
.attr("height", dotScale)
.style("fill", "black")
return svg.node()
}
Insert cell
Insert cell
Insert cell
function readInput(txt) {
let dots = []
let folds = []
let dimensions = [0,0]
txt.trim().split("\n").forEach( line => {
if (line.trim().length > 0) {
if (line.indexOf("fold") === -1) {
// register a dot
let dot = line.trim().split(",").map(parseFloat)
if (dot[0] + 1 > dimensions[0])
dimensions[0] = dot[0] + 1
if (dot[1] + 1 > dimensions[1])
dimensions[1] = dot[1] + 1
dots.push(dot)
} else {
// register a fold
let parts = line.trim().split("=")
folds.push({
axis: parts[0][parts[0].length - 1],
position: parseFloat(parts[1])
})
}
}
})
return {
folds: folds,
dots: dots,
dimensions: dimensions
}
}
Insert cell
test = readInput(`6,10
0,14
9,10
0,3
10,4
4,11
6,0
6,12
4,1
0,13
10,12
3,4
3,0
8,4
1,10
2,14
8,10
9,0

fold along y=7
fold along x=5`)
Insert cell
input = FileAttachment("13_input.txt").text().then( txt => readInput(txt))
Insert cell
hardInput = FileAttachment("13_input_harder.txt").text().then( txt => readInput(txt))
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