Public
Edited
Nov 11, 2022
1 star
Insert cell
Insert cell
Insert cell
function translate([x, y], [dx, dy]) {
return [x + dx, y + dy];
}
Insert cell
function scale([x, y], sc) {
return [sc * x, sc * y];
}
Insert cell
function rotate([x, y], dir) {
switch ((dir + 360) % 360) {
case 90:
return [-y, x];
case 180:
return [-x, -y];
case 270:
return [y, -x];
}
return [x, y];
}
Insert cell
Insert cell
function parse(rotateShip, forwardShip, initShip, input) {
const move = (ship, instr) => {
if (instr[0] == 'N') {
return [ship[0], translate(ship[1], [0, Number(instr.slice(1))])];
}
if (instr[0] == 'S') {
return [ship[0], translate(ship[1], [0, -1 * Number(instr.slice(1))])];
}
if (instr[0] == 'E') {
return [ship[0], translate(ship[1], [Number(instr.slice(1)), 0])];
}
if (instr[0] == 'W') {
return [ship[0], translate(ship[1], [-1 * Number(instr.slice(1)), 0])];
}
if (instr[0] == 'L') {
return rotateShip(ship, Number(instr.slice(1)));
}
if (instr[0] == 'R') {
return rotateShip(ship, -1 * Number(instr.slice(1)));
}
if (instr[0] == 'F') {
return forwardShip(ship, Number(instr.slice(1)));
}
};
return input.split('\n').reduce(move, initShip);
}
Insert cell
Insert cell
function rotateShip1(ship, n) {
return [rotate(ship[0], n), ship[1]];
}
Insert cell
function forwardShip1(ship, n) {
return [ship[0], translate(ship[1], scale(ship[0], n))];
}
Insert cell
Insert cell
function part1(input) {
const magnitude = ([_, [x, y]]) => Math.abs(x) + Math.abs(y);
return magnitude(parse(rotateShip1, forwardShip1, [[1, 0], [0, 0]], input));
}
Insert cell
Insert cell
Insert cell
Insert cell
function rotateShip2(ship, n) {
return [ship[0], rotate(ship[1], n)];
}
Insert cell
function forwardShip2(ship, n) {
return [translate(ship[0], scale(ship[1], n)), ship[1]];
}
Insert cell
function part2(input) {
const magnitude = ([[x, y], _]) => Math.abs(x) + Math.abs(y);
return magnitude(parse(rotateShip2, forwardShip2, [[0, 0], [10, 1]], input));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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