Skip to content

Instantly share code, notes, and snippets.

@cloudrac3r
Last active December 8, 2019 05:25
Show Gist options
  • Save cloudrac3r/2dfc25612d31c27703303d8f4b6fe60a to your computer and use it in GitHub Desktop.
Save cloudrac3r/2dfc25612d31c27703303d8f4b6fe60a to your computer and use it in GitHub Desktop.
Advent of Code 2019 day 6 solution (both parts)
const {read} = require("../util/read")
class SpaceJunk {
constructor(name) {
this.name = name
/** @type {SpaceJunk} */
this.parent = null
this.children = []
}
setParent(parent) {
this.parent = parent
this.parent.children.push(this)
}
countOrbiting() {
if (this.parent) return this.parent.countOrbiting()+1
else return 0
}
/**
* @returns {SpaceJunk[]}
*/
enumerateParents() {
if (this.parent) return [this.parent].concat(this.parent.enumerateParents())
else return []
}
/**
* @param {SpaceJunk} base
* @param {SpaceJunk} alter
*/
static findClosestSharedNode(base, alter) {
const baseTree = base.enumerateParents()
const alterTree = alter.enumerateParents()
const join = alterTree.find(junk => baseTree.includes(junk))
return baseTree.indexOf(join) + alterTree.indexOf(join)
}
}
class Universe {
constructor() {
/** @type {Map<string, SpaceJunk>} */
this.nodes = new Map()
}
get(name) {
return this.nodes.get(name)
}
getOrCreateNode(name) {
if (this.nodes.has(name)) {
return this.nodes.get(name)
} else {
const newNode = new SpaceJunk(name)
this.nodes.set(name, newNode)
return newNode
}
}
countAllOrbits() {
return [...this.nodes.values()].reduce((a, c) => a + (c.countOrbiting()), 0)
}
}
function loadUniverse(file) {
const lines = read(file).asLines()
const universe = new Universe()
lines.forEach(line => {
const [orbited, orbiter] = line.split(")").map(name => universe.getOrCreateNode(name))
orbiter.setParent(orbited)
})
return universe
}
function countAllOrbiting(file) {
const universe = loadUniverse(file)
return universe.countAllOrbits()
}
function countTransfers(file) {
const universe = loadUniverse(file)
//console.log(universe.get("YOU").enumerateParents())
return SpaceJunk.findClosestSharedNode(universe.get("SAN"), universe.get("YOU"))
}
module.exports.countAllOrbiting = countAllOrbiting
module.exports.countTransfers = countTransfers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment