DEV Community

Discussion on: Advent of Code 2019 Solution Megathread - Day 6: Universal Orbit Map

Collapse
 
mellen profile image
Matt Ellen • Edited

Bit late to the party on this one. With good reason, but also I kept making mistakes with how to add up the jumps.

Got there eventually.

Part 2 first:

function orbitsToSanta()
{
    let pretext = document.getElementsByTagName('pre')[0].innerHTML;
    let orbits = pretext.split('\n').filter(o=>o!=='');
    let orbithash = {};
    let meorbit = '';
    let sanorbit = '';

    for(let orbit of orbits) 
    {
        orbithash[orbit] = new leaf(orbit);
    }

    for(let orbit of orbits) 
    {
        let [main, sub] = orbit.split(')');
        if(sub === 'YOU')
        {
            meorbit = orbit;
        }
        if(sub === 'SAN')
        {
            sanorbit = orbit;
        }
        let parent = orbits.filter(oo =>
                                   {
                                       let [othermain, othersub] = oo.split(')');
                                       return main === othersub;
                                   })[0];
        if(typeof(parent) !== 'undefined')//root node has no parent. 
        {
            orbithash[orbit].parent = orbithash[parent];
        }
    }

    let melist = orbithash[meorbit].listOrbits();
    let sanlist = orbithash[sanorbit].listOrbits();
    // hco is Highest Common Orbit
    let hco = melist.filter(o => sanlist.indexOf(o) > -1).slice(-1)[0];
    let hcolist = orbithash[hco].listOrbits();

    let melength = melist.filter(l => hcolist.indexOf(l) === -1).length - 1; // minus 1 because you exclude the current orbit.
    let sanlength = sanlist.filter(l => hcolist.indexOf(l) === -1).length - 1; // minus 1 because the hco is already counted.

    return melength+sanlength;
}

function leaf(orbit) 
{
    this.orbit = orbit;
    this.parent = null;
}

leaf.prototype.orbitCounts = function()
{
    let count = 1;

    if(this.parent !== null)
    {
        count = 1 + this.parent.orbitCounts();
    }

    return count;
};

leaf.prototype.listOrbits = function() 
{
    if(this.parent === null) 
    {
        return [];
    }

    let pos = this.parent.listOrbits();

    pos.push(this.orbit);

    return pos;
};

Part 1 had the following code in place of the number of jumps calculation:

    let counts = 0;

    for(let orbit of orbits)
    {
        counts += orbithash[orbit].orbitCounts();
    }

    return counts;