Browse Source

Day 5 part 2

Tyler Hallada 5 years ago
parent
commit
57d8189964
2 changed files with 23 additions and 0 deletions
  1. 22 0
      src/day5.rs
  2. 1 0
      src/main.rs

+ 22 - 0
src/day5.rs

@@ -3,16 +3,23 @@ extern crate regex;
3 3
 use std::error::Error;
4 4
 use std::fs::File;
5 5
 use std::io::{BufRead, BufReader};
6
+use std::collections::HashMap;
6 7
 
7 8
 use regex::Regex;
8 9
 
9 10
 const INPUT: &str = "inputs/5.txt";
11
+const UNITS: &str = "abcdefghijklmnopqrstuvwxyz";
10 12
 
11 13
 pub fn solve_part1() -> Result<usize, Box<Error>> {
12 14
     let polymer = read_polymer(INPUT)?;
13 15
     Ok(reduce_polymer_completely(polymer).len())
14 16
 }
15 17
 
18
+pub fn solve_part2() -> Result<usize, Box<Error>> {
19
+    let polymer = read_polymer(INPUT)?;
20
+    Ok(find_shortest_unit_eliminated_polymer(polymer))
21
+}
22
+
16 23
 fn read_polymer(filename: &str) -> Result<String, Box<Error>> {
17 24
     let file = File::open(filename)?;
18 25
     let polymer = BufReader::new(file).lines().next().unwrap_or(Ok("".to_string()));
@@ -39,6 +46,16 @@ fn reduce_polymer_completely(polymer: String) -> String {
39 46
     }
40 47
 }
41 48
 
49
+fn find_shortest_unit_eliminated_polymer(polymer: String) -> usize {
50
+    let mut eliminated_unit_polymers = HashMap::new();
51
+    for unit in UNITS.chars() {
52
+        let test_polymer = polymer
53
+            .replace(unit, "")
54
+            .replace(unit.to_ascii_uppercase(), "");
55
+        eliminated_unit_polymers.insert(unit, reduce_polymer_completely(test_polymer).len());
56
+    }
57
+    *eliminated_unit_polymers.iter().min_by_key(|&(_, len)| len).unwrap().1
58
+}
42 59
 
43 60
 #[cfg(test)]
44 61
 mod tests {
@@ -67,4 +84,9 @@ mod tests {
67 84
     fn reads_polymer() {
68 85
         assert_eq!(read_polymer(TEST_INPUT).unwrap(), "dabAcCaCBAcCcaDA");
69 86
     }
87
+
88
+    #[test]
89
+    fn finds_shortest_unit_eliminated_polymer() {
90
+        assert_eq!(find_shortest_unit_eliminated_polymer("dabAcCaCBAcCcaDA".to_string()), 4);
91
+    }
70 92
 }

+ 1 - 0
src/main.rs

@@ -22,4 +22,5 @@ fn main() {
22 22
     println!("{}", day4::solve_part2().unwrap());
23 23
     println!("Day 5:");
24 24
     println!("{}", day5::solve_part1().unwrap());
25
+    println!("{}", day5::solve_part2().unwrap());
25 26
 }