Advertisement
Guest User

Advent of Code 2016 Day 9 part 2

a guest
Dec 9th, 2016
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.70 KB | None | 0 0
  1. #![allow(unused_imports)]
  2. #![allow(dead_code)]
  3. extern crate regex;
  4. use regex::Regex;
  5. use std::collections::{HashMap, HashSet};  
  6. use std::io;
  7.  
  8. fn read_line() -> String {
  9.     let mut input = String::new();
  10.     io::stdin().read_line(&mut input).unwrap();
  11.     input.trim_right().to_owned()
  12. }
  13.  
  14. fn parse_usize<'a, T: Into<&'a str>>(s: T) -> usize {
  15.     s.into().parse().unwrap()
  16. }  
  17.  
  18. fn decompress(s: &str) -> usize {
  19.     let mut out = 0;
  20.     let mut cur_slice = s;
  21.     loop {
  22.         match cur_slice.find('(') {
  23.             Some(pos) => {
  24.                 out += pos;
  25.                 cur_slice = &cur_slice[pos..];
  26.                 match cur_slice.find(')') {
  27.                     Some(pos) => {
  28.                         let enc = &cur_slice[1..pos];
  29.                         cur_slice = &cur_slice[pos+1..];
  30.                         let xpos = enc.find('x').unwrap();
  31.                         let cnt = parse_usize(&enc[0..xpos]);
  32.                         let rep = parse_usize(&enc[xpos+1..]);
  33.                         let replen = decompress(&cur_slice[0..cnt]);
  34.                         out += rep * replen;
  35.                         cur_slice = &cur_slice[cnt..];
  36.                     },
  37.                     _ => unreachable!(),
  38.                 }
  39.             },
  40.             _ => {
  41.                 out += cur_slice.len();
  42.                 break;
  43.             },
  44.         }
  45.     }
  46.     out
  47. }
  48.  
  49. fn main() {
  50.     let mut sum = 0;
  51.     let mut input = "".to_string();
  52.     loop {
  53.         let line = read_line();
  54.         if line.is_empty() { break };
  55.         input.push_str(&line[..]);
  56.     };
  57.     input.replace(char::is_whitespace,"");
  58.     let out = decompress(&input[..]);
  59.  
  60.     println!("{:?}", out);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement