Advertisement
Guest User

aoc 4

a guest
Dec 4th, 2016
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.50 KB | None | 0 0
  1. /// advent of code
  2. ///
  3. /// problem 4 part a + b
  4. pub static PROBLEM_NUMBER: &'static str = "4a";
  5.  
  6. use std::collections::BTreeMap;
  7.  
  8. fn rotate(input: &str, shift: u8) -> String {
  9.    String::from_utf8(
  10.        input.as_bytes().iter().map(|byte| {
  11.            ((byte - 97 + shift) % 26) + 97
  12.        }).collect::<Vec<u8>>()
  13.    ).unwrap_or("whoops, weird string data?".to_string())
  14. }
  15.  
  16.  
  17. pub fn adv_main(input: Vec<String>) {
  18.    let mut total: u64 = 0;
  19.  
  20.    for id in input {
  21.        let mut count: BTreeMap<char, u32> = BTreeMap::new();
  22.  
  23.        let mut parts: Vec<_> = id.split("-").collect();
  24.        let (rawid, chk) = parts.pop().unwrap().split_at(3);
  25.  
  26.        for c in parts.concat().chars() {
  27.            *count.entry(c).or_insert(0) += 1;
  28.        }
  29.  
  30.        let mut v: Vec<(char, u32)> = count.into_iter().collect();
  31.        v.sort_by(|a, b| b.1.cmp(&a.1));
  32.  
  33.        let s: String = v.into_iter().take(5).map(|(a, _)| a).collect();
  34.        
  35.        if s == &chk[1..6] {
  36.            let room_number: u64 = rawid.parse().unwrap();
  37.            let shift = room_number % 26;
  38.  
  39.            let desc = parts.iter().map(|word| rotate(word, shift as u8))
  40.                                   .collect::<Vec<_>>().join(" ");
  41.  
  42.            if desc.contains("pole") {
  43.                println!("problem b:");
  44.                println!("valid room no. {} - {}", room_number, desc);
  45.            }
  46.            total += room_number;
  47.        }
  48.  
  49.    }
  50.  
  51.    println!("total (problem a): {}", total);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement