-
Notifications
You must be signed in to change notification settings - Fork 0
/
day2.rs
88 lines (76 loc) · 2.02 KB
/
day2.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
//! [Day 2: Inventory Management System](https://adventofcode.com/2018/day/2)
struct Puzzle {
data: String,
}
impl Puzzle {
fn new() -> Puzzle {
Puzzle {
data: String::new(),
}
}
/// Get the puzzle input.
fn configure(&mut self, path: &str) {
let data = std::fs::read_to_string(path).unwrap();
self.data = data;
}
/// Solve part one.
fn part1(&self) -> u32 {
let mut two = 0;
let mut three = 0;
for line in self.data.lines() {
let mut has_two = 0;
let mut has_three = 0;
for letter in 'a'..='z' {
let n = line.chars().filter(|x| x == &letter).count();
match n {
2 => has_two = 1,
3 => has_three = 1,
_ => (),
}
}
two += has_two;
three += has_three;
}
two * three
}
/// Solve part two.
fn part2(&self) -> String {
for l in self.data.lines() {
for r in self.data.lines() {
let same: String = l
.chars()
.zip(r.chars())
.filter_map(|x| if x.0 == x.1 { Some(x.0) } else { None })
.collect();
if same.len() == l.len() - 1 {
return same;
}
}
}
"?".to_string()
}
}
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("test1.txt");
assert_eq!(puzzle.part1(), 12);
}
#[test]
fn test02() {
let mut puzzle = Puzzle::new();
puzzle.configure("test2.txt");
assert_eq!(puzzle.part2(), "fgij".to_string());
}
}