Skip to content

Instantly share code, notes, and snippets.

@devNoiseConsulting
Last active January 3, 2018 03:28
Show Gist options
  • Select an option

  • Save devNoiseConsulting/7e9a671787d9035a588b182b3fb05620 to your computer and use it in GitHub Desktop.

Select an option

Save devNoiseConsulting/7e9a671787d9035a588b182b3fb05620 to your computer and use it in GitHub Desktop.
Particle Swarm - Advent of Code - 20171220
let particles = require('./particles');
let stepParticles = function(particles) {
return particles.map(p => {
p.v = p.v.map((c, i) => c + p.a[i]);
p.p = p.p.map((c, i) => c + p.v[i]);
return p;
});
};
let moveParticles_1 = function(particles) {
let positions;
for (let i = 0; i < 1000; i++) {
particles = stepParticles(particles);
}
return particles;
};
// Move Particles with collision detection
let moveParticles_2 = function(particles) {
let positions;
for (let i = 0; i < 1000; i++) {
particles = stepParticles(particles);
positions = particles.reduce((acc, p, i) => {
let location = p.p.join(',');
if (acc.hasOwnProperty(location)) {
acc[location].push(i);
} else {
acc[location] = [i];
}
return acc;
}, {});
Object.values(positions).forEach(location => {
if (location.length > 1) {
location.forEach(i => {
particles[i] = false;
});
}
});
particles = particles.filter(p => p);
}
return particles;
};
let moveParticles = moveParticles_2;
let findNearestParticle = function(particles) {
particles = moveParticles(particles);
particles = particles.map(
p => Math.abs(p.p[0]) + Math.abs(p.p[1]) + Math.abs(p.p[2])
);
let closest = Math.min(...particles);
return [particles.indexOf(closest), particles.filter(p => p).length];
};
let result;
result = findNearestParticle(particles);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment