Published
Edited
Dec 15, 2018
Insert cell
Insert cell
Insert cell
Insert cell
class Cart {
constructor (id, row, col, symbol) {
this.id = id;
this.alive = true;
this.intersection = 0;
this.row = row;
this.col = col;
this.direction = {
'>': math.complex('1'),
'<': math.complex('-1'),
'^': math.complex('i'),
'v': math.complex('-i')
}[symbol];
}
rotate (direction) {
if (direction === 'R') {
this.direction = math.multiply(this.direction, math.complex('-i'));
} else if (direction === 'L') {
this.direction = math.multiply(this.direction, math.complex('i'));
}
}
move () {
if (this.direction.re === 0) {
this.row -= this.direction.im;
} else {
this.col += this.direction.re;
}
if (TRACK[this.row][this.col] === '/') {
(this.direction.re === 0) ? this.rotate('R') : this.rotate('L');
} else if (TRACK[this.row][this.col] === '\\') {
(this.direction.re === 0) ? this.rotate('L') : this.rotate('R');
} else if (TRACK[this.row][this.col] === '+') {
if (this.intersection === 0) {
this.rotate('L');
} else if (this.intersection === 2) {
this.rotate('R');
}
this.intersection = (this.intersection + 1) % 3;
}
}
static collides (a, b) {
return (a.id !== b.id &&
a.alive && b.alive &&
a.row === b.row &&
a.col === b.col);
}
}
Insert cell
function setUpCarts () {
let carts = [];
let cartId = 0;
for (let row = 0; row < DATA.length; row++) {
for (let col = 0; col < DATA[row].length; col++) {
if ('<>^v'.indexOf(DATA[row][col]) > -1) {
carts.push(new Cart(cartId, row, col, DATA[row][col]));
cartId++;
}
}
}
return carts;
}
Insert cell
part1 = {
let carts = setUpCarts();

while (true) {
// cycle through carts in row, col order
carts = carts.sort((a, b) => (a.row - b.row || a.col - b.col));
for (let c1 of carts) {
c1.move();
for (let c2 of carts) {
if (Cart.collides(c1, c2)) {
return [c1.col, c1.row];
}
}
}
}
}
Insert cell
Insert cell
part2 = {
let carts = setUpCarts();
while (carts.length > 1) {
carts = carts.sort((a, b) => (a.row - b.row || a.col - b.col));
for (let c1 of carts) {
c1.move();
for (let c2 of carts) {
if (Cart.collides(c1, c2)) {
c1.alive = false;
c2.alive = false;
}
}
}
// prune the dead
carts = carts.filter(c => c.alive);
}
return [carts[0].col, carts[0].row];
}
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