-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
91 lines (71 loc) · 2.14 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use std::fs;
use std::collections::HashMap;
fn read_file(file: &str) -> Vec<String> {
let list = fs::read_to_string(file)
.expect("file not found");
let tokens = list.split("");
tokens.map(|s| s.to_string()).collect::<Vec<String>>()
}
fn equal_ignore_case(a: &str, b: &str) -> bool{
a.eq_ignore_ascii_case(b)
}
fn react(token1: &String, token2: &String) -> bool {
if equal_ignore_case(token1, token2) {
return token1.to_string() != token2.to_string()
}
false
}
fn process(tokens: &mut Vec<String>) -> i32 {
let mut polymer: Vec<String> = Vec::new();
/* for: aBBa
* 1
* token = 'a'
* polymer ['a']
* tokens ['a', 'B', 'B' ]
*
* 2
* polymer ['a']
* tokens ['a', 'B', 'B' ]
* candidate = a
* token = 'B'
*
* polymer = ['a', 'B']
*
*/
while let Some(token) = tokens.pop() {
if polymer.is_empty() {
polymer.push(token);
continue;
}
let candidate = polymer.pop().unwrap();
if !react(&candidate, &token) {
polymer.push(candidate.to_string());
polymer.push(token.to_string());
}
}
polymer.len() as i32
}
/* Puzzle part two
*
*/
fn remove_unit(polymer: &Vec<String>, remove_chr: &str ) -> Vec<String> {
let mut filtered_polymer: Vec<String> = polymer.to_vec();
filtered_polymer.retain(|s| !equal_ignore_case(s, remove_chr) );
filtered_polymer
}
fn main() {
let mut code = read_file("./input.txt");
let mut cache : HashMap<String, bool> = HashMap::new();
code.retain(|s| !s.is_empty() && s.as_bytes()[0] != 10 );
println!("solution 1: {}", process(&mut code.to_vec()) );
let series = code.iter().map(|chr| {
if None == cache.get(&chr.to_ascii_lowercase()) {
let mut moded = remove_unit(&code, chr.as_str());
cache.insert(chr.to_ascii_lowercase(), true);
return process(&mut moded);
}
0x00beef
}).collect::<Vec<i32>>();
let minimum_reaction = series.iter().filter(|&n| *n != 0x00beef).min().unwrap();
println!("solution 2: {}", minimum_reaction);
}