Public
Edited
Dec 9, 2022
Insert cell
Insert cell
Insert cell
class Grid {
constructor() {
this.head = { x: 0, y: 0 };
this.tail = { x: 0, y: 0 };
this.grid = new Map();
this.grid.set("0:0", 1);
}

move(dir) {
this.moveTail();
this.recordTailPosition();
switch (dir) {
case "R":
this.head.x++;
break;
case "U":
this.head.y++;
break;
case "L":
this.head.x--;
break;
case "D":
this.head.y--;
break;
}
}

moveTail() {
// There's gotta be a better way to do this than a big if/else block
if (this.head.x === this.tail.x && this.head.y === this.tail.y) return;
if (this.head.x > this.tail.x) {
this.tail.x++;
if (this.head.y > this.tail.y) {
this.tail.y++;
} else if (this.head.y < this.tail.y) {
this.tail.x++;
}
} else if (this.head.x < this.tail.x) {
this.tail.x--;
if (this.head.y > this.tail.y) {
this.tail.y++;
} else if (this.head.y < this.tail.y) {
this.tail.x++;
}
} else if (this.head.y > this.tail.y) {
this.tail.y++;
} else if (this.head.y < this.tail.y) {
this.tail.y--;
}
}

key(x, y) {
return `${x}:${y}`;
}

recordTailPosition() {
const gridKey = this.key(this.tail.x, this.tail.y);
const val = this.grid.get(gridKey);
this.grid.set(gridKey, val ? val + 1 : 1);
}

gridSize() {
return [...this.grid.keys()].reduce(
([maxX, maxY], key) => {
const [x, y] = key.split(":").map((n) => parseInt(n));
return [Math.max(x, maxX), Math.max(y, maxY)];
},
[0, 0]
);
}

render() {
// return [...this.grid.keys()];
const [maxX, maxY] = this.gridSize();
// return [maxX, maxY];

return { head: this.head, tail: this.tail, maxX };
let output = "";
for (let i = maxY; i >= 0; i--) {
for (let j = 0; j <= maxX; j++) {
if (this.head.x === j && this.head.y === i) {
output += "H";
} else if (this.tail.x === j && this.tail.y === i) {
output += "T";
} else if (i === 0 && j === 0) {
output += "s";
} else {
output += ".";
}
output += " ";
}
output += "\n";
}
return html`<pre>${output}</pre>`;
}
}
Insert cell
new Grid().render()
Insert cell
{
const grid = new Grid();
grid.move("R");
grid.move("R");
grid.move("R");
// grid.move("R");
// grid.move("U");
// grid.move("U");
// grid.move("U");
// grid.move("U");
return grid.render();
}
Insert cell
parse = (input) =>
input
.split("\n")
.map((l) => l.split(" "))
.map(([dir, num]) => [dir, parseInt(num)])
Insert cell
parse(testIput);
Insert cell
part1 = (input) => {
const moves = parse(input);
const grid = new Grid();
moves.forEach(([dir, num]) => {
for (let i = 0; i < num; i++) {
grid.move(dir);
}
});
return grid.grid;
}
Insert cell
part1(testIput)
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