r/adventofcode • • Dec 09 '15

SOLUTION MEGATHREAD --- Day 9 Solutions ---

This thread will be unlocked when there are a significant amount of people on the leaderboard with gold stars.

edit: Leaderboard capped, achievement thread unlocked!

We know we can't control people posting solutions elsewhere and trying to exploit the leaderboard, but this way we can try to reduce the leaderboard gaming from the official subreddit.

Please and thank you, and much appreciated!


--- Day 9: All in a Single Night ---

Post your solution as a comment. Structure your post like previous daily solution threads.

11 Upvotes

178 comments sorted by

View all comments

Show parent comment

1

u/elite_killerX Dec 09 '15

Pretty much what I did. I had to do the permutations myself, though (NodeJS):

'use strict';

const fs = require('fs');

const input = fs.readFileSync('./input', 'utf8');
// const input = `
// London to Dublin = 464
// London to Belfast = 518
// Dublin to Belfast = 141
// `;

const distances = {};

input.trim().split('\n').forEach(item => {
  let match = item.match(/^(\w+) to (\w+) = (\d+)/);
  if (match) {
    distances[match[1]] = distances[match[1]] || {};
    distances[match[1]][match[2]] = parseInt(match[3]);
    distances[match[2]] = distances[match[2]] || {};
    distances[match[2]][match[1]] = parseInt(match[3]);
  }
});

function permute(array) {
  if (array.length > 1) {
    let newArray = [];
    array.forEach((item, index) => {
      permute(array.slice(0, index).concat(array.slice(index + 1))).forEach(newSubArray => {
        newArray.push([item].concat(newSubArray));
      });
    });
    return newArray;
  } else {
    return array;
  }
}

let routes = permute(Object.keys(distances)).map(route => {
  return route.reduce((memo, location) => {
    return {
      prevLoc: location,
      totalDistance: memo.totalDistance + (memo.prevLoc ? distances[memo.prevLoc][location] : 0)
    }
  }, {prevLoc: null, totalDistance: 0}).totalDistance;
});

let shortestRoute = routes.reduce((memo, route) => route < memo ? route : memo, 999999999999999);
let longestRoute = routes.reduce((memo, route) => route > memo ? route : memo, 0);

console.log('Part 1:', shortestRoute);
console.log('Part 2:', longestRoute);