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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more