-
Notifications
You must be signed in to change notification settings - Fork 0
/
day5.rs
87 lines (71 loc) · 1.9 KB
/
day5.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
//! [Day 5: Alchemical Reduction](https://adventofcode.com/2018/day/5)
// Return true if same letter and different cases
fn react(a: char, b: char) -> bool {
a.to_ascii_lowercase() == b.to_ascii_lowercase() && a.is_lowercase() ^ b.is_lowercase()
}
fn react_polymer(polymer: &[char]) -> usize {
let mut polymer = polymer.to_owned();
let mut i = 0;
while i < polymer.len() - 1 {
if react(polymer[i], polymer[i + 1]) {
polymer.remove(i);
polymer.remove(i);
i = i.saturating_sub(1);
} else {
i += 1;
}
}
polymer.len()
}
struct Puzzle {
polymer: Vec<char>,
}
impl Puzzle {
fn new() -> Puzzle {
Puzzle { polymer: vec![] }
}
/// Get the puzzle input.
fn configure(&mut self, path: &str) {
let data = std::fs::read_to_string(path).unwrap();
self.polymer = data.trim().chars().collect();
}
/// Solve part one.
fn part1(&self) -> usize {
react_polymer(&self.polymer)
}
/// Solve part two.
fn part2(&self) -> usize {
('a'..='z')
.map(|unit| {
let mut polymer = self.polymer.clone();
polymer.retain(|c| c.to_ascii_lowercase() != unit);
react_polymer(&polymer)
})
.min()
.unwrap()
}
}
fn main() {
let args = aoc::parse_args();
let mut puzzle = Puzzle::new();
puzzle.configure(args.path.as_str());
println!("{}", puzzle.part1());
println!("{}", puzzle.part2());
}
/// Test from puzzle input
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test01() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part1(), 10);
}
#[test]
fn test02() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part2(), 4);
}
}