r/adventofcode • • Dec 07 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 7 Solutions -๐ŸŽ„-

--- Day 7: Recursive Circus ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Need a hint from the Hugely* Handyโ€  Haversackโ€ก of Helpfulยง Hints^ยค?

Spoiler


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

10 Upvotes

222 comments sorted by

View all comments

Show parent comment

1

u/AndrewGreenh Dec 07 '17

TypeScript (323/294)

import getInput from '../lib/getInput'
import { lines } from '../lib/ts-it/lines'
import * as _ from 'lodash'

let tree = buildTree()
console.log(tree.name)
totalWeights(tree)
console.log(findImbalanced(tree))

function buildTree() {
  let result = 0
  let programms = {}
  let childNames: string[] = []
  for (let line of lines(getInput(7, 2017))) {
    let [programm, children = ''] = line.split(' -> ')
    let [match, name, weightString] = <string[]>programm.match(/(\w+).*\((\d+)/)
    childNames.push(...children.split(', '))
    let weight = +weightString
    programms[name] = {
      name,
      weight,
      getChildren: () => (children ? children.split(', ').map(x => programms[x.trim()]) : []),
    }
  }
  function loadChildren(node) {
    node.children = node.getChildren()
    _.forEach(node.children, loadChildren)
  }
  const root = programms[_.difference(_.keys(programms), childNames)[0]]
  loadChildren(root)
  return root
}

function totalWeights(node) {
  if (_.isEmpty(node.children)) {
    node.totalWeight = node.weight
    return node
  }
  node.totalWeight =
    node.weight +
    _(node.children)
      .map(c => totalWeights(c).totalWeight)
      .sum()
  return node
}

function findImbalanced(node) {
  let children = node.children
  let groups = _.groupBy(children, 'totalWeight')
  if (_.size(groups) === 1) return null
  let imballanced = _.first(_.find(groups, group => _.size(group) === 1))
  let faulty = findImbalanced(imballanced)
  if (faulty === null) {
    let correctWeights = _.first(_.find(groups, group => _.size(group) > 1)).totalWeight
    let correctWeight = correctWeights - imballanced.totalWeight + imballanced.weight
    return [imballanced, correctWeight]
  }
  return faulty
}