AoC 2019 D12: The N-Body Problem
| Problem statement | Source code | Tags: PuzzlePeriod findingPhysics
← Previous Back to AoC Index Next →
Part 1
I had a bit of fun with this one. It could be done in a more boring way, but I used some OOP by making each Moon an object with position and velocity members, and methods to apply gravity from another moon, update its position, and compute its energy. Then, I just pairwise apply gravity, and then update each one's position:
Part 2
I thought I could just let the simulation run for a while, but it turns out that the cycle is over steps. (Ballpark: anything over is too big to brute force in a reasonable time.) However, note that updates in each dimension are independent of the others. So I can just find the cycle length for each dimension separately, then take the least common multiple (LCM) of the three cycle lengths. The cycle finding code looks like this:
Note that because the update is bijective, if we see a state again, it must be the initial state; otherwise, we would have two distinct previous states that map to the same cycle-start state, which is impossible. So x_cycle is just t and we don't need to store the time we saw each state.