Published
Edited
Dec 6, 2021
5 stars
Insert cell
Insert cell
Plot.plot({
marks: [annotatedLine(part1), annotatedLine(part2)],
y: { reverse: true, type: "log" },
marginRight: 80
})
Insert cell
annotatedLine = (input) => [
Plot.line(input, { x: "x", y: "y", strokeWidth: 1 }),
Plot.text(
input,
Plot.selectLast({
x: "x",
y: "y",
text: (d) => `🛶 ${d.x * d.y}`,
textAnchor: "start",
dx: 5
})
)
]
Insert cell
part1 = {
const data = [];
let x = 0,
y = 0;
for (const { command, n } of commands) {
switch (command) {
case "forward":
x += n;
break;
case "down":
y += n;
break;
case "up":
y -= n;
break;
}
data.push({x, y});
yield data;
}
}
Insert cell
part2 = {
const points = [];
let x = 0,
y = 0,
aim = 0;
for (const { command, n } of commands) {
switch (command) {
case "forward":
x += n;
y += aim * n;
break;
case "down":
aim += n;
break;
case "up":
aim -= n;
break;
}
points.push({ x, y, aim });
yield points;
}
}
Insert cell
commands = input
.trim()
.split("\n")
.map((d) => {
const [command, n] = d.split(" ");
return { command, n: +n };
})
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