|
@@ -0,0 +1,70 @@
|
|
1
|
+extern crate regex;
|
|
2
|
+
|
|
3
|
+use std::error::Error;
|
|
4
|
+use std::fs::File;
|
|
5
|
+use std::io::{BufRead, BufReader};
|
|
6
|
+
|
|
7
|
+use regex::Regex;
|
|
8
|
+
|
|
9
|
+const INPUT: &str = "inputs/5.txt";
|
|
10
|
+
|
|
11
|
+pub fn solve_part1() -> Result<usize, Box<Error>> {
|
|
12
|
+ let polymer = read_polymer(INPUT)?;
|
|
13
|
+ Ok(reduce_polymer_completely(polymer).len())
|
|
14
|
+}
|
|
15
|
+
|
|
16
|
+fn read_polymer(filename: &str) -> Result<String, Box<Error>> {
|
|
17
|
+ let file = File::open(filename)?;
|
|
18
|
+ let polymer = BufReader::new(file).lines().next().unwrap_or(Ok("".to_string()));
|
|
19
|
+ Ok(polymer?)
|
|
20
|
+}
|
|
21
|
+
|
|
22
|
+fn reduce_polymer(polymer: &String) -> String {
|
|
23
|
+ lazy_static! {
|
|
24
|
+ static ref REACTING_UNITS: Regex = Regex::new(concat!(
|
|
25
|
+ r"aA|bB|cC|dD|eE|fF|gG|hH|iI|jJ|kK|lL|mM|nN|",
|
|
26
|
+ r"oO|pP|qQ|rR|sS|tT|uU|vV|wW|xX|yY|zZ|",
|
|
27
|
+ r"Aa|Bb|Cc|Dd|Ee|Ff|Gg|Hh|Ii|Jj|Kk|Ll|Mm|Nn|",
|
|
28
|
+ r"Oo|Pp|Qq|Rr|Ss|Tt|Uu|Vv|Ww|Xx|Yy|Zz")).unwrap();
|
|
29
|
+ }
|
|
30
|
+ REACTING_UNITS.replace_all(&polymer, "").to_string()
|
|
31
|
+}
|
|
32
|
+
|
|
33
|
+fn reduce_polymer_completely(polymer: String) -> String {
|
|
34
|
+ let reduced = reduce_polymer(&polymer);
|
|
35
|
+ if reduced == polymer {
|
|
36
|
+ reduced
|
|
37
|
+ } else {
|
|
38
|
+ reduce_polymer_completely(reduced)
|
|
39
|
+ }
|
|
40
|
+}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+#[cfg(test)]
|
|
44
|
+mod tests {
|
|
45
|
+ use super::*;
|
|
46
|
+
|
|
47
|
+ const TEST_INPUT: &str = "inputs/5_test.txt";
|
|
48
|
+
|
|
49
|
+ #[test]
|
|
50
|
+ fn reduces_polymer() {
|
|
51
|
+ assert_eq!(reduce_polymer(&"aA".to_string()), "");
|
|
52
|
+ assert_eq!(reduce_polymer(&"aAbB".to_string()), "");
|
|
53
|
+ assert_eq!(reduce_polymer(&"aAfgbB".to_string()), "fg");
|
|
54
|
+ assert_eq!(reduce_polymer(&"abAB".to_string()), "abAB");
|
|
55
|
+ assert_eq!(reduce_polymer(&"aabAAB".to_string()), "aabAAB");
|
|
56
|
+ assert_eq!(reduce_polymer(&"dabAcCaCBAcCcaDA".to_string()), "dabAaCBAcaDA");
|
|
57
|
+ assert_eq!(reduce_polymer(&"dabAaCBAcCcaDA".to_string()), "dabCBAcaDA");
|
|
58
|
+ assert_eq!(reduce_polymer(&"dabCBAcCcaDA".to_string()), "dabCBAcaDA");
|
|
59
|
+ }
|
|
60
|
+
|
|
61
|
+ #[test]
|
|
62
|
+ fn reduces_polymer_completely() {
|
|
63
|
+ assert_eq!(reduce_polymer_completely("dabAcCaCBAcCcaDA".to_string()), "dabCBAcaDA");
|
|
64
|
+ }
|
|
65
|
+
|
|
66
|
+ #[test]
|
|
67
|
+ fn reads_polymer() {
|
|
68
|
+ assert_eq!(read_polymer(TEST_INPUT).unwrap(), "dabAcCaCBAcCcaDA");
|
|
69
|
+ }
|
|
70
|
+}
|