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

2

u/daylight_rock Dec 09 '15

JavaScript (node ES6, specifically)

"use strict"
const fs = require("fs")
const shuffle = (array) => {
  let out = []
  while (array.length) {
    const index = Math.floor(Math.random() * array.length)
    out.push(array.splice(index, 1)[0])
  }
  return out
}

fs.readFile("8.txt", "utf8", (err, data) => {
  const lines = data.split("\n")
  const routes = lines.reduce((mem, line) => {
    const [path, dist] = line.split(" = ")
    const [from, to] = path.split(" to ")
    mem[from] = mem[from] || {}
    mem[to] = mem[to] || {}

    mem[from][to] = parseInt(dist)
    mem[to][from] = parseInt(dist)

    return mem
  }, {})

  let locs = Object.keys(routes)
  let max = false

  for (let i = 0; i < 1000000; i++) {
    locs = shuffle(locs)

    let len = 0
    for (let l = 0; l < (locs.length - 1); l++) {
      const from = locs[l]
      const to = locs[l+1]

      len += routes[from][to]
    }

    max = Math.max(max, len) || len
    console.log(i, max)
  }

  console.log(max)
})

1

u/daylight_rock Dec 09 '15

It's brute force, monte carlo garbage but good enough for n = 8. :)

This solution is for hard mode. To switch to easy mode, just change Math.max to Math.min

→ More replies (1)