Skip to content

Instantly share code, notes, and snippets.

@FelicitusNeko
Created December 14, 2019 06:20
Show Gist options
  • Select an option

  • Save FelicitusNeko/436f57b88a21c541366eaf743f7be63d to your computer and use it in GitHub Desktop.

Select an option

Save FelicitusNeko/436f57b88a21c541366eaf743f7be63d to your computer and use it in GitHub Desktop.
Advent of Code 2019 Day 12
const pos3d = { x: 0, y: 0, z: 0 }
const gravObject = { pos: { x: 0, y: 0, z: 0 }, vel: { x: 0, y: 0, z: 0 } };
const gravMachine = (data, cycles) => {
let gravObjects = data.split(/[\r\n\<\>]+/).filter(i => i.length).map(i => {
let retval = { pos: Object.assign({}, pos3d), vel: Object.assign({}, pos3d) };
i.split(', ').map(ii => ii.split('=')).forEach(ii => retval.pos[ii[0]] = parseInt(ii[1]));
return retval;
});
for (let x = 1; x <= cycles; x++) {
gravObjects.forEach((proc, y) => {
gravObjects.forEach((read, z) => {
if (y === z) return;
['x', 'y', 'z'].forEach(l => {
if (proc.pos[l] > read.pos[l]) proc.vel[l]--;
else if (proc.pos[l] < read.pos[l]) proc.vel[l]++;
});
});
});
gravObjects.forEach(move => ['x', 'y', 'z'].forEach(l => move.pos[l] += move.vel[l]));
}
return {
gravObjects,
totalEnergy: gravObjects.reduce((r, i) =>
r + Object.values(i).reduce((rr, ii) =>
rr * Object.values(ii).reduce((rrr, iii) => rrr + Math.abs(iii), 0)
, 1)
, 0)
};
}
[
[`<x=-1, y=0, z=2>
<x=2, y=-10, z=-7>
<x=4, y=-8, z=8>
<x=3, y=5, z=-1>`, 10, 179],
[`<x=-8, y=-10, z=0>
<x=5, y=5, z=10>
<x=2, y=-7, z=3>
<x=9, y=-8, z=-3>`, 100, 1940]
].forEach((i,x) => {
console.assert(gravMachine(i[0], i[1]).totalEnergy === i[2], `Fail test #${x}`);
});
let bigData = `<x=-5, y=6, z=-11>
<x=-8, y=-4, z=-2>
<x=1, y=16, z=4>
<x=11, y=11, z=-4>`;
console.log(gravMachine(bigData, 1000));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment