A large stream blocks your path. According to the locals, it's not safe to cross the stream at the moment because it's full of garbage. You look down at the stream; rather than water, you discover that it's a stream of characters.
You sit for a while and record part of the stream (your puzzle input). The characters represent groups - sequences that begin with {
and end with }
. Within a group, there are zero or more other things, separated by commas: either another group or garbage. Since groups can contain other groups, a }
only closes the most-recently-opened unclosed group - that is, they are nestable. Your puzzle input represents a single, large group which itself contains many smaller ones.
Read the full puzzle.
using System.Collections.Generic;
using System.Linq;
namespace AdventOfCode.Y2017.Day09;
[ProblemName("Stream Processing")]
class Solution : Solver {
public object PartOne(string input) => BlockScores(input).Sum();
public object PartTwo(string input) => Classify(input).Where((x) => x.garbage).Count();
IEnumerable<int> BlockScores(string input) {
var score = 0;
foreach (var ch in Classify(input).Where((x) => !x.garbage).Select(x => x.ch)) {
if (ch == '}') {
score--;
} else if (ch == '{') {
score++;
yield return score;
}
}
}
IEnumerable<(char ch, bool garbage)> Classify(string input) {
var skip = false;
var garbage = false;
foreach (var ch in input) {
if (garbage) {
if (skip) {
skip = false;
} else {
if (ch == '>') {
garbage = false;
} else if (ch == '!') {
skip = true;
} else {
yield return (ch, garbage);
}
}
} else {
if (ch == '<') {
garbage = true;
} else {
yield return (ch, garbage);
}
}
}
}
}
Please ☆ my repo if you like it!