DEV Community

Discussion on: Advent of Code 2019 Solution Megathread - Day 12: The N-Body Problem

Collapse
 
maxart2501 profile image
Massimo Artizzu • Edited

Finally got the second part! 🥳

I actually had the right idea right off the bat, but I tried to cut the corners thinking if would have been too cumbersome... It turned out it was the opposite! 😄

But... Let's start with

Part One

This was fairly simple. All we had to do is to write a function that takes a step and evolves it into the next one. I used a JavaScript generator again, because why the heck not:

const coordRE = /<x=(-?\d+), y=(-?\d+), z=(-?\d+)>/;
function* getStates() {
  // Every satellite state is a vector of six numbers
  let satellites = input.trim().split('\n').map(line => ([
    ...line.match(coordRE).slice(1).map(Number),
    0, 0, 0
  ]));
  while (true) {
    satellites = satellites.map(satellite => {
      const velocity = satellite.slice(3);
      const nextVelocity = velocity.map((value, index) => {
        return satellites.reduce((diff, sat) => {
          return diff + Math.sign(sat[index] - satellite[index])
        }, value);
      });
      const nextPosition = satellite.slice(0, 3).map((value, index) => value + nextVelocity[index]);
      return [
        ...nextPosition,
        ...nextVelocity
      ];
    });
    yield satellites;
  }
}

function getTaxiDriverLength(vector) {
  return vector.reduce((sum, length) => sum + Math.abs(length), 0);
}

function getTotalEnergy(satellites) {
  return satellites.reduce((total, satellite) => {
    return total +
      getTaxiDriverLength(satellite.slice(0, 3)) *
      getTaxiDriverLength(satellite.slice(3));
  }, 0)
}

const states = getStates();
let satellites;
for (let i = 0; i < 1000; i++) {
  ({ value: satellites } = states.next());
}
console.log(getTotalEnergy(satellites));

I don't think there's much to say here...

Part Two

Now it comes the tricky part... My solution is 332477126821644 (~3.3e14), yours will be similar in size, so brute force is out of question.

I thought that this system is quite chaotic, but not that much chaotic, so satelite configurations could have a shorter period. When all 4 periods are found, all I had to do was to compute the least common multiple and I would have been golden! Right?

Well, in theory. In practice, I couldn't find the period of any of my satellites after one billion cycles, so that was no good. The next attempt consisted in splitting a satellite's state into position and velocity vectors, hoping that would have reduced their periods enough. And it did, but... that led me to a very high result.

Note that a "period" at that time consisted in the step number of the first time a vector was equal to the respective initial value. That's wrong too. For instance, in the first given example (with a period of 2772), the position of Europa (the second satellite) was the same of the initial position after 616, 1232, 1539, 2155, 2771 and 2772 steps. No clear period was evident.

But computing the differences between step marks gives the following sequence: 616, 616, 307, 616, 616, 1, 616, 616, 307, 616, 616, 1, 616, 616, 307, 616, 616, 1, 616... and so on. Grouping these numbers every 6 gives us a period of exactly 2772 steps. So I made this function to compute the period of a given array of (distances between) marks:

function getPeriod(distances) {
  for (let length = 1; length <= distances.length; length++) {
    const sums = [];
    const limit = distances.length - distances.length % length;
    for (let i = 0; i < limit; i += length) {
      let sum = 0;
      for (let j = 0; j < length; j++) {
        sum += distances[i + j];
      }
      sums.push(sum);
    }
    // If every sum is the same, then that sum is *probably* the period
    if (sums.length > 0 && sums.every(sum => sum === sums[0])) {
      return sums[0];
    }
  }
}

The following correction was to split everything down to every single vector component, and started marking all the occurences of a value equalling the initial value. And lo and behold, periods started to come out after "just" one million iterations! This is the last part of my script:

const states = getStates();
let { value: satellites } = states.next();
const initialStates = satellites.flatMap(satellite => [ ...satellite ]);
const marks = initialStates.map(() => new Set());

for (let i = 1; i < 1e6; i++) {
  ({ value: satellites } = states.next());
  satellites.forEach((satellite, index) => {
    for (let j = 0; j < 6; j++) {
      if (satellite[j] === initialStates[index * 6 + j]) {
        marks[index * 6 + j].add(i);
      }
    }
  });
}

const markDistances = marks.map(
  set => Array.from(set).map((mark, i) => mark - (i ? marks[i - 1] : 0))
);
console.log([ ...new Set(markDistances.map(getPeriod)) ].join(' '));

I admit that I actually did not compute the least common multiple. That problem wasn't interesting and I just used an online calculator to get the final result 😂

As usual, text, complete solutions and input are on my repo.

Tomorrow... IntCodes?