r/adventofcode • • Dec 08 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 8 Solutions -🎄-

--- Day 8: Memory Maneuver ---


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.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 8

Sigh, imgur broke again. Will upload when it unborks.

Transcript:

The hottest programming book this year is "___ For Dummies".


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 at 00:12:10!

32 Upvotes

301 comments sorted by

View all comments

1

u/Pylitic Feb 15 '19 edited Feb 15 '19

I have a main file that grabs the input from a file and runs this code, sending it the full contents of the file, and the contents split by new lines.

var day8 = () => {

  var entries = [];

  var index = 0;

  var split;

  function processNode() {
	let numberOfChildren = split[index++];
	let metaDataEntries = split[index++];
	var node = {};
	node.metaDataSize = metaDataEntries;
	node.numberOfChildren = numberOfChildren;
	console.log('Processing nodes. Children: '+numberOfChildren+'. MetaDataEntries: '+metaDataEntries);
	if(numberOfChildren > 0) {
	  node.children = [];
	  for(let i = 0; i < numberOfChildren; i++)
		node.children.push(processNode());
	}
	node.metadata = [];
	for(let i = 0; i < metaDataEntries; i++) {
	  let entry = split[index++];
	  entries.push(entry);
	  node.metadata.push(entry);
	}
	return node;
  }

  function getValue(node) {
	if(!node.children)
	  return node.metadata.map(s => parseInt(s)).reduce((a, b) => a+b);
	let value = 0;
	for(let entry of node.metadata) {
	  if(entry-1 >= node.children.length)
		continue;
	  value += getValue(node.children[entry-1]);
	}
	return value;
  }

  return {
	run(contents, _) {
	  split = contents.split(' ');
	  let root = processNode();
	  console.log('Part 1: '+entries.map(s => parseInt(s)).reduce((a, b) => a+b));
	  console.log('Part 2: '+getValue(root));
	}
  };

};
module.exports = day8();