Published
Edited
Dec 9, 2019
Insert cell
md`# Advent of Code 2019 Day 3`
Insert cell
// const input = `R75,D30,R83,U83,L12,D49,R71,U7,L72
// U62,R66,U55,R34,D71,R55,D58,R83`;
input = `R8,U5,L5,D3
U7,R6,D4,L4`;
Insert cell
wires = input.split( '\n' ).map( w => w.split( ',' ) );
Insert cell
get = ( board, x, y ) => {
if ( ! board[y] ) board[y] = [];
return board[y][x];
}
Insert cell
set = ( board, x, y, char ) => {
if ( get( board, x, y ) ) {
board[y][x] = 'X';
return true;
}
board[y][x] = char;
return false;
}
Insert cell
collisions = [];
Insert cell
process = ( board, wire ) => {
const instructions = wire.map( el => [ el[0], parseInt( el.slice(1) ) ] );
instructions.forEach( i => {
const [ dir, dist ] = i;
let char = '.';
for ( i = 0; i < dist; i++ ) {
switch( dir ) {
case 'R':
turtle[0]++;
char = '-';
break;
case 'U':
turtle[1]++;
char = '|';
break;
case 'D':
turtle[1]--;
char = '|';
break;
case 'L':
turtle[0]--;
char = '-';
break;
default:
throw i;
}
if ( set( turtle[0], turtle[1], char ) ) {
collisions.push( [ ...turtle ] );
}
}
})
}
Insert cell
output = ( board ) => {
const boardWidth = board.reduce( ( ( max, row ) => Math.max( max, row.length ) ), 0 );
let table = '<table>';
for ( let i = board.length - 1; i >= 0; i-- ) {
table += '<tr>';
for ( let j = 0; j < boardWidth; j++ ) {
table += `<td>${ board[i][j] || '.'}</td>`;
}
table += '</tr>';
}
table += '</table>';
return html`${table}`;
}
Insert cell
{
process( wires[0] );
return output( board );
}
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