Public
Edited
Dec 2, 2021
Insert cell
Insert cell
Insert cell
/*
** Return the submarine's (x, y) position after a series of commands
*/
function find_final_position(commands) {
let x = 0;
let y = 0;

for (let index = 0; index < commands.length; ++index) {
var c = commands[index].split(' ');
if (c[0] == 'forward') {x += parseFloat(c[1]);}
if (c[0] == 'down') {y += parseFloat(c[1]);}
if (c[0] == 'up') {y -= parseFloat(c[1])};
}
return [x, y]
}
Insert cell
Insert cell
// Multiply final x, y position to get puzzle answer
find_final_position(test_commands).reduce((a, b)=> a*b, 1) // Should return 150
Insert cell
Insert cell
find_final_position(commands).reduce((a, b) => a*b, 1)
Insert cell
Insert cell
/*
** Return the submarine's (x, y) position after a series of commands
*/
function find_final_position_2(commands) {
let x = 0;
let y = 0;
let aim = 0;

for (let index = 0; index < commands.length; ++index) {
var c = commands[index].split(' ');
if (c[0] == 'forward') {x += parseFloat(c[1]); y += aim * parseFloat(c[1])}
if (c[0] == 'down') {aim += parseFloat(c[1]);}
if (c[0] == 'up') {aim -= parseFloat(c[1])};
}
return [x, y]
}
Insert cell
Insert cell
// Multiply final x, y position to get puzzle answer
find_final_position_2(test_commands).reduce((a, b) => a*b, 1) // Should return 900
Insert cell
Insert cell
find_final_position_2(commands).reduce((a, b) => a*b, 1)
Insert cell
Insert cell
Insert cell
commands[0]
Insert cell
commands.length
Insert cell
commands = inputs.split('\n')
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