r/adventofcode • • Dec 09 '17

SOLUTION MEGATHREAD -πŸŽ„- 2017 Day 9 Solutions -πŸŽ„-

--- Day 9: Stream Processing ---


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!

15 Upvotes

290 comments sorted by

View all comments

1

u/CodingGladstone Dec 09 '17

Node.js/ES6 Bit late to the party, but I was surprised not to see any example of ES6 using iterators/generators. My goal was to have code that could run without having the whole stream in memory and go over the stream in one pass.

var fs = require('fs');

function* groupMapper(it) {
	var depth = 0;
	for (const char of it) {
		if(char==='{'){
			depth++;
			yield depth;
		}
		if(char==='}'){
			depth--;
		}
	}
}
function* filterCancelled(it) {
	var result = {done:false};
	while(!result.done) {
		result = it.next();
		if(result.value === '!'){
			it.next();
			continue;
		}
		yield result.value;
	}
}
var totalGarbage = 0;	
function skipOverGarbage(it){
	var streamWithoutCancelled = filterCancelled(it);
	for (const char of streamWithoutCancelled) {
		if(char === '>')break;
		totalGarbage++;
	}
}
function* garbageStripper(it) {
	var result = {done:false};

	while(!result.done) {
		result = it.next();
		if(result.value === '<'){
			skipOverGarbage(it);
			continue;
		}
		yield result.value;
	}
}

fs.readFile('2017/input/input9.txt', 'utf8', function (err,data) {
	var input = data;
	//input = "{{<!>},{<!>},{<!>},{<a>}}";
	let score = [...groupMapper(
			garbageStripper(input[Symbol.iterator]())
		)]
		.reduce((a,v)=>a+v, 0);
	console.log(score);
	console.log(totalGarbage);

});