// starMap defined as above...constgetAncestors=body=>bodyinstarMap?[...getAncestors(starMap[body]),starMap[body]]:[];constyouAncestors=getAncestors('YOU');constsantaAncestors=getAncestors('SAN');consttransfers=youAncestors.filter(body=>santaAncestors.includes(body)).map(body=>[// .reverse is actually not necessary......youAncestors.slice(youAncestors.indexOf(body)).reverse(),// + 1 because we'd include the common planet twice...santaAncestors.slice(santaAncestors.indexOf(body)+1)]);// - 1 because we're counting the movements, not the positionsconsole.log(Math.min(...transfers.map(xfer=>xfer.length-1)));
Finally a nice and short one.
My solutions aren't particularly efficient as they involve recursive functions, but still run pretty fast so whatever. ¯\_(ツ)_/¯
Part 1
Part 2
You can find my solutions on GitHub.
Maybe a future node version will add tail call optimization, and Javascript could have efficient recursion again.
Tail recursive functions are so much clearer to me than a while loop... something about walking down to a trivial solution just makes sense. 🤷♀️
I long the day they will tackle the problem once and for all. It's the last thing missing from ES2015! (Only Safari supports it.)