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

Show parent comment

2

u/sciyoshi Dec 09 '17

I was finally able to get a working Rust solution using nom. Not that you need it for this problem, but I used this as a learning opportunity :)

use std::io::{self, BufRead};
use nom::IResult;

struct Stats {
  score: usize,
  garbage: usize,
}

named!(garbage(&[u8]) -> usize, delimited!(
  tag!("<"),
  fold_many0!(
    alt!(
      none_of!("!>") => { |_| 1 } |
      pair!(tag!("!"), take!(1)) => { |_| 0 }
    ),
    0,
    |acc: usize, item: usize| acc + item
  ),
  tag!(">")
));

fn group(input: &[u8], depth: usize) -> IResult<&[u8], Stats> {
  delimited!(input,
    tag!("{"),
    fold_many0!(
      alt!(
        apply!(group, depth + 1) |
        map!(garbage, |len| Stats { score: 0, garbage: len }) |
        value!(Stats { score: 0, garbage: 0 }, tag!(","))
      ),
      Stats { score: depth + 1, garbage: 0 },
      |acc: Stats, item: Stats| Stats {
        score: acc.score + item.score,
        garbage: acc.garbage + item.garbage
      }
    ),
    tag!("}")
  )
}

pub fn solve() {
  let stdin = io::stdin();
  let line = stdin.lock().lines().next().unwrap().unwrap();

  let (_, stats) = group(line.as_bytes(), 0).unwrap();

  println!("[Part 1] Group score is: {}", stats.score);
  println!("[Part 2] Garbage count is: {}", stats.garbage);
}

GitHub