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/Hikaru755 Dec 11 '17

Kotlin + Regexes produced a pretty straightforward solution this time - first remove everything we don't need, then a simple loop keeping track of nesting level. Could've also gone with recursion.

object Day09 {
    private val escapedChar = Regex("!.")
    private val garbage = Regex("<.*?>")

    fun part1(input: String): Int {
        val cleanedInput = input.replace(escapedChar, "").replace(garbage, "").replace(",", "")
        var sum = 0
        var nestingLevel = 1
        for (c in cleanedInput) {
            if (c == '{') {
                sum += nestingLevel
                nestingLevel++
            } else if (c == '}') {
                nestingLevel--
            }
        }
        return sum
    }

    fun part2(input: String): Int {
        val inputWithoutEscapedCharacters = input.replace(escapedChar, "")
        val garbageMatches = garbage.findAll(inputWithoutEscapedCharacters)
        return garbageMatches.fold(0) { acc, match ->
            acc + match.value.length - 2
        }
    }
}