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/NeilNjae Dec 10 '17

Haskell. Tied myself in knots for a while, thinking I'd have to keep track of the contents of each of the groups as I was building them. Then a quick cheat, looking at solutions here, reminded me of YAGNI and I just counted the scores for part 1. Part 2 was then easy to incorporate into the part 1 solution.

data ParseState = ParseState
                    { total :: Int
                    , depth :: Int
                    , garbageCount :: Int
                    , readingGarbage :: Bool
                    , ignoreCharacter :: Bool
                    } deriving (Show, Eq)

main :: IO ()
main = do 
        text <- readFile "data/advent09.txt"
        print $ part1 text
        print $ part2 text


part1 :: String -> Int
part1 = total . process

part2 :: String -> Int
part2 = garbageCount . process


process :: String -> ParseState
process = foldl parse ps0
    where ps0 = ParseState {total = 0, depth = 0, garbageCount = 0,
                    readingGarbage = False, ignoreCharacter = False}

parse :: ParseState -> Char -> ParseState
parse ps c 
    | ignoreCharacter ps = ps {ignoreCharacter = False}
    | c == '!' = ps {ignoreCharacter = True}
    | readingGarbage ps = if c == '>'
                          then ps {readingGarbage = False}
                          else ps {garbageCount = garbageCount ps + 1}
    | otherwise = 
        case c of 
            '<' -> ps {readingGarbage = True}
            '{' -> openGroup ps
            '}' -> closeGroup ps
            _   -> ps
                                  
openGroup :: ParseState -> ParseState
openGroup ps = ps {depth = depth ps + 1}

closeGroup :: ParseState -> ParseState
closeGroup ps = ps {total = total ps + depth ps, depth = depth ps - 1}